C language Unit-4 notes
C language Unit-4 notes
, II Semester
Unit – IV
Syllabus:
FUNCTIONS
INTRODUCTION: -
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. “A function is a self-contained
program segment that carries out some specific task.” A function can be called multiple times to provide
reusability and modularity to the C program. In other words, we can say that the collection of functions
creates a program. The function is also known as procedure or sub-routine in other programming languages.
USES OF C FUNCTIONS:
• C functions are used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• Easy to read, write and debug a function.
• Easier to maintain or modify such a function.
• Function increases the execution speed of the program.
• A Function may be used by many other programs.
• The length of the source program can be reduced using functions.
• A function increases the modularity of program.
• Function reduces the amount of work and development time.
• Function declaration or prototype– This informs compiler about the function name, function parameters
and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.
FUNCTION DEFINITION:
When a function is defined, space is allocated for the function in the memory. Function definition contains
two parts
• Function header
• Function body
Syntax:
Return_ type function_name(list of parameters) //Function header
{
:
:
Statements //function body
:
Return(variable);
}
List of parameters in the function header are called as formal parameters. The parameter list may contain
zero or more parameters.
The function body contains set of instructions to perform the desired task.
The function can be defined either before or after the main(). If it is defined before main(), then function
definition itself act as a function declaration. So in this situation we can skip the function declaration.
SIMPLE EXAMPLE PROGRAM FOR C FUNCTION:
• As you know, functions should be declared and defined before calling in a C program.
• In the below program, function “square” is called from main function.
• The value of “m” is passed as argument to the function “square”. This value is multiplied by itself
in this function and multiplied value “p” is returned to main function from function “square”.
#include<stdio.h>
// function prototype, also called function declaration
float square (float x);
// main function, program starts from here
int main( )
{
float m, n;
printf ("\nEnter some number for finding square \n");
FUNCTION CALL:
The function call invokes the function. When the function is invoked the compiler jumps to the function
definition to execute the statements in the function. Once the called function is executed, the program
control passes back to the function call.
Syntax:
Function_name(list of parameters);
The list of parameters in the function call are called as actual parameters.
While calling a function, the points to be remembered is
“The function name and the number and type of the actual parameters in the function call should be
same as that given in the function definition.”
• Number of actual parameters =number of formal parameters
• Data Type of actual parameters = data type of formal parameters
• Order of actual parameters =order of formal parameters
function. A calling environment invokes the function but not feeding any formal arguments and the
functions also does not return back anything to the caller.
Example:
void display();
main( )
{
display( );
}
void display( )
{
printf("Hello");
}
Output:
Hello
Function with arguments and no returns value:
The second type of writing a user-defined function is passing some formal arguments to a
function but the function does not return back any value to the caller. It is also a one way data
communication between calling function and the called function.
Example:
void square(int a);
main( )
{
int x;
x = 5;
square(x);
}
void square(int a)
{
int c;
c = a * a;
printf(" The result=%d", c);
}
Output:
The result=25
int square(int a)
{
int c;
c = a * a;
return c;
}
Output:
The result=25
Function with no arguments and returns value:
The fourth type of user-defined function is no passing formal arguments to a function
from calling portion of the program and the computed values, if any- is transferred back to the caller. Data is
communicated between calling portion and a function block.
Example:
int square();
main( )
{
int ans;
ans = square();
printf(" The result=%d", ans);
}
int square()
{
int c, a=5;
c = a * a;
return c;
}
Output:
The result=25
2. CALL BY REFERENCE:
• In call by reference method, the address of the variable is passed to the function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only address is used by both
parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
• In this program, the address of the variables “m” and “n” are passed to the function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
Department of Computer Science Page 6
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
OUTPUT:
Return statement:
The return statement is used to return some value or simply pass the control to the calling function. The
return statement can be used in the following two ways.
1.return;
2.return expression;
The first form of the return statement is used to terminate the function and pass the control to the calling
function. No value from the called function is returned when this form of the return statement is used.
void main()
{
int sum=sumDigits();
printf(“%d\n”,sum);
return;
}
int sumDigits()
{
int sum=0;
int digit;
for(digit=0;digit<=9;digit++)
{
sum+=digit;
}
return sum;
}
The function main is called when our program is started. Then it calls the routine sumDigits. At this point
“main” is paused and sumDigits starts. The second function will do its calculations and reach
the return sum; statement. Here it ends and the control is transferred back in main. Since sumDigits returns a
value(the value of the sum variable), a value will appear in the place where the function was called.
The sum of the digits is 0+1+2…+9= 45. This value will appear in the place of invocation and the variable
sum will take this value. Then we print that value and return from the main function, which ends our program.
Scope of a variable:
A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.
• In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables:
variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside
their own. The following example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
Live Demo
#include<stdio.h>
int main()
{
/*local variable declaration */
int a,b;
int c;
/*actual initialization*/
a=10;
b=20;
c=a+b;
printf(“value of a=%d,b=%d and c=%d\n”,a,b,c);
return 0;
}
Global variables:
Global variables are defined outside a function, usually on top of the program. Global variables hold their
values throughout the lifetime of your program and they can be accessed inside any of the functions defined
for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout
your entire program after its declaration. The following program show how global variables are used in a
program.
#include<stdio.h>
/* global variable declaration*/
int g;
int main()
{
/* local variable declaration*/
int a,b;
/*actual initialization*/
a=10;
b=20;
g=a+b;
printf(“value of a=%d,b=%d and g=%d\n”,a,b,g);
return 0;
}
Storage Classes in C
Each variable has a storage class which defines the features of that variable. It tells the compiler about where
to store the variable, its initial value, scope (visibility level) and lifetime (global or local).
There are four storage classes in C.
• auto
• extern
• static
• register
The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
register int miles;
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and implementation restrictions.
Static storage class:
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope.
#include<stdio.h>
#include<conio.h>
void increment();
void main()
{
increment();
increment();
increment();
increment();
getch();
}
void increment()
{
static int i=0;
printf(“%d”,i);
i++;
}
Extern Storage Class:
The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. It is equivalent to global variable.
#include<stdio.h>
#include<conio.h>
int x=20;
void main()
{
extern int y;
printf(“The value of x is %d\n”,x);
printf(“The value of y is %d”,y);
getch();
}
int y=30;
output:
The value of x is 20
The value of y is 30
Recursive Functions:
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller
problem. Any function which calls itself is called recursive function, and such function calls are called
recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a
termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to
understand.
#include<stdio.h>
int fact(int);
int main()
{
int n,f;
printf(“enter the number whose factorial you want to calculate”);
f=fact(n);
printf(“factorial=%d”,f);
}
int fact(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
int main()
{
struct point p1; // The variable p1 is declared like a normal variable
}
How to initialize structure members?
Structure members cannot be initialized with declaration. The initializers or values are enclosed in braces and
separated by commas
Ex: student s={172,”raj”,10000.0,”01-Aug-90”};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct point p1 = {0, 1};
}
How to access structure elements?
Structure members are accessed using dot (.) operator.
#include<stdio.h>
struct point
{
int x, y;
};
int main()
{
struct point p1 = {0, 1};
return 0;
}
Output:
x=20,y=1
struct car
char name[100];
float price;
};
//price as 987432.50
car1.price
To access the name of car1,
car1.name
#include<stdio.h>
int main()
{
struct car
{
char name[100];
float price;
}
//car1.name->”xyz”
//car1.price->987432.50
struct car car1={“xyz”,987432.50};
//printing values using dot(.)operator or member acess operator
printf(“name of car1=%s\n”,car1.name);
printf(“price of car1=%f\n”,car1.price);
return 0;
}
Program: To read and display the information about a structure
#include<stdio.h>
main()
{
typedef struct
{
int sno;
char name[25];
float fees;
char DOB[10];
}student;
student s1;
printf(“\n Enter the rollno:”);
scanf(“%d”,&s1.sno);
printf(“\n Enter name:”);
scanf(“%s”,s1.name);
printf(“\n Enter DOB”);
scanf(“%s”,s1.DOB);
printf(“\n Enter fee”);
scanf(“%f”,&s1.fees);
printf(“\n *******STUDENT DETAILS********”);
printf(“\n ROLL NO=%d”,s1.sno);
printf(“\n NAME=%s”,s1.name);
printf(“\n FEES=%f”,s1.fees);
printf(“\n DOB=%s”,s1.DOB);
Nested structures
A structure can be placed within another structure. Ie a structure may contain another structure as its membe
r. A structure that contains another structure as its member is called NESTED STRUCTURE.
Ex:
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main()
{
printf(“name:%s\ncity:%s\npincode:%d\nphone:%s”,emp.name,emp.add.city,emp.add.city,emp.add.
pin,emp.add.phone);
C provides us the feature of nesting one structure within another structure by using which, complex data typ
es are created. For example, we may need to store the address of an entity employee in a structure. The attrib
ute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address
of the employee, we need to store the address of the employee into a separate structure and nest the structure
address into the structure employee.
Enter employee information
Arun
Delhi
110001
1234567890
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
Array of structures
Structure is collection of different data type. An object of structure represents a single record in me
mory, if we want more than one record of structure type, we have to create an array of structure or object. As
we know, an array is a collection of similar type, therefore an array can be of structure type.
struct struct_name
{
…………
data type varn;
}
struct struct-name obj[size];
int id;
char name[25];
int age;
long salary;
};
void main()
{
int i;
struct employee emp[3];
for(i=0;i<3;i++)
{
}
printf(“details of employees”);
for(i=0;i<3;i++)
printf(“\n%d\t%s\t%d\t%ld”,emp[i].id,emp[i].age,emp[i].salary);
}
Output:
Enter details of 1 Employee
Details of Employees
In the above example, we are getting and displaying the data of 3 employee using array of object. Statement
1 is creating an array of Employee Emp to store the records of 3 employees.
Structures and Functions
A function may access the member of a structure in 3 ways
Passing structures to
function Passing the entire structure
#include<stdio.h>
typedef struct
{
int x;
int y;
}point;
void disp(int,int);
main()
{
point p1={2,3};
disp(p1.x,p1.y);
}
void disp(int a,int b)
{
printf(“%d%d”,a,b);
}
Output:
23
typedef struct
{
int x;
int y;
}point;
void disp(point);
main()
{
point p1={2,3};
disp(p1);
}
void disp(point m)
{
printf(“%d%d”,m.x,m.y);
Output:
23
typedef struct
{
int x;
int y;
}point;
void disp(point * m);
main()
{
point p1={2,3};
disp(&p1);
}
void disp(point *m)
{
printf(“%d%d”,m->x,m->y);
}
Output:
23
Unions in C
A union is a special data type available in C that allows to store different data types in the same memory loc
ation. You can define a union with many members, but only one member can contain a value at any given ti
me. Unions provide an efficient way of using the same memory location for multiple-purpose.
A union is a memory location that is shared by 2 or more different types of variables. Declaring a union is simi
lar to Structures.
}union_variable; }union_name;
in xyz, both i and ch share the same memory location. i occupies 2 bytes, ch uses only 1 byte.
When a union variable ie xyz is declared, the complier automatically allocates enough storage to hold the large
st memory of the union.
To access the member of a union, the same syntax of structure is used
• Dot operator
• Arrow operator
Ex:
• xyz,i=10;
• p=&xyz; p->i=20;
union category
{
int class;
char deptid[10];
};
union category catg[10]; //creates an array of unions with 10 elements of union type.
Unions can be very useful when declared inside a structure. Consider an example
#include<stdio.h>
struct stud
{
union
{
char name[20];
int rno;
};
int marks;
};
main()
{
struct stud s;
char c;
printf(“|n u can enter name or roll number of the student”);
printf(“\n Do u want to enter the name? (y or n):”);
gets(c);
if(c==’y’||c==’Y’)
{
printf(“\nEnter the name:”);
gets(s.name);
}
else
{
printf(“\n Enter roll number:”):
scanf(“%d”,&s.rno);
}
printf(“\n Enter the marks:”);
scanf(“%d”,&s.marks);
Department of Computer Science Page 24
St.Joseph’s Degree College, Sunkesula Road, Kurnool I B.Sc., II Semester
if(c==’y’||c==’Y’)
printf(“\n Name:%s”,s.name);
else
printf(“\n roll number{%d”,s.rno);
printf(“\n Marks:%d”,s.marks);
return 0;
}
Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants
which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.
Each integer value is given an identifier called enumeration constant.
Here is the syntax of enum in C language,
Enum enum_name{const1,const2,…};
The enum keyword is also used to define the variables of enum type. There are two ways to define the variables
of enum type as follows.
1.enum week{Sunday,Monday,Tuesday,wenesday,Thursday,Friday,Saturday};
enum week day;
2 enum color{red,blue,green,white};
Now we can define variables of type color
enum color x;
enum color y;
enum color z;
Assigning values to enumerated type
• x=blue;
z=purple;//error-coz there is no purple color in the list
• x=y;
z=y;
Comparing enumerated types
• if (x==y)
• if (x==blue)
• enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
Ex:
enum month x;
:
:
switch(x)
{
case jan:---
break;
case feb:----
break;
:
:
}
The Compiler automatically assigns values to enumerated type starting with ‘0’ & we can over ride it &assigns
our own value.
Ex:
• Enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
This jan is assigned the value 0
Fed is assigned the value 1 & soon until dec with 11.
• To make Jan start with 1, we can declare
Enum month{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
The rest will be automatically assigned by the compiler.
I/P-O/P Operation:
When we read an enumerated type, we must read it as an integer. When we write it, it displays as an integer.
Ex:
main()
{
enum month{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
enum months a,b;
printf(“\n Enter a and b values:”);
scanf(“%d%d”,&a,&b); //enter 1,11
printf(“%d%d”,a,b);
}
O/P:
Enter a and b value
1
11
111
#include<stdio.h>
main()
{
enum tv{maa=17,abc=11,espn=39,hbo=15,bbc=21};
printf(“Here are my favorite cable stations:\n”);
printf(“maa=%d\n”,maa);
printf(“abc=%d\n”,abc);
printf(“espn=%d\n”,espn);
printf(“hbo=%d\n”,hbo);
printf(“bbc=%d\n”,bbc);
}
O/P:
Here are my favorite cable stations:
maa=17
abc=11
espn=39
hbo=15
bbc=21