C Unit 4
C Unit 4
Use of a function
If we want to perform a task repetitively, then it is not necessary to rewrite the
particular block of the program again and again. We can shift the particular block of
statements in a user defined function and we can call the function, when needed. Using
functions large program can be reduced to smaller ones. It is easy to debug and find out the
errors in it. It also increases the readability.
Example:
printline()
{
int a;
for(a=1;a<40;a++)
printf(“*”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40 characters. The
function is used in main as follows.
Example:
printline()
{
int a;
for(a=1;a<40;a++)
printf(“*”);
printf(“\n”);
}
This example defines a function called printline that prints a line of 40 characters. The
function is used in main as follows.
main()
{
printline();
printf(“Use of C functions”);
printline();
OUTPUT
Use of C functions
**************************************
Need for functions:
1. To reduce the length of the program.
2. To reduce the complexity of program.
3. Easy to debug, test and maintain.
4. To call the function wherever it is needed.
FUNCTION DEFINITION
A function definition, also known as function implementation shall include the following
elements,
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declarations; 5. Function statements;and
6. A return statement.
All the six elements are grouped into two parts namely,
• function header
• function body
Syntax:
The first line function_ type function-name(parameter list) is known as the function header
and the statements within the opening and closing braces constitute the function body. Function
header
The function header consists of three parts:
1. function type
2. function name
3. formal parameter list
To indicate parameter list is empty,the keyword void must be used between the paranthesis as in
void printline(void)
{
……….
}
void printline( )
Function body
The function body contains the declarations and statements necessary for performing the
required task.
1. Local declarations that specify the variables needed by the
function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
Some examples of typical function definitions are:
In Pascal there is no return statement. A subroutine automatically returns when execution reaches
its last executable statement. Values may be returned by assigning to an identifier that has the same
name as the subroutine, a function in Pascal terminology. This way the function identifier is used
for recursive calls and as result holder; this is syntactically similar to an explicit output parameter
An example of use of simple return statement as follows:
if ( error )
return;
The second form of return with an expression returns the value of the expression. For example, the
function
FUNCTION CALLS
A function can be called by simply using the function name in a statement. When
the function encounters a function call, the control is transferred to the called function.
Then the function is then executed line by line as described and the value is returned when
a return statement is encountered.
Example 1:
main( )
{
int y ;
y = mul ( 10, 5 );
printf(“%d\n”, y);
}
When the compiler encounters a function call, the control is transferred to the function
mul( ).This function is then executed line by line.
main ( )
{
int y ;
y = mul (10, 5);
……….
}
Int p;
p=x * y;
The function calls sends two integer values 10 and 5 to the function.
Example 2:
main( )
{
int p;
p=add(10,15);
printf(“%d”,p);
}
int add(int a, int b)
{
int c;
c=a+b;
return( c );
}
In the above example, the function is called using the function name add and
passing the values (10,5). Thus after encountering the function call, the control is
transferred to the called function add and it is executed.
There if it encounters the return statement then the control is transferred to main
function.
Working of functions
Actual argument
The arguments of calling function are actual arguments In
the above example, ‘x’ , ‘y’ and ‘z’ are actual arguments.
main()
{
_______
_______
abc(x,y,z); Function call
Actual argument
_______
_______
}
________
________
return();
}
Formal arguments
The arguments of called function are formal arguments. In
the above example, ‘l’ , ‘k’ and ‘j’ are formal arguments.
Function name
Here, ‘abc’ is a function name.
Argument list
Variable names enclosed within parenthesis are called
argument list. Function call
A function can be called by its name, terminated by a semicolon.
Example
function fact (int n1)
{
int f1; for(i
=1;i<=n1;i++)
f1=f1*i; return(f1);
}
Suppose if the return type is integer then there is no need to mention about the
return type in the function definition as well as in the proto type. If the function returns
non integer value then there is need for explicit specification about the return type. The
return statement is used to return a value to the calling function. It takes the following
form
Return Or
return(expression);
FUNCTION DECLARATION
Functions and Variables:
Each function behaves the same way as C language standard function main(). So a
function will have its own local variables defined. In the above example total variable is local to
the function Demo.
A global variable can be accessed in any function in similar way it is accessed in main()
function.
Declaration and Definition
When a function is defined at any place in the program then it is called function definition. At the
time of definition of a function actual logic is implemented with-in the function.
1. A function declaration does not have any body and they just have their interfaces.
2. A function declaration is usually declared at the top of a C source file, or in a separate
header file.
A function declaration is sometime called function prototype or function signature. For the above
Demo() function which returns an integer, and takes two parameters a function declaration will
be as follows:
int Demo( int par1, int par2);
A function declaration are also known as function prototype consists of four parts.
• Function type(return type)
• Function name
• Parameter list
• Terminating semicolon.
They are coded in the following format:
Function – type function name (parameter list); Example:
Int mul (int m,int n);/* Function prototype */
A function prototype or function interface in C or C++ is a declaration of a function
that omits the function body but does specify the function's return type, name and argument
types. While a function definition specifies what a function does, a function prototype can be
thought of as specifying its interface.
In a prototype, argument names are optional (and have function prototype scope, meaning
they go out of scope at the end of the prototype), however, the type is necessary along with all
modifiers (e.g. if it is a pointer or a const argument).
Different forms of declarations are:
Int mul (int , int );
mul ( int a , int b );
mul (int , int );
Consider the following function prototype:
int fac(int n);
This prototype specifies that in this program, there is a function named "fac" which takes
a single integer argument "n" and returns an integer. Elsewhere in the program a function
definition must be provided if one wishes to use this function. It's important to be aware that a
declaration of a function does not need to include a prototype.
The following is a prototype-less function declaration, which just declares the function
name and its return type, but doesn't tell what parameter types the definition expects.
double fac()
In C, if a function is not previously declared and its name occurs in an expression
followed by a left parenthesis, it is implicitly declared as a function that returns an int and nothing
is assumed about its arguments. In this case the compiler will not be able to perform compile-
time checking of argument types and arity when the function is applied to some arguments. This
can cause problems. The following code illustrates a situation in which the behavior of an
implicitly declared function is undefined.
#include <stdio.h>
Global prototype
The declaration above all the functions, the prototype is referred to as lobal prototype.
Local prototype
When we place it in a function definition are called local prototype. Multiple functions
can use them.
Can be accessed only in the function where it Can be accessed by all the functions in the
has been declared. program.
Needs to be declared inside the function where it is Needs to be declared in the global
to be used. declaration section outside all programs.
Can be used by many functions and so are
Variables are secure.
not secure.
Stored in separate locations , so accessing will
Stored in one location, so any function
change the value only in the function where it’s
accessing can change its value.
used.
Example:
int m;
main( )
{
int i;
float balance;
……..
…..
function1( );
}
function1( )
{
int i;
float sum;
……
……
}
In the above example, variable m is a global variable and can be accessed anywhere in the
program where as variable i is a local variable and should be accessed only in the function in
which it is declared. The variables balance and sum are local variables and can be accessed in
the functions main and function1 respectively.
CATEGORIES OF FUNCTIONS
Depending on whether the argument is present or not and whether a value is returned or
not, may belong to one of the following categories.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.
5. Functions that return multiple values.
When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from the
called function.
So there is only a transfer of control between the calling and the called function, but not
a data transfer.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}
/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
add ( );
}
/* function definition*/
add()
{
int a,b;
a=a+b;
printf(“%d”,a);
return(0);
}
/* function definition*/
add(int a1,int b1)
{ Formal
a1=a1+b1;
printf(“%d”,a1); return;
}
The arguments that we are using in the main function are called actual arguments.
The arguments that we are using in the called function instead of the actual arguments
are called as formal arguments.
When a function call is made, only a copy of the values of
actual arguments is passed into the called function. Changes inside the function will have no
effect on variables used in the actual argument list.
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1; return(a1); }
Example:
/* addition of two numbers*/
#include<stdio.h>
main( )
{
int a,b,c;
c=add (a,b);
printf(“%d”,c);
getch();
}
/* function definition*/
add(int a1,int b1)
{
a1=a1+b1;
return(a1);
}
Example:
/*C program to check whether a number entered by user is prime or not using function
with no arguments and no return value*/
#include<stdio.h> void prime(); int main(){
prime();//No argument is passed to prime().
return0; }
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is
void */ int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num); for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if(flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Function prime() is used for asking user a input, check for whether it is prime of not
and display it accordingly. No argument is passed and returned form prime() function.
Functions that return multiple values:
A return statement can return only one value.We have used arguments to send values to
the called function, in the same way we can also use arguments to send back information to the
calling function. The arguments that are used to send back data are called Output Parameters.
The mechanism of sending back information through arguments are known as address
operator ( &) and indirection operator ( * ). We can get memory address of any variable by
simply placing “&” before variable name.
In the same way we get value stored at specific memory location by using “*” just before
memory address Example 1 :
#include <stdio.h> void
doubleit(int &x, int &y){ x
*= 2; y *= 2;
}
doubleit(x,y);
printf("%i %i",x,y);
return 0;
}
Example 2:
#include<stdio.h>
#include<conio.h>
Explanation: “Calc()” function has four arguments, first two arguments need no
explanation. Last two arguments are integer pointer which works as output parameters
(arguments). Pointer can only store address of the value rather than value but when we add
* to pointer variable then we can store value at that address.
When we call function “calc()” in the line no. 14 then following assignments
occurs. Value of variable “a” is assigned to “x”, value of variable “b” is assigned to “y”,
address of “p” and “q” to “add” and “sub” respectively. In line no. 6 and 7 we are adding
and subtracting values and storing the result at their respective memory location.
Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(a, b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}
/* function definition*/
swap(int a, int b)
{
int t;
t=a;
a=b; b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}
OUTPUT
In function
swap a=4, b=3
In main
a=3, b=4
Call by Reference
• Instead of passing value, addresses are passed.
• Function operates on addresses rather than values.
• Any change made in the formal argument will affect the actual arguments.
Example
/* swapping of two numbers*/
#include<stdio.h>
main( )
{
int a=3,b=4;
swap(&a, &b);
printf(“In main”);
printf(“a=%d, b=%d”, a, b);
getch();
}
/* function definition*/
swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“In function swap”);
printf(“a=%d, b=%d”, a, b)
}
OUTPUT
In function
swap a=4, b=3
In main
a=4, b=3
Functions with arrays:
Like the values of simple variables, it is also possible to pass the values of an array
to a function. To pass an array to a called function, it is enough to list the name of the
array, without any subscripts and the size of the array as arguments.
Example:
Lar(a,n);
NESTING OF FUNCTION
C permits nesting of functions.Calling any function inside another function call is known
as nesting function call. Sometime it converts a difficult program in easy one.
Try to find out maximum number among the five different integers without using nested function
call.
Example 1:
int max(int x,int y){return x>y?x:y;}
void main(){
int m;
m=max(max(4,max(11,6)),max(10,5));
printf("%d",m); getch();
}
Output: 11
Example 2:
//program to calculate a / b-c
#include<stdio.h> main()
{
float a,b,c,res;
scanf(“%f%f
%f”.&a,&b,&c);
res=result(a,b,c);
if(res==0)
printf(“cannot calculate ratio since denominator= 0”);
else
printf(“ratio - %f”,res);
}
//module that returns the value of a/diff
float result(float a, float b, float c)
{
float diff;
diff=difference(b,c);
if(diff==0)
return 0;
else
return(a/diff);
}
//module that returns the difference b-c
float difference(float b, float c)
{
float a;
a=b-c;
if(a==0)
return 0;
else
return a;
}
RECURSION
• Recursion is the process where a function is called
repetitively by itself.
• The recursion can be used directly or indirectly. Direct
recursion
A function calls itself till the condition is true.
Example 1.
main()
{
printf(“this is main”);
main();
}
Example 2:
//program to find the factorial of a number
#include<stdio.h>
main()
{
int n;
scanf(“%d”,&n);
printf(“%d”,factorial(n));
}
factorial(int n)
{
int fact;
if(n==1)
return 1; else
fact=n*factorial(n-1);
return(fact);
}
Steps:
1. When n=3, fact=3*factorial(2)
2. When n=2, fact=2*factorial(1)
3. When n=1, 1 is returned & control goes to step 1 where fact = 2*1=2 & control is
returned to step 1 where fact = 3*2=6 & value is given to the calling function
Indirect Recursion
A function calls another function then the called function calls
the calling function.
Example.
void main()
{
add();
}
add()
{
static int i=0;
while (i<5)
{ i++;
main();
}
}
max_value = values[0];
for( i = 0; i < 5; ++i )
if( values[i] > max_value )
max_value = values[i];
return max_value;
}
main()
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );
Output
Enter 5 numbers
7 23 45 9 121
Maximum value is 121
The program defines an array of five elements (values) and initializes each element to the
users inputted values. The array values is then passed to the function. The declaration int
maximum( int values[5] )
defines the function name as maximum, and declares that an integer is passed back as the result,
and that it accepts a data type called values, which is declared as an array of five integers.
One-Dimensional arrays
In C programming, a single array element or an entire array can be passed to a function.
Also, both one-dimensional and two-dimensional array can be passed to function as argument.
#include <stdio.h>
void display(int a)
{
printf("%d",a);
}
int main(){ int c[]={2,3,4}; display(c[2]);
//Passing array element c[2] only.
return 0;
} Output
4
Single element of an array can be passed in similar manner as passing variable to a
function.
Passing entire one-dimensional array to a function
While passing arrays to the argument, the name of the array is passed as an argument(,i.e,
starting address of memory area is passed as argument).
Write a C program to pass an array containing age of person to a function. This function
should find average age and display the average age in main function.
#include<stdio.h> float
average(float a[]); int
main(){
float avg, c[]={23.4,55,22.6,3,40.5,18};
avg=average(c);/* Only name of array is passed as argument.
*/ printf("Average age=%.2f",avg); return0; }
float average(float a[]){ int
i;
float avg, sum=0.0;
for(i=0;i<6;++i)
{ sum+=a[i];
} avg
=(sum/6); return
avg;
}
Output
Average age=27.08
Two-Dimensional arrays
To pass two-dimensional array to a function as an argument, starting address of memory
area reserved is passed as in one dimensional array It is similar to the One-Dimensional array.
The rules are:
1. The function must be called by passing only the array name.
2. In the function definition,we must indicate that the array has two-dimensional by
including two sets of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
#include
voidFunction(int c[2][2]);
int main(){ int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i) for(j=0;j<2;+
+j){
scanf("%d",&c[i][j]);
}
Function(c);/* passing multi-dimensional array to function */
return0; }
voidFunction(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */ int
i,j;
printf("Displaying:\n");
for(i=0;i<2;++i) for(j=0;j<2;+
+j)
printf("%d\n",c[i][j]);
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Syntax:
Example:
Write a program to declare and use variables of register class
void main ()
{
register int m=1;
clrscr(); for(;m<=5;m++)
printf(“\t %d”,m);
}
OUTPUT
1 2 3 4 5
Explanation:
In the above program variable ‘m’ is declared and initialized to 1. The for loop display values
from 1 to 5. The register class variable is used as loop variable.
External variables extern is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern' the variable cannot be initialized as all it does is point
the variable name at a storage location that has been previously defined.
External variables are declared outside a function. For example ,the external declaration of
integer and float are declared as:
Int number;
float length = 7.5 ;
main ( )
{
-----------
-----------
}
function1 ( ) {
-----------
-----------
}
function2
(){
-----------
-----------
}
When you have multiple files and you define a global variable or function which will be used in
other files also, then extern will be used in another file to give reference of defined variable or
function. Just for understanding extern is used to declare a global variable or function in another
files.
File 1: main.c
int count=5;
main()
{
write_extern();
}
File 2: write.c void
write_extern(void);
void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file. Now
compile these two files as follows
gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the
new value
Static variables static is the default storage class for global variables. The two variables below
(count and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the static
variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initalised at run time but
is not reinitalized when the function is called. This inside a function static variable retains its
value during vairous calls.
void func(void);
main()
{
while (count--)
{
func();
}
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
Here keyword void means function does not return anything and it does not take any parameter.
You can memoriese void as nothing. static variables are initialized to 0 automatically.
Definition vs. Declaration:
Before proceeding, let us understand the difference between defintion and declaration of
a variable or function. Definition means where a variable or function is defined in realityand
actual memory is allocated for variable or function. Declaration means just giving a reference of
a variable and function.
Through declaration we assure to the complier that this variable or function has been
defined somewhere else in the program and will be provided at the time of linking. In the above
examples char *func(void) has been put at the top which is a declaration of this function where as
this function has been defined below to main() function.
Place of
Storage class Visibility Lifetime
Declaration
Before all
Entire file + other files where variable is Entire
None functions in
declared as extern. Program(Global)
a file
Before all Entire file + other files where variable is
Extern functions in declared as extern and the file where it is Global.
a file originally declared as global.
Before all O
Static(external) functions in Global
a file le
Inside a Until end of
None or auto Only in that function
function function
Inside a Until end of
Register Only in that function
function function
Inside a
Static(internal) Only in that function Global
function
MULTI-FILE PROGRAMS
In a program consisting of many different functions, it is often convenient to place each
function in an individual file, and then use the make utility to compile each file separately and
link them together to produce an executable.
Multiple source files can share a variable provided it is declared as an external variable
appropriately. Variables that are shared by two or more files are global variables and therefore
we must declare them accordingly in one file and then explicitly define them with extern in other
files. Figure ….illustrates the use of extern declarations in a multifile program.
The function main in file1 can reference the variable m that is declared as global in file2.
Remember, function1 cannot access the variable m. If, however, the extern int m; statement is
placed before main, then both the functions could refer to m. This can also be achieved by using
extern int m; statement each function in file1.
The extern specifier tells the compiler that the following variable types and names have
already been declared elsewhere and no need to create storage space for them. It is the
responsibility of the linker to resolve the reference problem. It is important to note that a multifile
global variable should be declared without extern in one (and only one) of the files. The Extern
declaration is is done in places where secondary references are made. If we declare a variable as
global in two different files used by a single program, then the linker will have a conflict as to
which variable to use and , therefore, issues a warning.
file1.c file2.c
main() int m / *global variable */
{ function2()
Extern int m; {
int i; int i;
……… ……….
……… ………..
} }
function1 () function3()
{ {
int j; int count;
…….. ……………
……… ……………
} }
Fig (a)Use of extern in a multifile program.
The multifile program shown in fig.(a) can be modified as shown in Fig. (b)
file1.c file2.c
int m; /* global variable */ extern int m;
main() function2()
{ {
int i; int i;
………. ……..
} }
funciton1() funciton3()
{ {
int j; int count;
………. ………
} }
Fig.(b)Another version of a multifile program.
STRUCTURES & UNION
Introduction:
Structure is a constructed data type for packing data of different types. It is a convenient tool for
handling a group of logically related data items.
Some of the examples of structures in as follows.
Time : seconds,minutes,hours
Date : day,month,year Book
: author,title,price,year.
City : name,country,population.
1. Structures enable the user to group together a collection of different data items of
different data types using a single name.
2. Structures help to organize complex data in a more meaningful way.
Features of Structures:
1. To copy elements of one array to another array of same type elements are copied one by
one. It is not possible to copy all the elements at a time. Whereas in structures it is
possible to copy the contents of all the structure elements of different data types to
another structure variable of its type using assignment (=) operator. It is possible because
the structure elements are stored successive memory locations.
2. Nesting of structures is possible .ie creating structure within another structure.
3. It is possible to pass structure elements to a function.
4. It is possible to create structure pointers.
Defining a structure:
A structure can be used to represent a student’s details such as student_name, rollno, marks etc
as follows
Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1; float
stud_mark2; float
stud_mark3;
};
A structure definition creates a format that may be used to declare structure variables.
General format for structure definition is as follows:
struct tag-name
data-type member1;
data-type member2;
……………
……………};
Example:
In the above example book bank is a tag-name that is optional one. If you give the tagname
then later in the program you can declare the variables using the given tag-name otherwise it is
not possible. The title, author, pages and price are members of the structure.
While defining the structure memory is not allocated for its members. Only during the
declaration the memory is allocated for the members. Thus the structure definition creates a
template to represent a group of logically related information. In the structure definition we
should follow the rules stated below
1. The template is terminated with semicolon.
2.While the entire declaration is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag name such as book_bank can be used to declare structure variables of its type
later in the program.
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;
Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10]; float
mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name); printf(“\nRoll
no : “); scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “); scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2); printf(“\nMark3
: “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 + student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks:%f%f %f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}
Structure Initialization:
Like any other type, a structure variable can be initialized. However, a structure must be
declared as static if it is to be initialized inside a function.
Example:
main( )
static struct
{
int weight;
float height;
}student={100,150.45};
……………………..
……………………..
}
Thus in the above example the value 100 is stored in student.weight and 150.45 to
student.height. There is a one- to-one correspondence between the members and their initializing
values.
A variation in initializing a structure is as follows:
main( )
{
struct st_record
{
int weight;
float weight;
};
static struct st_record stu1={30,70.56};
static struct st_record stu2={45,65.73};
……………
……………
}
Another variation in initializing structure variable outside the function is as follows:
struct stu
{
int weight; float height;
}stu1={56,170.56};
main()
{
static struct stu student2 = {23,150.5};
………………..
………………..
}
Example :Write a program to read values using scanf() and assign them to structure
variables.
main()
{
struct book1
{
char book [30];
int pages;
float price;
};
struct book1 b;
clrscr();
printf(“Enter Book name ,pages & Price:”);
scanf(“%s”,b.book);
scanf(“%d”,&b.pages);
scanf(“%f”,&b.price); printf(“\n Book
name :“%s”,b.book); printf(“\n No.of
pages : %d”,b.pages);
printf(“\m Book Price : %d”,b.price);
}
Output:
Example:
structclass
{ int
number;
char
name[20];
float marks;
};
main()
{
int x;
structclass student1 = {111,"Rao",72.50}; structclass
student2 = {222,"Reddy", 67.00};
structclass student3;
student3 = student2;
if(x == 1)
{
printf("\nstudent2 and student3 are same\n\n");
printf("%d %s %f\n", student3.number,
student3.name,
student3.marks);
} else
printf("\nstudent2 and student3 are different\n\n");
}
Output
Array of structures
Array is a collection of similar data types. In the same way we can also define array of
structures. In such type of array every element is of structure type. Array of structures can be
declared as follows :
struct time
{
int second;
int minute;
int hour;
} t[3];
In the above example t[3] is an array of 3 elements containing three objects of time structure.
Each element of t[3] has structure of time with 3 members that are second, minute & hour .
Example:
main()
{
int k;
struct time
{
int second;
int minute;
int hour;
};
struct t
{
int carno;
struct time st;
struct time rt;
};
struct tt r1[3];
clrscr();
printf(“\n Enter car no starting time(hh:mm;ss) &reaching time(hh:mm:ss) :”);
for(k=0;k<3;k++)
{
scanf(“%d”,&r1[k].carno);
scanf(“%d %d %d”,&r1[k].st.hour,&r1[k].st.minute,&r1[k].st.second);
scanf( “%d %d %d”,&r1[k].rt.hour,&r1[k].rt.minute,&r1[k].rt.second);
}
printf(“\n\n Car No,\t Starting Time \t Reaching Time \n”);
for(k=0;k<3;k++)
{
printf(“\n\t %d \t”,r1[k].carno);
printf(“%d %d %d”,r1[k].st.hour,r1[k].st.minute,r1[k].st.second)
printf(“%d %d %d”,r1[k].rt.hour,r1[k].rt.minute,r1[k].rt.second);
}
}
output:
Enter car no starting time(hh:mm;ss) &reaching time(hh:mm:ss) :
120 2 20 25 3 25 58
121 3 25 40 4 40 25
122 4 30 52 5 40 10
120 2 20 25 3 25 58
121 3 25 40 4 40 25
122 4 30 52 5 40 10
Explanation: In the above program two structures time and t are declared. An array of three –
elements r1[3] is defined. The first for loop executes three times and the scanf () statement reads
data through the keyboard for each element of the object. The second for loop and the printf ()
statements within it displays the contents of the array of objects with their elements.
struct date
{ int
dd; int
mm;
int yy; };
struct student
{
int rl; struct
date dob;
int m[3];
int t;
}; void
main()
{
struct student list[50];
int i,j,n;
clrscr();
printf("enter how many student\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter rollno,date of birth\n"); scanf("%d%d%d
%d", &list[i].rl,&list[i].dob.dd,
&list[i].dob.mm,&list[i].dob.yy);
list[i].t=0;
printf("enter three subject marks\n");
for(j=0;j<3;j++)
{
scanf("%d",&list[i].m[j]);
list[i].t+=list[i].m[j];
}
}
printf("student list\n");
for(i=0;i<n;i++)
{
printf("%d\t%d-%d-%d\t",list[i].rl,
list[i].dob.dd,
list[i].dob.mm,
list[i].dob.yy);
for(j=0;j<3;j++) printf("%d\
t",list[i].m[j]);
printf("%d\n",list[i].t);
}
getch();
}
Structures within structures:
Structure within structure can be used to create complex data applications.
Syntax:
Example:
struct time
{
int second;
int minute;
int hour;
};
struct t
{
int carno;
struct time st;
struct time et;
};
struct t player;
Example:
Write a program to enter full name and date of birth of a person and display the same. Use nested
structure.
void main()
{
struct name
{
char firstn [30];
char secondn[30];
char lastn[30];
};
struct b_date
{
int day ;
int month;
int year;
};
struct data
{
struct name n;
struct b_date d;
};
struct data s;
clrscr();
printf(“Enter your name :”);
scanf(“%s %s %s”,s.n.firstn,s.n.secondn,s.n.lastn);
printf(“Enter date of birth:”);
scanf(“%d %d %d”, s.d.day,s.d.month,s.d.year);
printf(“\n\nName:%s%s%s“,s.n.firstn,s.n.secondn,s.n.lastn);
printf(“Date of Birth :%d / %d /%d”,s.d.day,s.d.month.s.d.year);
output:
Enter your name: ram sham pande
Enter date of birth :12 12 1985
Explanation:
In the above example structure name ,b_date and data are defined. The structure data have
member variable of type name and b_date structures respectively .Therefore, this type of
structure is called as nested structure. The variable ‘s’ is a variable of type data structure. Using
scanf() statement the program reads data from keyoard . In the same way, using printf()
statement entered data is displayed on the screen. Here , the dot (.) operator is used twice as we
are accessing variables of structure which are inside the another structure.
Example:
struct book
{
char name[35];
char author[35];
int pages;
} b1;
void main()
{
---------------
---------------
show(&b1); ____________
____________
}
show(struct book *b2)
{
____________
____________
}
Whenever a structure element is to be passed to any other function, it is essential to declare the
structure outside the main ( ) function i.e., global .
In the above example structure book is declared before main ().It is a global structure . Its
member elements are char name[35], char author [35] and int pages . They can be accessed by all
other functions.
Example:
Write a program to pass address of structure variable to user defined function and display the
contents.
# include<stdio.h>
#include<conio.h>
struct book
{ char
name[35]; char
author [35]; int
pages;
};
void main()
{
struct book b1={“LET US C”,”YESWANTH KANTIKAR”,345}; show(&b1);
}
show(struct book *b2)
{ clrscr()
;
printf(“\n%s by %s of %d pages”,b2name ,b2author,b2pages);
}
Output:
LET US C by YESWANTH KANITKAR of 375 PAGES
Explanation : In the above program structure book is defined before main ( ) .In the main ( )
function b1 is an object declared and initialized. The address of object b1 is passed to function
show ( ).In the function show ( ) the address is assigned to pointer *b2 that is a pointer to the
structure book. Thus , using operator contents of structure elements are displayed.
Example:
Write a program to pass entire structure to user defined function.
struct boy
{
char name[25];
int age;
int wt;
};
void main()
{
struct boy b1={“Amit”, 20 ,45};
print(b1);
}
print(struct boy b)
{
clrscr();
printf(“\n %s %d %d “,b.name ,b.age,b.wt)l
return 0;
}
Output:
Amit 20 45
Explanation: In the above program structure boy is defined outside the main ( ).so it is global
and every function can access it. The object defined on structure boy b1 is passed to function
print (). The formal argument (object) of function print ( ) receives contents of object b1. Thus ,
using dot operator contents of individual elements are displayed.
Pointer to Structure
A pointer is a variable that holds the address of another data variable. The variable may be of
any data type ie. int, float or double. In the same way we can define pointer to structure. Here ,
starting address of the member variables can be accessed. Thus, such pointers are called structure
pointers. Example:
struct book
{
char name [25];
char author[25];
int pages;
};
struct book *ptr;
Here, *ptr is pointer to structure book. Syntax for using pointer with member is as given
below.
5. ptr name
6. ptr author
7. ptrpages
By executing these three statements starting address of each member can be estimated.
Example:
Write a program to declare pointer to structure and display the contents of the structure.
void main()
{
struct book
{
char name [25];
char author [25];
int pages ;
};
struct book b= {“Let us C”, ”Yeswanth kanitkar”,375};
struct book *ptr;
ptr=&b;
clrscr();
printf(“\n %s by %s of %d pages “,b.name,b.author,b.pages); printf(“\n
%s by %s of %d pages“,ptrname,ptrauthor,ptrpages); }
Output
Let us C by Yeswanth kanitkarof 375 pages
Let us C by Yeswanth kanitkarof 375 pages
Explanation: In the above program the function printf( ) statement prints structure elements by
calling them as usual. In the second printf( ) statement to print the structure elements using
pointer an arrow operator ( -and > together) is used instead of dot(.)operator. The ptr is not a
structure variable but pointer to a structure.
Example:
Write a program to declare pointer as members of structure and display the contents of the
structure without using (arrow) operator.
void main()
{
struct boy
{
char *name;
int *age;
float *height;
};
struct boy b;
char nm[10]=”Akil”;
int ag=20;
float ht =5.4;
strcpy(b.name ,nm);
b.age =&ag;
b.height = &ht;
clrscr();
printf(“\n Name = %s”,b.name);
printf(“\n Age = %d”,*b.age);
printf(“\n Height = %d”,*b.height);
}
Output:
Name = Akil
Age = 20
Height = 5. 4
Explanation: Here no pointer is declared in structure. Hence, using dot operator we can display
the contents of the structure.
Example:
Write a program to display the contents of the structure using ordinary pointer.
void main()
{
int *p;
struct num
{
int a;
int b; int c;
};
struct num d;
d.a =2;
d.b=3;
d.c=4;
p=&d.a;
clrscr();
printf(“\n a=%d”,*p);
printf(“\n b=%d’,*(++p));
printf(“\n c=%d”,*(++p));
};
Output:
a=2 b=3
c=4
Explanation: In the above program *p and structure num are declared .The structure num has
three members a,b &c of integer data type and initialized with the values 2,3 and 4 respectively.
The structure variables are stored in successive memory locations. If we get starting address of
one variable we can display next elements. The address of variable a is assigned to pointer p. By
applying unary * and ++ operator pointer is increased and values are displayed.
Example:
enum month{jan,feb,mar,apr,may,jun.jul,aug,sep,oct,nov,dec};
This statement creates a user-defined data type. The keyword enum is followed by the tag
name month. The identifiers are jan,feb etc., The identifier jan refers to 0,feb refers to 1etc., .The
identifiers are not to be enclosed within quotation marks.
Example:
Write a program to create enumerated data type for 12 months. Display their values in integer
constants.
#include<stdio.h>
#include<conio.h>
void main()
{
enum month
{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; clrscr();
printf(“\n Januay =%d”,jan); printf(“\n April =%d”,apr);
printf(“\n July =%d”,jul); printf(“\n December =%d”,dec);
} Output:
January = 0
April = 3
July =6
December=11
Explanation:
In the above program enumerated data type month is declared with 12-month names within two
curly braces. The compiler assigns 0 value to first identifier and 11 to last identifier .Using printf
() statement the constants are displayed for different identifiers.
By default the compiler assigns values from 0 onwards. Instead of 0 the programmer can
initializes his/her own constant to each identifier .
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
enum month
{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; clrscr();
printf(“\n Januay =%d”,jan);
printf(“sss\n April =%d”,apr);
printf(“\n July =%d”,jul);
printf(“\n December =
%d”,dec);
} Output:
January = 1
April = 4
July =7
December=12
UNION
Example:
Write a program to find the size of union and member of bytes reserved for it.
main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
union result perf;
}data;
clrscr();
printf(“Size of union :%d\n”,sizeof(data.perf));
printf(:Size of structure :%d \n”,sizeof(data));
}
Output
Size of union :2
Size of structure :19
Explanation:
Union contains two variables of data types int & char respectively. The int & char requires 2 & 1
bytes respectively for storage. According to the theory the union reserves two bytes because int
takes more space than char data type.
The structure ‘res’ are defined immediately after union,which contains data type char, int &
union variable. The size of structure is printed which are nothing but sum of 15 bytes of char
array, 2 bytes of int and 2 bytes of union variable perf. Thus, the total size of structure is 19.
Size of structures
We normally use structures, unions, and arrays to create variables of large sizes. The actual size
of these variables in terms of bytes may change from machine to machine. We may use the unary
operator sizeof to tell us the size of a structure (or any variable). The expression sizeof(struct
x)
will evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple structure variable of type struct x, then the expression
sizeof(y)
would also give the same answer. However , if y is an array variable of type struct x , then
sizeof (y) would give the total number of bytes the array y requires.
Bit Fields
Bit field provides exact amount of bits required for storage of values. If a variable is 1 or 0, we
need a single bit to store it. If a variable is between 0 and 3, we need two bits to store them.
Similarly if variable is between 0 to 7,then three bits will be sufficient to hold the variable and so
on. The number of bits required for a variable is specified by non-integer followed by colon. The
variables occupy a maximum of one byte for char and two bytes for integer. Instead of using
complete integer if bits are used, space of memory can be saved.
Example:
Write a program to display the examination result of the student using bit fields.
#include<stdio.h>
#include<conio.h>
#define PASS 1
#define FAIL 0
#define A 0
#define B 1
#define C 2 void
main()
{
struct student
{
char *name;
unsigned result :1;
unsigned grade:2;
};
struct student v;
v,name =”Sachin”;
v.result=PASS;
v.grade=C; clrscr();
printf(“\n Name :%s”,v.name);
printf(“\n Result : %d”,v.result);
printf(“\n Grade : %d”,v.grade);
}
Output:
Name : Sachin
Result : 1
Grade :2
Explanation:
In the above program using #define macros are defined. The result of the student is indicated in
1 bit and the grade requires 2 bits. An object v is declared and using the object bits fields are
initialized with data.
UNION AND STRUCTURES
The union can be nested within another union .we can also create structure in a union or vice
versa
Example
Write a program to use structure within union .Display the contents of structure elements.
#inlcude<stdio.h>
#include<conio.h>
void main()
{
struct x
{
float f;
char p[2];
};
union z
{
structure x set;
};
union z st;
st.set.f=5.5;
st.set.p[0]=65;
st.set.p[1]=66;
clrscr();
printf(“\n %f”,st.set.f);
printf(“\n %c’,st.set.p[0]);
printf(“\n %c”,st.set.p[1]);
}
Output:
5.5
A
B
Explanation:
In the above program structure x is defined. The union z contains structure member as its
member variable. The variable st is an object of union z. The member variables of structure x are
assigned with certain values .Using objects of structure and union.
Sample programs:
1. C Program to Reverse a String by Passing it to Function
#include<stdio.h>
#include<string.h>
voidReverse(char str[]);
int main(){ char
str[100];
printf("Enter a string to reverse: ");
gets(str); Reverse(str);
printf("Reversed string: ");
puts(str);
return0; }
voidReverse(char str[]){ int
i,j;
char temp[100]; for(i=strlen(str)-1,j=0;
i+1!=0;--i,++j)
{
temp[j]=str[i];
} temp[j]='\0';
strcpy(str,temp);
}
Output
Enter a string to reverse: zimargorp Reversed
string: programiz
2. C program to Check Whether a Number can be Express as Sum of Two Prime Numbers
This program takes a positive integer from user and checks whether that number can be
expressed as the sum of two prime numbers. If that number can be expressed as sum of two
prime numbers then, that number is expressed as sum of two prime numbers in output. To
perform this task, a user-defined function is created to check prime number.
#include<stdio.h>
int prime(int n);
int main() {
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n); for(i=2;
i<=n/2;++i)
{
if(prime(i)!=0)
{
if( prime(n-i)!=0)
{
printf("%d = %d + %d\n", n, i, n-i);
flag=1;
}
}}
if(flag==0)
printf("%d can't be expressed as sum of two prime numbers.",n);
return0; }
int prime(int n)/* Function to check prime number */
{ int i, flag=1;
for(i=2; i<=n/2;++i)
if(n%i==0)
flag=0;
return flag; }
Output
Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
Output:
Enter two positive integers: 366
60
H.C.F of 366 and 60 = 6
UNIT IV QUESTIONS SECTION A
SECTION B
SECTION C
1. Explain in detail about user-defined data types and enumerated data types with suitable
example.
2. How will you declare functions and function-prototypes. Explain with example.
3. What are the types of functions? Explain in detail with example.
4. Write a brief note on return() statement. Explain with example.
5. Write c program for
6. To display message using user-defined functions.
7. To display alphabets ‘A,’B’ and ‘C’ using functions.
8. How will you pass arrays with functions. Explain with example.
9. Explain in detail about Recursion with example.
10. Write a brief note on call by reference and call by value with example.