You are on page 1of 181

C programming

MODULE 4
CSE Dept.

1
Module 4
Working with functions
syllabus
• Introduction to modular programming, writing
functions, formal parameters, actual
parameters, Pass by Value, Recursion, Arrays
as Function Parameters, structure, union,
• Storage Classes, Scope and life time of
variables,
• simple programs using functions.
Previous University questions
Previous University questions
Previous University questions
Previous University questions
UNIVERSITY QUESTIONS
UNIVERSITY QUESTIONS
UNIVERSITY QUESTIONS
Modular Programming

• Modular programming is the process of


subdividing a computer program into separate
sub-programs. 
Advantages
• Ease of Use :This approach allows simplicity, as rather than
focusing on the entire thousands and millions of lines code
in one go, we can access it in the form of modules
• Programming errors are easy to detect: Minimizes the risks
of programming errors and also makes it easier to spot
errors, if any.
• Allows re-use of codes: A program module is capable of
being re-used in a program which minimizes the
development of redundant codes
• Improves manageability: Having a program broken into
smaller sub-programs allows for easier management.
Function
• A function is a block of code that performs a
specific task.
• Every C program has at least one function,
which is main(), and can have additional
functions.
Types of C function
1. Standard library functions

2. User defined function


The standard library functions
• The standard library functions are built-in functions
in C programming.
• These functions are defined in header files.
• For example
– The printf() is a standard library function to display output
on the screen. This function is defined in the stdio.h
header file.
– The sqrt() function calculates the square root of a number.
The function is defined in the math.h header file.
– The strlen() function calculates the length of a given
string. The function is defined in the string.h header file.
User defined function

• Functions that we define ourselves to do


certain specific task are referred as user-
defined functions.
Advantages of user defined functions
• Functions eliminate redundancy ie it eliminate
redundant or repetitions of code.
• The length of  a source program can be reduced 
• Modular Programming can be done
– We can divide program in to smaller modules.
easy to understand, maintain and debug
– Individual functions can be easily built and tested
Advantages of user defined functions

• Reusable codes that can be used in other


programs

• A large program can be divided into smaller


modules. Hence, a large project can be divided
among many programmers.
– Functions support the division of labour
user defined functions

1. Function declaration or function


prototyping

2. Function definition

3. Function call
Function definition

• The general form of a function definition in C


programming language is as follows −

return_type function_name(argument list ) //function header


{
body of the function
return statement Function body
}
Function definition
• A function definition in C programming consists of a function
header and a function body.
• Function header consist of return type,function name,arguments
• Return Type −
– A function may return a value. The return_type is the data type of the
value the function returns.
– Some functions perform the desired operations without returning a value.
– In this case, the return_type is the keyword void.
• Function Name −
– This is the actual name of the function.
– The function name and the parameter list together constitute the
function signature.
• Parameters −
– A parameter is like a placeholder. When a function
is invoked, you pass a value to the parameter.
– Parameters are optional; that is, a function may
contain no parameters.
• Function Body −
– The function body contains a collection of
statements that define what the function does.
Calling a Function
• When a program calls a function, the program
control is transferred to the called function.

• A called function performs a defined task and


