Professional Documents
Culture Documents
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
2. Function definition
3. Function call
Function definition
#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
}
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 :
– 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;
Example:
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1
Replacing the calculated values gives us the following expression
4! = 4 * 3 * 2 * 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
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
88
If mark of student to be stored, then we can
follow two approaches:
92
Structures
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>;
...
} ;
95
Declaring Structure Variables
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)
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
0 1 2 … 98 99
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 :
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++)
{
}
Copying structure elements
1. copying every element of structure one by
one.
struct employee
{
char name[10] ;
int age ;
float salary ;
} e1,e2,e3;
void main( )
{
struct employee e1 = { "Anu", 30, 5500.50 } ;
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;
}
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
void main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);
}
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
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. 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
#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
#include<stdio.h> }
void increment();
void main()
{
increment();
increment();
increment();
increment();
}
void increment()
{
auto int i = 0 ;
printf ( "%d", i ) ;
i++;
Register Storage Class
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
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
#include<stdio.h>
int x=10;
void main()
{
printf("x=%d",x);
}
• Output is x=10
}
int x=10;
Output is
Error: undefined symbol “x” in function main().
#include<stdio.h>
void main()
{
extern int x;
printf("x=%d",x);
}
int x=10;
Output is
x=10
#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
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