FUNCTIONS
Certain operations or calculations are repeated at many points, this can be achieved by writing the statements in a function that can be called wherever required. This way if a program is split into a number of such user defined functions, then it becomes easy to understand the program and even to debug it, as programmer has to deal with the only part not working upto mark.
A function consists of:
Function definition
Function call
Function declaration
1. Function definition:
It consists of function header and function body.
(a)Function header:
The function header consists of function type, function name and list of parameter (arguments).
Function type is data type of value that the function is expected to return to the calling function.
If it is not going to return any value, we have to type void (which is a fundamental data type). Which we have to explicitly write as if data type is not mentioned then by default it is considered to be int.
Function name is any valid C identifier i.e. it should not be a keyword etc.
Formal parameter (arguments) are the variables that will receive the data from calling function and serve as input data to function to carry out specified task.
The list consists of declaration of data type & names of variables separated by comma.
If the function is not expected to receive any data, we can type void in parenthesis or even we can just give empty parenthesis.
(b) The function body:
The function body contains declaration of local variables and statements enclosed in braces. Generally at end of function body, a return statement is typed. This
statement returns the results, of operations performed on arguments, to the calling function.
If the function is not to return the value then this return statement is omitted.
General form of function definition is
Function_type function_name (parameter_list) {
body of function }
2. Function call:
The defined function can be called any time and as many times in the main function or even in any other function.
The function call basically consists just the name of function.
If calling function is expected to send any value to the called function then these values are to be written in parenthesis after name of function. Care should be taken that argument types and order and number should match exactly with the types and order and number of formal argument.
Actual arguments can be values, variables or expressions. But if no argument is to
be transmitted then empty parenthesis should be given.
If the called function is expected to return the value then function call should be the right hand side of an equation having left side a variable that will be assigned the value returned by called function.
3. Function declaration:
Like variables all functions should be declared before using them. The syntax of function prototype (declaration) is
Function_type function_name (parameter list)
The function type is the data type of value that function is expected to return.
Function name must be valid identifier. Parameter list consists of data type and names of variable which should match with the parameters in function definition.
In declaration we may just declare the data type skipping the names of arguments.
(Note: If function definition is before ‘main' then it serves the declaration as well hence declaration can be omitted.)
Categories of functions:
There are four categories of functions:
1. Function with no argument and no return value.
2. Function with argument with no return value.
3. Function with no argument but return value.
4. Function with argument and return value.
1.Function with no argument and no return value:
This function does not receive any data from the calling function and does not send any value to calling function. Thus there is no data transfer between calling and called function.
Program : WAP that accepts two numbers , finds their sum and prints it using function with no argument no return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void add(void);
void main() {
clrscr();
add();
getch();
}
void add(void) {
int a,b,c;
printf(“please enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum is %d”,c);
}
2. Function with argument and no return value:
This function receives the same data from the calling function but does not send any result (as value) back to calling function.
Program: WAP that accepts two numbers , finds their sum and prints it using function with argument but no return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void add(int,int);
void main() {
clrscr();
int a,b;
printf(“please enter two numbers”);
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
}
void add(int p, int q) {
int r;
r=p+q;
printf(“sum is %d”,r);
}
3. Function with argument but with return value:
This function doesn't receive any value from calling function but return a value to the calling function.
The library function getchar( ) is the best example.
Program : WAP that accepts two numbers , finds their sum and prints it using function with no argument but return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int add(void);
void main() {
clrscr();
int r;
r=add();
printf(“sum is %d”,r);
getch();
}
void add(void) {
int a,b,c;
printf(“please enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}
4. Function with argument and return value:
This function receives the data from calling function and returns the result value to the calling function.
Program: WAP that accepts two numbers , finds their sum and prints it using function with argument and return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int add(int,int);
void main() {
clrscr();
int a,b,c;
printf(“please enter two numbers”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“sum is %d”,c);
getch();
}
int add(int p, int q) {
int r;
r=p+q;
return(r);
}
Program : WAP that accepts a number , finds and states whether it is even or odd using function with no argument no return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void add(void);
void main() {
clrscr();
add();
getch();
}
void add(void) {
int a;
printf(“please enter a number”);
scanf(“%d”,&a);
if(a%2==0)
printf(“number is even”);
else
printf(“number is odd”);
}
Program: WAP that accepts marks of a student in 4 subjects , finds and prints the percentage using function with argument and return value.
#include<stdio.h>
#include<conio.h>
#include<math.h>
float percentage(int,int,int,int);
void main()
{
clrscr();
int pic,math,cms,btx;
float per;
printf(“please enter the marks in 4 subjects”);
scanf(“%d%d%d%d”,&pic,&math,&cms,&btx);
per=percentage(pic,math,cms,btx);
printf(“percentage is %f”,per);
getch();
}
float add(int a, int b,int c,int d) {
float p;
p=(a+b+c+d)/4.0;
return(p);
}
Nesting of function:
Whenever we intend to shorten a program , make it easily understandable we use functions.
Due to functions we can easily enhance the program or even modify the program .
Generally we call user defined functions in main program. Now a called function can even call another function .
Calling of a function in a called function is known as nesting of function.
Program: WAP that accepts marks of a student in 4 subjects , finds and prints the percentage using nested function .
#include<stdio.h>
#include<conio.h>
#include<math.h>
float percentage(int,int,int,int);
int sum(int,int,int,int);
void main() {
clrscr();
int pic,math,cms,btx;
float per;
printf(“please enter the marks in 4 subjects”);
scanf(“%d%d%d%d”,&pic,&math,&cms,&btx);
per=percentage(pic,math,cms,btx);
printf(“percentage is %f”,per);
getch();
}
float percentage(int a, int b,int c,int d) {
int s;
float p;
s=sum(a,b,c,d);
p=s/4.0;
return(p);
}
int sum(int e, int f,int g,int h) {
int s;
s=e+f+g+h;
return(s);
}
Program: Write a program that finds the real roots of a quadratic equation using nested functions.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void roots(int,int,int);
int x(int,int,int);
void main() {
clrscr();
int a,b,c;
printf(“please enter the coefficients of a quadratic equation”);
scanf(“%d%d%d”,&a,&b,&c);
roots(a,b,c);
getch();
}
roots(int a, int b,int c) {
float x1,x2;
int t;
t=x(a,b,c);
x1=((-1)*b+sqrt(t))/(2*a);
x2=((-1)*b-sqrt(t))/(2*a);
printf(“Roots of equation are %f and %f”,x1,x2);
}
int x(int a, int b,int c) {
int t;
t=b*b-4*a*c;
return(t);
}
Recursion:
Generally we call a user defined function in main. This calle function may or may not call any other function. Sometimes a user defined function calls itself within itself.
This phenomenon of a function calling itself is known as recursion of function.
The best example of recursion is finding factorial of a number.
Program : Write a program for finding factorial of a number using recursion of function.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int);
void main() {
clrscr();
int a,f;
scanf("%d",&a);
f=fact(a);
printf("\nfactorial of %d is %d",a,f);
}
int fact(int p) {
if(p==1) return(1);
else {
p=p*fact(p-1);
return(p);
} }
Storage classes:
Variables are differentiated not only on the basis of their types (i.e. integer, float, char) but even on the basis of place where it will be stored, region over which it will be available (i.e.
scope) and time for which it can be accessed (i.e. life time) and these factors depend on the class in which the variable is stored. There are 4 storage classes.
1. Automatic storage class:
Whenever a variable is to be used only within one function then it is known a local variable and such variable to be declared in automatic storage class by using a keyword ‘auto'.
auto int a;
Automatic is a default storage class i.e. whenever a variable is declared inside a function, it is treated to be automatic.
The automatic storage class is declared inside the function, it is treated to be automatic.
The automatic storage class is declared inside the function it is active in that function and is active till end of function.
2. External storage class:
Whenever a variable is to be used in all functions then it is known as global variable and such variable is to be declared outside the function, may be before or after. If it is defined before all functions then the keyword ‘extern' is not used.
Whereas if it is defined after some functions then the functions in which it is to be used, in that also it is to be defined using the keyword ‘extern'.
If should be declared preferably before all functions it remains active in entire file and is alive till complete program is run. (If a local variable with same name as global variable is declared in any function then local is given precedence over global). The default initial value is ‘0'.
3. Static storage class:
If a variable is declared as in auto storage class then the variable remains active and alive only till function lasts and again if we call the same function, the variable is re-initialized with stated value because its previous value is completely lost. If we intend that even though the variable is active only during a particular function but its last value should be available whenever we re-visit the function. We are supposed to declare the variable to be in static storage class and for that specifically we have to use keyword ‘static'.
It should be declared inside function it remains active only during function called but it remains alive for the whole file. [If static is declared before all functions it remains global their default initial value is ‘0'].
4. Register storage class:
Whenever a variable is declared to be in register storage class then its values is not stored in memory but in one of machines registers (storage location in microprocessor that are used to hold time being information) such variables can be accessed very fast as compared to other class.
Hence generally the counters and loops are stored in register storage class.
They are declared inside the functions and are active and alive only during function.
STRUCTURES
Whenever in C program, one value is to be stored we can use a variable.
If a set of similar data types is to be stored we declare it as an array.
But if the data is collection of different data types then ‘C' allows us to store it by constructing a structure.
A structure is user defined data type in which user has liberty to use as many and any types of data types.
Array Vs structure:
Both array and structure are structured data types that allow us to manage data easily but the difference is:
Array is collection of compulsorily similar data types whereas structure can be collection of elements of different data types as per need of user.
Array is derived data types whereas structure is user defined data type.
Any array behaves like a built in data type we just have to declare the variable whereas in structure we have to declare complete data structure.
For using the structure first of all we have to define the structure and then declare the structure.
Syntax of defining the structure is Struct structure tag
{
data type member 1;
data type member 2;
. . . .
data type member n;
};
Syntax of declaring the structure is struct structure tag variable list;
Even the definition and declaration can be combined as:
Struct structure tag {
data type member 1;
data type member 2; . .
.
data type member n;
} variable list;
for e.g. If we intend to prepare a structure to enter roll no, name, marks in two subjects and average marks of three students.
Struct stu_rec {
int roll_no;
char name[15];
int CPR;
int maths;
float avg;
} stu1, stu2, stu3;
This way once the members (in definition) and variables (in declaration) are specified the value in variable can be entered as follows [Note: memory is assigned only after entering number of variables in declaration.]
Initialization of members of variables of structure
Initialization can be done after definition but with declaration as:
stu_rec stu1 = {1, "ABC", 20, 15}, stu2 = {2, "PQR", 18, 17};
If declaration and initialization are done before termination of definition then structure tag is to be skipped
If initialization is done after definition and declaration then it is not to be done before all functions but inside any function as
stu1.roll_no = 1;
strcpy (stu1.name, "ABC");
stu1.CPR = 20;
stu1.maths = 15;
Or
stu_rec stu1 = {1, "ABC", 20, 15};
Even the values can be scanned as
scanf("%d%s%d%d",&stu1.roll_no,&stu1.name,&stu1.CPR,&stu1.maths);
Copying all values of one variable into other
All values of one variable can be copied into other with Stu2 = stu1;
Comparison of two variables
Comparison of two variables of a structure is to be done by comparing each element (member) with corresponding member separately.
Mathematical operation on any member
Individual members can undergo any operation for e.g.
stu1.avg = (stu1.CPR + stu1.maths) / 2.0;
Or stu2.CPR + = 2;
Declaring member or variable of a structure as array:
We can declare any member of a structure as array and even variable of structure can be declared as array.
Program : WAP that accepts roll no, name, marks in pic and maths subjects of 2 students .Finds and prints percentage of each student using structures.
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<conio.h>
struct fm {
int roll;
char nam[10];
int pic;
int math;
float per;
}st1,st2;
void main() {
clrscr();
printf("\nplz enter roll no.name marks in pic & math of 2 students");
scanf("%d ",&st1.roll);
gets(st1.nam);
scanf("%d%d",&st1.pic,&st1.math);
scanf("%d ",&st2.roll);
gets(st2.nam);
scanf("%d%d",&st2.pic,&st2.math);
st1.per=(st1.pic+st1.math)/2.0;
st2.per=(st2.pic+st2.math)/2.0;
printf("\nroll\tnam\tpic\tmath\tper");
printf("\n%d\t%s",st1.roll,st1.nam);
printf("\t%d\t%d\t%f",st1.pic,st1.math,st1.per);
printf("\n%d\t%s",st2.roll,st2.nam);
printf("\t%d\t%d\t%f",st2.pic,st2.math,st2.per);
getch();
}
Program : WAP that accepts roll no, name, marks in 3 subjects of 5 students .Finds and prints percentage of each student using structures.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
struct stu_reco {
int roll;
char nam[10];
int m[3];
float per;
}s[5];
void main() {
clrscr();
int i,j,sum;
printf("plz enter roll,name,mks in 3 subjects of 5 students");
for(i=0;i<5;i++) {
scanf("%d ",&s[i].roll);
gets(s[i].nam);
for(j=0;j<3;j++)
scanf(" %d",&s[i].m[j]);
}
for(i=0;i<5;i++) {
sum=0;
for(j=0;j<3;j++) sum=sum+s[i].m[j];
s[i].per=sum/3.0;
}
printf("\nroll\tname\tpic\tmath\tpercentage");
for(i=0;i<5;i++) {
printf("\n%d\t%s",s[i].roll,s[i].nam);
for(j=0;j<3;j++)
printf("\t%d",s[i].m[j]);
printf("\t%f",s[i].per);
}
getch();
}
Q: Define a structure for a book having members “name” ,”author”
“cost”.
ans: struct book {
char name[10];
char author[10];
float cost;
};
Q: Define a structure for a college having members “college
name” , “college code”,“principal name”,”no. of branches” for 3 colleges.
ans: struct college {
char college_name[30];
int college_code;
char principal_name[10];
int no_of_branches;
}c1,c2,c3;