when its return statement is executed or when
its function-ending closing brace is reached, it
returns the program control back to the main
program.
Function declaration or prototype  
• Like variable we also need to declare function
before using it in program.
• Function declaration is also called as function
prototype
Function declaration or prototype  
• This informs compiler about the function
name, function parameters and  return value’s
data type.
• Prototype declaration always ends with
semicolon.
• Parameter list is optional.
Positioning function declaration
• If function definition is written after main then
and then only we write prototype declaration
in global declaration section
• If function definition is written above the main
function then ,no need to write prototype
declaration
#include <stdio.h>
int add(int a, int b); // function prototype
int main()
{ int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = add(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
Int add(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Pgm with out function prototype
#include <stdio.h>
void sum()
{ int a,b,s=0;
printf("enter a and b");
scanf("%d",&a,&b);
s=a+b;
printf("%d",s);
}
void main()
{
sum();
}
Pgm with function prototype
#include <stdio.h>
void sum();
void main()
{
sum();
}
void sum()
{ int a,b,s=0;
printf("enter a and b");
scanf("%d“ “%d”, &a, &b);
s=a+b;
printf("%d",s);
}
Category of functions
1. Functions with no arguments and no return
values
2. Functions with arguments and no return values
3. Functions with arguments and one return values
4. Functions with no arguments and but return a
value
5. Function that have multiple return values(work
based on condition)
Functions with no arguments and no return values(sum of two
numbers)

#include <stdio.h>
void sum() // fun defnition
{
int a,b,s=0;
printf("enter a,b");
scanf("%d",&a,&b);
s=a+b;
printf("%d",s);
}
void main()
{
sum(); // fun call
}
Functions with no arguments and no return
values Factorial of a number
#include<stdio.h>
void fact()
{ int limit,i=1,f=1;
printf("enter the limit");
scanf("%d",&limit);
for(i=1;i<=limit;i++)
{
f=f*i;
}
printf("factorial is %d",f);
}
void main()
{
fact();
}
Functions with arguments and no return
values
#include<stdio.h>
void fact( int limit )
{
int i=1,f=1;
for(i=1;i<=limit;i++)
{ f=f*i;
}
printf("factorial is %d",f);
}

void main()
{ int n;
printf("enter the limit");
scanf("%d",&n);
fact(n);
}
Functions with arguments and with return values
#include<stdio.h>
int fact( int limit )
{int i=1,f=1;
for(i=1;i<=limit;i++)
{
f=f*i;
}
return f;
}
void main()
{ int n,factorial;
printf("enter the limit");
scanf("%d",&n);
factorial=fact(n);
printf("factorial is %d",factorial);
}
Functions with no arguments and but
return a value
#include<stdio.h>
int fact()
{int limit,i=1,f=1;
printf("enter the limit");
scanf("%d",&limit);
for(i=1;i<=limit;i++)
{ f=f*i;
}
printf("factorial is %d",f);
return f;}
void main()
{
int factorial;

factorial=fact();
printf("factorial is %d",factorial);

}
Function that have multiple return
statements
#include <stdio.h>
int even(num)
{
if( num%2==0)
return 1;
else
return 0;
}
void main()
{
int s,a;
printf("enter a");
scanf("%d",&a);
printf("%d",even(a));
}
This function expects a number as an argument
and returns True if the number is divisible by
2, or it returns False otherwise
Parameter & Arguments
• Parameters are temporary variable names
within functions.
• The argument can be thought of as the value
that is assigned to that temporary variable.
Within the function, parameters act as
placeholders for the argument it is passed
Actual parameters & formal parameters

• Actual parameters are parameters as they


appear in function calls.

• Formal parameters are parameters as they


appear in function declarations.
Void fact(int limit)
{
Identify the actual and formal
int i=1,f=1;
parameters in the program
for(i=1;i<=limit;i++)
{
f=f*i;

}
printf("factorial is %d",f);
}
void main()
{ int n;
printf("enter the limit");
scanf("%d",&n);

fact(n);
}
• Actual parameter ----n

• Formal parameter----limit
Passing Argument to Function :

• In C Programming we have different ways of


parameter passing schemes such as
– Call by Value

– Call by Reference.
Call By Value:
• Here values of actual parameters are copied to
function’s formal parameters
• two types of parameters are stored in
different memory locations.
• So any changes made inside functions are not
reflected in actual parameters of caller.
void swapx(int x, int y);
  
int main()
{
    int a = 10, b = 20;
  
    // Pass by Values
    swapx(a, b);   output
   inside function x=20 y=10                                  
    printf("a=%d b=%d\n", a, b);                                                                     
   outside function a=10 b=20
    return 0;
}   
void swapx(int x, int y)
{
    int t;
      t = x;
    x = y;
    y = t;   
    printf("x=%d y=%d\n", x, y);
}
  output
void swap(int a, int b); inside function a=20 b=10                                
int main()                                                                     
outside function a=10 b=20
{ int a = 10, b = 20;
swap(a, b);
printf("outside function a=%d b=%d\n", a, b);
return 0; }

swap(int a, int b)
{ int t;
t = a;
a = b;
b = t;
printf("inside function a=%d b=%d\n", a, b); }
Call by value example
#include <stdio.h>
int callbyvalue(num)
{
num=num*10;
printf(" value of num inside function is %d\n",num);
}
void main()
{
int a=7;

printf(" value of a before function call is %d\n",a);


callbyvalue(a);
printf(" value of a after function call is %d\n",a);
}
Output is
value of a before function call is 7

value of num inside function is 17

value of a after function call is 7


Call by Reference
• While calling a function, instead of passing the
values of variables, we pass address of
variables(location of variables) to the function
known as Call By References.
• Both the actual and formal parameters refer
to same locations, so any changes made inside
the function are actually reflected in actual
parameters of caller.
void swapx(int*a, int *b);
int main()
{ int a = 10, b = 20;
Swap(&a, &b);
printf("outside function a=%d b=%d\n", a, b);
return 0; }
  output
void swap(int *a, int *b) inside function a=20 b=10                                      
{ int t;                                                                 
outside function a=20 b=10
t = *a;
*a = *b;
*b = t;
printf("inside function a=%d b=%d\n", *a, *b); }
Call by reference example
#include <stdio.h>
int callbyvalue(int * num)
{
*num=*num+10;
printf(" value of num inside function is %d\n",*num);
}
void main()
{
int a=7;

printf(" value of a before function call is %d\n",a);


callbyvalue(&a);
printf(" value of a after function call is %d\n",a);
}
Output is
value of a before function call is 7

value of num inside function is 17

value of a after function call is 17


Call by reference-explanation
• While passing parameter using call by address
scheme , we are passing the actual address of
the variable to the called function.
• Any updates made inside the called
function will modify the original copy since
we are directly modifying the content of the
exact memory location.
Swap 2 variables
#include <stdio.h>
using call by value
int callbyvalue( int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf(" value of x and y inside function is %d and %d\n",x,y);
}
void main()
{
int a=10,b=20;

printf(" value of a and b before function call is %d and %d\n",a,b);


callbyvalue(a,b);
printf(" value of a and b after function call is %d and %d\n",a,b);
}
Output is
Swap 2 variables using call by reference
#include <stdio.h>
int callbyvalue( int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf(" value of x and y inside function is %d and %d\n",*x,*y);
}
void main()
{
int a=10,b=20;

printf(" value of a and b before function call is %d and %d\n",a,b);


callbyvalue(&a,&b);
printf(" value of a and b after function call is %d and %d\n",a,b);
}
Output is
Passing an array as Parameter

• Like the value of simple variables, it is also


possible to pass the values of an array to a
function.
• To pass a single dimensional array to a
function, it is sufficient to list the name of the
array without any subscripts and the size of
the array as arguments
Passing arrays to functions
For eg:
If ‘arr’ ia an integer array of size ‘n’,
this array can be passed to function named
‘display’ as follows
display(arr,n)
The function header of display is as follows
Void display(int a[],int size)
Rules to pass an Array to Function
• The function must be called by passing only
the name of the array.
• In function definition, formal parameter must
be an array type; the size of the array does not
need to be specified.
• The function prototype must show that the
argument is an array.
1. Write a program to find the sum of elements
in an array using function
The function should pass array name and length
as arguments
Array sum using function
#include<stdio.h> int a[10],limit,i;
void arraysum(int a[ ], int n) printf("enter limit");
{ int i,sum=0; scanf("%d",&limit);
for(i=0;i<n;i++)
printf("enter elements");
{
for(i=0;i<limit;i++)
sum=sum+a[i]; scanf("%d",&a[i]);
}
printf("sum of array arraysum(a,limit);
elements is %d",sum);
} }
void main()
{
Pgm to display all numbers between
50 and 100 in a given array
#include<stdio.h> int a[10],limit,i;
void range(int a[], int n) printf("enter limit");
{ int i; scanf("%d",&limit);
for(i=0;i<n;i++)
{ printf("enter elements");
if( (a[i]>50) && (a[i]<100)) for(i=0;i<limit;i++)
printf(" %d",a[i]); scanf("%d",&a[i]);
}
range(a,limit);
}
void main() }
{
Pgm to display all positive numbers in
given array
#include<stdio.h> int a[10],limit,i;
void positive(int a[], int n) printf("enter limit");
{ int i; scanf("%d",&limit);
for(i=0;i<n;i++)
{ printf("enter elements");
if( a[i]>0) for(i=0;i<limit;i++)
printf(" %d",a[i]); scanf("%d",&a[i]);
}
positive(a,limit);
}
void main() }
{
Predict the output
#include<stdio.h>
void square(int newarray[],int n)
{ int i,sum=0; }
void main()
for(i=0;i<n;i++) {
{ int a[10]={1,2,3,4,5};
newarray[i]=newarray[i]*2; int i;
square(a,5);
} printf(" newarray is");
for(i=0;i<n;i++)
{
printf(" %d",newarray[i]); }
}
Output is
newarray is 2 4 6 8 10
Predict the output
#include<stdio.h>
void square(int newarray[],int n) void main()
{ int i,sum=0; {
int a[10]={1,2,3,4,5};
for(i=0;i<n;i++) int i;
{ square(a,5);
newarray[i]=newarray[i]*2; printf(" original array is");
} for(i=0;i<5;i++)
printf(" newarray is"); {
for(i=0;i<n;i++) printf(" %d",a[i]);
{ printf(" %d",newarray[i]); }
}} }
Output is
Recursion
Recursion
• In some problems, it may be natural to define
the problem in terms of the problem itself.
• Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
• Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
Recursion

• A function is recursive if it calls itself and has


a termination condition.
• Termination condition is necessary to stop the
function from calling itself.
• termination condition will be the base case
where the problem can be solved without
further recursion.

• A recursion can lead to an infinite loop, if the


base case is not met in the calls. 
Predict the output
#include <stdio.h>
void helo()
{
printf( "hello");
helo();
}
void main()
{
helo();
}
Eg of a recursive function---
factorial of a number

Example: 
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1 
Replacing the calculated values gives us the following expression 
4! = 4 * 3 * 2 * 1 

Generally we can say: Recursion in computer science is a method


where the solution to a problem is based on solving smaller
instances of the same problem. 
Factorial using recursion
#include<stdio.h>
int fact( int n)
{
if (n<=1)
return 1;
else
return(n * fact(n-1));
}

void main()
{ int limit,f;
printf("enter the limit");
scanf("%d",&limit);
f=fact(limit);
printf("factorial is %d", f);
}
• fact(5): 5 is not 0, so fact(5) = 5 * fact(4)
• what is fact(4)? fact(4): 4 is not 0,
• so fact(4) = 4 * fact(3)
• what is fact(3)? fact(3): 3 is not 0, so fact(3) = 3 * fact(2)
• what is fact(2)? fact(2): 2 is not 0, so fact(2) = 2 * fact(1)
• what is fact(1)? fact(1): 1 is not 0, so fact(1) = 1 * fact(0) what is fact(0)?
fact(0): 0 IS 0, so fact(0) is 1Now lets gather our result.
• fact(5) = 5* fact(4)substitute in our result for fact(4)
• fact(5) = 5 * 4 * fact(3)substitute in our result for fact(3)
• fact(5) = 5 * 4 * 3 * fact(2)substitute in our result for fact(2)
• fact(5) = 5 * 4 * 3 * 2 * fact(1)substitute in our result for fact(1)
• fact(5) = 5 * 4 * 3 * 2 * 1 * fact(0)substitute in our result for fact(0)
• fact(5) = 5 * 4 * 3 * 2 * 1 * 1 = 120
Advantages of recursion

• Recursive functions make the code look clean


and elegant.
• A complex task can be broken down into
simpler sub-problems using recursion.
• Sequence generation is easier with recursion
than using some nested iteration.
Disadvantages of recursion

• Sometimes the logic behind recursion is hard


to follow through.
• Recursive calls are expensive (inefficient) as
they take up a lot of memory and time.
• Recursive functions are hard to debug.
Fibanacii series using recursion
#include<stdio.h>
int fib( int n)
{

if (n <= 1)
return n;
else
return(fib(n-1) + fib(n-2));
}
void main()
{
int limit,i;
printf("enter the limit ");
scanf("%d",&limit);
for(i=0;i<limit;i++)
printf(" %d",fib(i));
}
Sum of first numbers using recursion

#include<stdio.h>
int sumn( int n)
{

if (n<1)
return n;
else
return (n+sumn(n-1));

}
void main()
{

int limit;
printf("enter the limit ");
scanf("%d",&limit);
printf(" sum of first n numbers is %d",sumn(limit));
}
Sum of digits of a number using recursion

#include<stdio.h>
int sumdigit( int n)
{

if (n ==0)
return 0;
else
return(n%10 + sumdigit(n/10));

}
void main()
{

int num;
printf("enter the number ");
scanf("%d",&num);
printf("sum of digits is %d",sumdigit(num));
}
Structures
Structures

• A Structure is a collection of related data


items, possibly of different types.
• A Structure is heterogeneous in that it can be
composed of data of different types.
• In contrast, array is homogeneous since it can
contain only data of the same type.

88
If mark of student to be stored, then we can
follow two approaches:

• 1) Construct individual arrays, one for storing


names, another for storing mark

• 2) Use a structure variable.


main( ) 1st approch
{
char name[3][10] ;
float mark[3] ;
int i ;
printf ( "\nEnter names, mark of 3 students\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
scanf ( "%s %d", name[i], &mark[i]);

printf ( "\nAnd this is what you entered\n" ) ;


for ( i = 0 ; i <= 2 ; i++ )
printf ( "%s %d\n", name[i], mark[i] );
}
And here is the sample run...
And this is what you entered
nEnter names, mark of 3 students
jain 12.000000
jain 12.000000
anu 34.000000
anu 34.000000
sinu 3.000000
sinu 3.000000
• The program becomes more difficult to handle
as the number of items relating to student go
on increasing.
• For example, we would be required to use a
number of arrays, if we also decide to store
name of the course, name of subject, etc.
• To solve this problem, C provides a special
data type—the structure.

A structure contains a number of data types


grouped together.
These data types may or may not be of the
same type.
Structures
• Examples:
– Student record: student id, name, gender, start
year, …
– Bank account: account number, name, balance, …
– Address book: name, address, telephone number,

92
Structures

• Individual components of a structure type


are called members (or fields).
• Members can be of different types

93
struct basics
• Definition of a structure:
• struct keyword is used to define a structure.
Each identifier
struct <struct-name>{ defines a member
<type> <identifier>; of the structure.
<type> <identifier>;
...
} ;

• Example: The “Date” structure


struct Date {
int day; has 3 members,
int month;
int year; day, month & year.
} ;
94
struct examples
• Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age; structure has 5 members
char Gender;
char Name[15]; of different types.
char Course[9];
};

95
Declaring Structure Variables

• It is possible to declare variables of  structure,


after the structure is defined. 
• Structure variable declaration is similar to the
declaration of variables of any other data types.
• Structure variables can be declared in following
two ways.
– 1) Declaring Structure variables separately
– 2) Declaring Structure Variables with Structure
definition
Declaring Structure Variables with Structure
definition
struct Student
{
char name[20];
int age;
int rollno;
} S1;

Here S1 is variable of structure Student.


Declaring Structure Variables with Structure
definition
struct Student
{
char name[20];
int age;
int rollno;
} S1, S2 ;

Here S1 and S2 are variables of structure Student.


Declaring Structure variables separately

struct Student
{
char[20] name;
int age;
int rollno;
};
Main()
struct Student S1 , S2; //declaring variables of Student
This statement sets aside space in memory.
It makes available space to hold all the elements in the structure
Accessing Structure Members
•  structure variable followed by dot . operator (also
called period or member access operator.)
struct Book
{
char name[15];
int price;
int pages;
} b1 ;
Reading variable
1. b1.price=200;
2. scanf() to give values to structure members through terminal.
scanf(" %s ", b1.name);
scanf(" %d ", &b1.price);
Structure Initialization(method1)

• Like any other data type, structure variable


can also be initialized at compile time.
struct book
{
char authorname[100];
int price;
int pages;
} b1={"Dennis",200,500};//initialization
Structure Initialization(method2)

struct book
{
char authorname[100];
int price;
int pages;
};
Main()
{
struct book b1={"dennis",200,500};
}
Pgm to initialize a structure and display the
contents(method1)
#include<stdio.h>
struct book
{
char authorname[100];
int price;
int pages;
}b1={"Dennis",200,500};

void main()
{
printf("%s\n",b1.authorname);
printf("%d\n",b1.price);
printf("%d\n",b1.pages);
Pgm to initialize a structure and display the
contents(method 2)
#include<stdio.h>
void main()
{
struct book
{
char authorname[100];
int price;
int pages;
};
struct book b1={"dennis",200,500};
printf("%s",b1.authorname);
printf("%d",b1.price);
printf("%d",b1.pages);

}
Pgm to read the information about one books
from keyboard and print the result
#include<stdio.h>
void main()
{
struct book
{
char authorname[100];
int price;
int pages;
};
struct book b1={"dennis",200,500};
printf("%s",b1.authorname);
printf("%d",b1.price);
printf("%d",b1.pages);

}
Array of Structures

• In our sample program, to store data of 100


books we would be required to use 100
different structure variables from b1 to b100,
which is definitely not very convenient.
• A better approach would be to use an array
of structures
Arrays of structures
• An ordinary array: One type of data

0 1 2 … 98 99

• An array of structs: Multiple types of data in


each array element.

0 1 2 … 98 99 109
Array of structures
Structure is used to store the information of One
particular object but if we need to store such 100
objects then Array of Structure is used.
Example :
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}Book[100];
Explanation :

Here Book structure is used to Store the


information of one Book.
In case if we need to store the Information of
100 books then Array of Structure is used.
b1[0] stores the Information of 1st Book ,
b1[1] stores the information of 2nd Book and So
on
We can store the information of 100 books.
Pgm to read the information about n books from
keyboard and print the details
#include<stdio.h>
struct book
{
char authorname[100];
int price;
int pages;
};

void main()
{
struct book b1[100];
int i,n;
printf("Enter limit");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter author name");
scanf("%s",&b1[i].authorname);
printf("Enter book price");
scanf("%d",&b1[i].price);
printf("Enter number of pages");
scanf("%d",&b1[i].pages);
}
for(i=0;i<n;i++)
{
printf("%s\n",b1[i].authorname);
printf("%d\n",b1[i].price);
printf("%d\n",b1[i].pages);
}
}
Pgm to read the information about n books from
keyboard and print the total price of books
#include<stdio.h>
void main()
{
struct book
{
char authorname[100];
int price;
int pages;
};
struct book b1[10];
int i,n,total=0;
printf("Enter limit");
scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("Enter author name");


scanf("%s",&b1[i].authorname);
printf("Enter book price");
scanf("%d",&b1[i].price);
printf("Enter number of pages");
scanf("%d",&b1[i].pages);
}
for(i=0;i<n;i++)
{
printf("%s\n",b1[i].authorname);
printf("%d\n",b1[i].price);
total=total+b1[i].price;
printf("%d\n",b1[i].pages);
}

