POP (BPOPS103) - Module-3
POP (BPOPS103) - Module-3
: 3
MODULE 3:
1. INTRODUCTION
Every C program should consist of one or more functions. Among these functions
main( ) function is compulsory. All programs start execution from main( ) function.
Functions are independent program modules that are designed to carry out a particulartask. In functions we
have two types:
1. Managing huge programs and software packages is easier by dividing them into
functions/modules—Maintenance is easier
2. Error detection is easier—Debugging is easier
3. Functions once written can be re-used in any other applications – Reusability is
enhanced
4. We can protect our data from illegal users—Data protection becomes easier
Following block diagram explains how functions are useful:Instead of writing entire program (to add and
main( ) Subtract ( )
main( ) calls add( ) completes the work
and returns back to
main( )
subtract) within main( ) function we can write independent modules add( ) and subtract( ) as shown:
Note: As shown in the above diagram, function can accept any number of inputs butone value as
output.
2. MODULAR PROGRAMMING
4. All modules are designed as single-entry, single-exit systems using control structures.
5. A module can be called by one and only higher module.
i. Function definition
ii. Function call
iii. Function declaration/Function prototype
DEFINITION OF FUNCTIONS
All the above six elements are grouped into two parts. Namely:
➢ Function header (First three elements)
➢ Function body (Second three elements)
Syntax:
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
executable statement2;
......
......
return statement;
}
The first line function_type function_name(parameter list) is known as the function
header and the statements within opening and closing braces is known as the function body.
i. Function Header: It consists of three parts: Function type, function name and formal
parameter list. The semicolon is not present at the end of header.
Function type:
➢ The function type specifies the type of value that the function is expected to
return to the program calling the function.
➢ If the return type is not specified, then it is assumed as int.
➢ If function is not returning anything, then it is void.
Function name: The function name is any valid C identifier and must follow same rulesas of other variable.
Formal Parameter List:The parameter list declares the variables that will receive the data sent by the
calling program which serves as input and known as Formal ParameterList.
ii. Function Body: The function body contains the declarations and statements necessary
for performing the required task. The body is enclosed in braces, contains three parts:
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.
FUNCTION DECLARATION
Syntax:function_type function_name(parameter_list);
Ex: int sum(int, int);
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
4. CATEGORIES OF FUNCTIONS
User defined
functions
➢ 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.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
4b
➢ The calling function accepts the input, checks its validity and pass it on to the
called function.
➢ The called function does not return any values back to calling function.
➢ The actual and formal arguments should match in number, type and order as
shown in Figure 3.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
Figure 4: Arguments matching between the function call and the called function
void show(int);
1 Description of user defined function marked in the
int main( ) example given is:
2
1. function prototype of show( ) has an
{ integer parameter ‘int’
2. calling function main ( )
int num=5; 3. actual parameter ‘num’ is passed to
show(num); 3 function show( )
4. formal parameter ‘no’contains value 5
copied from ‘num’ and displays it on
}/* end of main */
screen
{ 4
printf(“%d”, no);
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
In this example a photocopy of value stored in ‘num’ (i.e. 5) is made in ‘no’ and finallydisplayed on screen.
Next let us discuss functions with parameters and return values
➢ The calling function sends the data to called function and also accepts the return
values from called function.
➢ Actual Parameters: When a function is called, the values that are passed in the call
are called actual parameters.
➢ Formal Parameters:The values which are received by the function, and are
assigned to formal parameters.
return(sq * sq); 4
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
➢ The calling function does not send any data to called function and but, accepts the
return values from called function.
➢ Global Variables: These are declared outside any function, and they can be
accessed on any function in the program.
➢ Local Variables: These are declared inside a function, and can be used only
inside that function.
int SquareMaker ( ); 1
2
int main( ) Description of user defined function marked in
the example given are:
{
1. function prototype of SquareMaker( )
int square; has an integer no parameter but return
type is ‘int’
square=SquareMaker( ); 2. calling function
3
3. No parameter is passed to function
printf(“Square of number is %d”, square); SquareMaker( ) while calling it
4. SquareMaker( ) calculates square of
} ‘num’ and returns that value back to
main( )
int SquareMaker( )
int num;
Note: Function call can be an expression like: “square=SquareMaker( )” only in functions with
return values. Void function call cannot be an expression.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
5. Inter-Function Communication
Two functions can communicate with each other by two methods:
In pass-by-value the calling function sends the copy of parameters (ActualParameters) to the called
function (Formal Parameters).
void main()
void swap( int x, int y )
{
int a=5, b=10; {
int temp;
swap(a, b);
temp=x;
printf(“%d %d”, a,b);
x=y;
}
y=temp;
}
y=temp /* copies 5 to y */
Value in b=10 Copied to y Thus x and y values got swapped, but problem is a and b
values remain unchanged!
So pass by value method fails here!
} *y=temp;
6. NESTING OF FUNCTIONS
A function within a function is called as nesting of functions.
}
float checkno(float b)
{
if(b!=0)
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
return 0;
else
return 1;
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
9. RECURSION
Limitations of Recursion
➢ Recursive solutions may involve extensive overhead because they use function
calls.
➢ Each time you make a call, you use up some of your memory allocation. If recursion
is deep, then you may run out of memory.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
PROGRAMS
1. Write a C program to find a factorial of number using recursion.
#include<stdio.h>int
fact(int);
void main( )
{
int n,res;
printf(“enter the number to find its factorial\n”);scanf(“%d”,&n);
res=fact(n);
printf(“factorial of %d=%d”,n,res);
}
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}
Storage classes in C
auto: This is the default storage class for all the variables declared inside a function or a block.
• Hence, the keyword auto is rarely used while writing programs in C language.
• Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines
their scope).
• Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was
declared.
• They are assigned a garbage value by default whenever they are declared.
extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used.
• Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well.
• So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used
elsewhere.
• It can be accessed within any function/block.
• Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in
any function/block.
• This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only.
• The main purpose of using extern variables is that they can be accessed between two different files which are part of a large
program.
static: This storage class is used to declare static variables which are popularly used while writing programs in C language.
• Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables
preserve the value of their last use in their scope.
• So we can say that they are initialized only once and exist till the termination of the program.
• Thus, no new memory is allocated because they are not re-declared.
• Their scope is local to the function to which they were defined.
• Global static variables can be accessed anywhere in the program.
• By default, they are assigned the value 0 by the compiler.
register: This storage class declares register variables that have the same functionality as that of the auto variables.
• The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free registration
is available.
• This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime
of the program.
• If a free registration is not available, these are then stored in the memory only.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
• Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which
improves the running time of the program.
• An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
ARRAYS
Now suppose we have to store values into these variables then 50 scanf statements or initializing 50 values
has to be done as shown:
scanf(“%d”,
&marks_1);
scanf(“%d”,
&marks_2);
scanf(“%d”,
&marks_3);
………………..scanf(“%d”, &marks_50);
OR
marks_1=
25;
marks_2=23;
marks_3=20;
………….. so on marks_50=21;
This style of programming is fine for a small set of values. But if we have to store 1000 or 10000 values
declaring so many variables is a cumbersome process. Alternative solution is Arrays!
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
2. DEFINITION OF ARRAYS
3. TYPES OF ARRAYS
I. One-Dimensional Arrays: A list of items can be given one variable name using only
one subscript and such a variable is called a single subscripted variable or one dimensional
array.
➢ Here marks is the name of the array which is capable of storing 4 integer values. The
first value will be stored in marks[0], the second value will be stored in marks[1] and so on
and the last value will be in marks[3].
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
Declaration of One-Dimensional Array: Here is general syntax for array declaration along
with examples.
float temperature[5];
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
b) Initialization without size: We needn’t have to specify the size of array provided we
are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
d) Initializing all the elements zero: If we want to store zero to all the elements in the
array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};
2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example:
printf(“Enter the marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Note: Every iteration of for loop will help us to fill values into marks array (i.e. marks[0]=95, marks[1]=35,
marks[2]=67, marks[3]=87)
Accessing the array elements: Accessing the array element is done using a loop statement in combination
with printf statements or any other processing statements. Example of accessing the array elements and
calculating total marks is given below:
Let us take an example program that uses a function square( ) to calculate square ofnumbers stored in an
array. In this program each array element is passed one by one.
This diagram clearly illustrates how each individual element of array num[ ] is passed tofunction square
through parameter no.
3 4 8 9 10
0 1 2 num[3]=9→ no
3 4
num[1]=4 copied → no
num[0]=3 copied to no
num[2]=8→ no
Next program illustrates how to pass an entire array to a function average( ) andcalculate average marks.
First sum of all the elements of array marks
Output:
average=71.000000
In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
71.000000
II. Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
array.
Declaration of Two-Dimensional Array: Here is general syntax for array declaration along
float city_temper[3][3];
with examples.
2. Run time initialization: Run time initialization is storing values in an array when
program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
012 1234
a b
345 5678
67 8 9 10 11 12
III. Multi Dimensional Arrays: Multidimensional arrays can have three, four or more
dimensions.
➢ A three-dimension array is an array of two dimensional arrays. It has row, column and
depth associated with it.
➢ Declaring multidimensional arrays
int table[3][5][4];
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
A[3][4][2]={
{ {{{1,2},{3,4}},{{5,6},{7,8}}}
{ 1,2},
{3,4}, 4 rows &
{5,6}, 2 columns
{7,8}
},
{ 3 depth
{ 8,9},
{10,11},
{12,13},
{14,15}
},
{
{ 8,9},
{10,11},
{12,13},
{14,15}
}
}
Bubble Sort
Bubble sort will start by comparing the first element of the array with the second element, if the first element
is greater than the second element, it will swap both the elements, and then move on to compare the second
and the third element, and so on.
#include<stdio.h>
void main( )
{
int i,j,n,temp,a[100]; printf("Enter the
value of n\n");scanf("%d",&n);
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
Selection Sort
Selection sort will start by comparing the first element with other elements and finds minimum element and
swaps, then it starts comparing by taking second element with other elements and so on.
#include<stdio.h>
void main( )
{
int a[100],i,j,n,temp,pos; printf("Enter
the value of n\n");scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
pos=j;
}
if(pos !=i )
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search an element or value in
a given array by traversing the array from the starting, till the desired element or value is found.
#include<stdio.h>
#include<stdlib.h> void )
main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
}
if(loc>=0)
printf("The element %d is found at %d \n",key,loc);else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary search on acollection, the collection
must first be sorted. The array is divided into two parts,
compared with middle element if it is not successful, then it is compared whether it is lesser or greater than
middle element. If it is lesser, search is done towards left part else right part.
#include<stdio.h>
#include<stdlib.h> void
main( )
{
int n, a[100], i, key, loc, high, low, mid;loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low +high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
{
if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
}
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
if(loc>=0)
printf("The element %d is found at %d \n",key,loc);else
printf("The search is unsuccessful\n");
}
Applications of an array:
Apart from being widely used in programming, arrays have additional applications as well:
• Used in mathematical problems like matrices etc.
• They are used in the implementation of other data structures like linked lists etc.
• Database records are usually implemented as arrays.
• Used in lookup tables by computer.
• It effectively executes memory addressing logic wherein indices act as addresses to the one-dimensional
array of memory.
PROGRAMS
1. WACP to read N integers into an array A and to
i. Find the sum of odd numbers.
ii. Find the sum of even numbers.
iii. Find the average of all numbers.
Output the results compared with appropriate headings.
#include<stdio.h>
void main( )
{
int oddsum=0, evensum=0, i ,N, A[20];float
avg;
printf(“enter the size of an array\n”);
scanf(“%d”,&N);
printf(“Enter the array elements\n”);
for(i=0;i<N;i++)
{
scanf(“%d”, &A[i]); /* reading array values*/
}
for(i=0;i<N;i++)
{
if(A[i]%2==0)
{
{
}
else }
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”);scanf(“%d”,&m,&n);
printf(“enter the elements of an array\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional array are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“%d”,a[i][j]);
printf(“\n”);
}
}
30
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
31
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
gets(str1); //Shri\0
printf("enter the string2
\n"); gets(str2); //kant\0
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}
#include<stdio.h>
#include<conio.h>void
main()
{
char s1[100],s2[100];int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
s2[i]=s1[i];
32
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 3
i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}
33