printf("\n total price is%d",total);

}
Copying structure elements
1. copying every element of structure one by
one.

2. copying all elements at one go


#include<stdio.h>
#include<string.h>

struct employee
{
char name[10] ;
int age ;
float salary ;
} e1,e2,e3;

void main( )
{
struct employee e1 = { "Anu", 30, 5500.50 } ;

printf("details of object e1\n");


printf ( "\n%s %d %f\n", e1.name, e1.age, e1.salary ) ;
/* copying every element of structure one by one */
strcpy ( e2.name, e1.name ) ;
e2.age = e1.age ;
e2.salary = e1.salary ;
printf("details of object e2\n");
printf ( "\n%s %d %f \n", e2.name, e2.age, e2.salary ) ;
/* copying all elements at one go */
e3 = e1 ;

printf("details of object e3\n");


printf ( "\n%s %d %f\n", e3.name, e3.age, e3.salary ) ;
}
• Prepare ranklist of n student.input
name,rollno,mark of 3 sub,output rank, name
and total mark

JAIN STOBLE B 119


#include<stdio.h>
#include<string.h>
struct student
{
int m1,m2,m3,total,rno;
char name[20];
}s[60],t;

main()
{
int n,j,i;
printf("\nenter number of students\t");
scanf("%d",&n);
JAIN STOBLE B 120
• for(i=0;i<n;i++)
{
printf("\nenter roll number\t");
scanf("%d",&s[i].rno);
printf("\nenter name\t");
scanf("%s",s[i].name);
printf("\nenter mark of 3\t");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
}

JAIN STOBLE B 121


for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(s[j].total<s[j+1].total)
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}

JAIN STOBLE B 122


printf("\n################MARKLIST#################");
printf("\nRANK\tROLLNUMBER\tNAME\tMARK");
for(i=0;i<n;i++)
{
printf("\n%d\t%d",i+1,s[i].rno);
printf("\t\t");
printf("%s",s[i].name);
printf("\t");
printf("%d",s[i].total);
}
}

JAIN STOBLE B 123


Union
Union
• C Union is also like structure, i.e. collection of
different data types which are grouped
together.
• Each element in a union is called member.
• Union and structure in C  are same in
concepts, except allocating memory for their
members.
Union
• Structure allocates storage space for all its members
separately.
• All of the members of union share the same memory space
• We can access only one member of union at a time.

• But, structure can access all member values at the same


time.
– This is because, Union allocates one common storage space for all its
members.
– Where as Structure allocates storage space for all its members
separately.
Allocation of memory for structure object

struct student
{
      int rollno;
      char gender;
      float marks;
}s1;
Allocation of memory for union object
Union student
{
      int rollno;
      char gender;
      float marks;
}s1;
#include<stdio.h> union books
void main() {
{ char authorname[100];
struct book int price;
{ int pages;
char authorname[100]; }b2;
int price; printf("size of union object
int pages; %d\n",sizeof(b2));
}b1;
}
printf("size of structure
object%d\n",sizeof(b1));
}
Output is
Size of structure object is 108
Size of union object is 100
• More memory is allocated to structures than union

• As seen in the above example, there is a difference in


memory allocation between union and structure.
• The amount of memory required to store a structure
variable is the sum of memory size of all members.

• But, the memory required to store a union variable is


the memory required for the largest element of an
union.
• In the case of structure, all of its members can
be accessed at any time.
• But, in the case of union, only one of its
members can be accessed at a time and all
other members will contain garbage values.
#include <stdio.h>
union job
{
char name[32];
float salary;
int workerNo;
} job1;

void main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);

printf("Enter salary: \n");


scanf("%f", &job1.salary);

printf("Displaying\nName :%s\n", job1.name);


printf("Salary: %.1f", job1.salary);

}
Output

Enter name
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary
Salary: 1234.2
Note: 
• You may get different garbage value for the name.
• Initially in the program, Hillary is stored
in job1.name and all other members of job1, i.e.
salary, workerNo, will contain garbage values.
• But, when user enters the value of salary, 1234.23
will be stored in job1.salary and other members, i.e.
name, workerNo, will now contain garbage values.
• Thus in the output, salary is printed accurately
but, name displays some random string.
• Advantage of union over structure

It occupies less memory because it occupies


the memory of largest member only.

• Disadvantage of union over structure

It can store data in one member only.


sizeof operator

• sizeof operator is used to calcualte the size of


data type or variables.

• sizeof operator will return the size in integer


format.

• sizeof operator syntax looks more like a function


but it is considered as an operator in c
programming
example
#include<stdio.h> Output :

Void main() {
4
int ivar = 100; 1
char cvar = 'a'; 4
float fvar = 10.10;
Or
printf(“\n %d", sizeof(ivar));
2
printf(“ \n%d", sizeof(cvar));
printf(“\n %d", sizeof(fvar)); 1
} 4
Storage class in C
storage class
• In C language, each variable has a storage
class
• The storage class of a variable in C determines
– life time of the variable .
– variable's storage location (memory or registers),
– The scope (visibility level) of the variable,
– And the initial value of the variable.
Storage classes of C will provides following information to compiler.

1. Storage area of variable


2. Scope of variable that is in which block the
variable is visible.(i.e., the portion of the program
over which the variable is recognized).

3. Life time of a variable that is how long the


variable will be there in active mode.
4. Default value of a variable if it is not initialized it.
four different storage classes in a C

1. auto
2. register
3. static
4. extern
AUTOMATIC VARIABLES
• Storage location −main Memory.
• Default initial value − An unpredictable value, which
is often called a garbage value.
• Scope − Local to the block in which the variable is
defined.
• Life − Till the control remains within the block in
which the variable is defined.
• Keyword auto is used to declare this variables
• Eg:
– auto int i;
The auto Storage Class

• The auto storage class is the default storage class for


all local variables.
• A variable declared inside a function or a block
without any storage class specification, is by default
an automatic variable.
• They are created when a function is called and are
destroyed automatically when the function exits.
• Automatic variables can also be called local variables
because they are local to a function or to local to a
block.
Predict the output
void main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output
1211 221

• where, 1211 and 221 are garbage values of i and j.


• When you run this program you may get different
values, since garbage values are unpredictable.
• So always make it a point that you initialize the
automatic variables properly, otherwise you are
likely to get unexpected results.
• Note that the keyword for this storage class is
auto, and not automatic.
The following C program demonstrates the visibility level of auto
variables.

#include <stdio.h>
int main( )
{
auto int i = 1;
{
auto int i = 2;
{
auto int i = 3;
printf ( "\n%d ", i);
}
printf ( "%d ", i);
}
printf( "%d\n", i);
}
The output
321

• Note that the Compiler treats the three i’s as totally


different variables, since they are defined in
different blocks.
• Once the control comes out of the innermost block
the variable i with value 3 is lost, and hence the i
in the second printf( ) refers to i with value 2.
• Similarly, when the control comes out of the next
innermost block, the third printf( ) refers to the i
with value 1.
Example of auto storage class

#include<stdio.h> }

void increment();
void main()
{
increment();
increment();
increment();
increment();
}
void increment()
{
auto int i = 0 ;
printf ( "%d", i ) ;
i++;
Register Storage Class

• Storage - CPU registers.


• Default initial value - Garbage value.
• Scope - Local to the block in which the variable is
defined.
• Life - Till the control remains within the block in
which the variable is defined.
• Keyword register is used to declare this variables
• Eg:
– register int i;
Register storage class
• Register variables are also local variables, but
stored in register memory. Whereas, auto
variables are stored in main CPU memory.
• A register declaration is equivalent to
an auto declaration,
• but hints that the declared variable will be
accessed frequently; therefore they are placed in
CPU registers, not in memory.
•  if a variable is declared register, & (address of)
operator may not be applied to it, explicitly or
implicitly.
Advantages and limitations
• Advantages: The register variables are faster than
remaining variables, because register variable are
stored in register memory not in main memory.

• Limitation: only limited variables can be used as


register since register size is very low. (16 bits, 32 bits
or 64 bits).
Register Storage Class Eg:

• A good example of frequently used variables is loop


counters. We can name their storage class as register.

Void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Explanation of above code
• Here, even though we have declared the storage class of
i as register, we cannot say for sure that the value of i
would be stored in a CPU register.
• Because the number of CPU registers are limited, and
they may be busy doing some other task.
• What happens in such an event...
• the variable works as if its storage class is auto.
Eg of register storage class
#include <stdio.h>

#include <stdio.h>
int main()
{ register int i = 10;
printf("Value of i: %p", &i);
}
• Output is
//error: address of register variable requested
Static Storage Class
• Storage −main Memory.
• Default initial value − Zero.
• Scope − Local to the block in which the variable is
defined.
• Life − Value of the variable persists between different
function calls. ie they retain the latest value
• Keyword static is used to declare this variables
• Eg:
– static int i;
The static Storage Class

• A static variable tells the compiler to persist


the variable until the end of program.
• ie they retain the latest value.
• Instead of creating and destroying a variable
every time when it comes into and goes out of
scope, static is initialized only once and
remains into existence till the end of program.
Example of static storage class
void test(); //Function declaration or function prototype

Void main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
12 3
#include <stdio.h>
void main()
{ test();
test();
}
void test()
{ static int a = 1;
int b=1;
printf("static is%d\t\n",a);
printf("auto is%d\t\n",b);
a = a+1;
b= b+1;
}
static is1

auto is1

static is2

auto is1
EXTERNAL (GLOBAL) STORAGE CLASS
EXTERNAL (GLOBAL) VARIABLES

• Storage −main Memory(RAM).


• Default initial value − Zero.
• Scope − Global.
• Life − till the end of program.
• Keyword extern is used to declare this variables
• Eg: extern int i;
The extern storage class
• Variables defined out side the functions are called external or
global variables.
• if variables declared above function definition it can be
accessed in function
• If variable declared below function definition it can’t be
accessed from the functions.
The extern storage class
The extern keyword is used to give reference of a global
variable that is already declared somewhere else.
The extern declaration does not allocate storage for
variables.
When extern specifier is used with a variable declaration
then no storage is allocated to that variable and it is
assumed that the variable has already been defined
elsewhere in the program.
Predict the output

#include<stdio.h>
int x=10;
void main()
{
printf("x=%d",x);

}
• Output is x=10

JAIN STOBLE B 170


Predict the output
#include<stdio.h>
void main()
{
printf("x=%d",x);

}
int x=10;
Output is
Error: undefined symbol “x” in function main().

JAIN STOBLE B 172


Predict the output

#include<stdio.h>

void main()
{
extern int x;
printf("x=%d",x);

}
int x=10;
Output is
x=10

JAIN STOBLE B 174


Predict the output

#include<stdio.h>

void main()
{
extern int x=20;
printf("x=%d",x);

}
int x=10;
Output is
Error :'x' has both 'extern' and initializer

JAIN STOBLE B 176


#include <stdio.h>
int x = 32;
int b = 8;
int main()
{
printf("The value of extern variables x and b : %d,%d\n",x,b);
x = 15;
fun();
printf("The value of modified extern variable x : %d\n",x);
return 0;
}
void fun()
{ extern int x;
x=x+1;}
The value of extern variables x and b : 32,8

The value of modified extern variable x : 16


#include <stdio.h>
void main()
{ int i;
for(i=0;i<4;i++)
funX();}
void funX()
{ static int i=1;
i*=2;
printf("%d\t",i);}
Main
memory

Main
memory

Main
memory
Predict the output
#include<stdio.h>
void display(); // function declaration or prototype
void main()
{
printf("x=%d",x);
display();
}
int x=10; /* defining external variable */
void display()
{
printf("\nx=%d",x);
x=x+50;
}
Output is
Error: undefined symbol “x” in function main().
Explanation
• Here in this example, x is an external variable because
declared outside both the function main() and display().
Because it is defined below to the main() and above to the
display(), It is global to display() but, not to the main().
Hence x can’t be accessed from the main(), which results
error.
• It can be rectified by declaring the external variable x in
the main() using the storage class specifier extern.
• It informs the compiler that, x is an external variable
defined some where else in the code and capable to get
into the main().
Predict the output
#include<stdio.h>
void display();
void main()
{
extern int x;
printf("x=%d",x);
display();
printf("\nx=%d",x);

}
int x=10; /* defining external variable */
void display()
{
printf("\nx=%d",x);
x=x+50;
}
Output is

You might also like