POP Module 3
POP Module 3
In modular programming, the program is divided into separate small programs called
modules. Each module is designed to perform specific function. Modules make our actual
program shorter ,hence easier to read and understand.
Advantages:
Reusability – particular set of instructions can be used repeatedly from several different
places within the program.
Easy debugging- Since each function is smaller and has a logical clarity,it is easy to locate
and correct errors in it.
TYPES OF C FUNCTIONS:
Library Function:
Library functions are in-built function in C compiler.
Ex:
main(), printf(),sqrt(),scanf() etc.,
#include<stdio.h>
Global declarations;
void function_name(parameter-list); //function declaration or function prototype
main()
{
local declarations;
statements;
function_name (parameter-list); //function call
…….
……….
}
Every C program begins from main() and program starts executing the codes inside main()
functions.
When the control of the program reaches to function_name() inside main() function, the
control of the program jumps to void function_name() and executes the code inside it.
When all the codes inside the user defined function are executed the control of the program
jumps to the statement just after function_name() from where it is called.
Function Declaration:
Every function must be declared before they are used in the program.
Function declaration gives compiler information about
o function Name
o types of arguments to be passed and
o return type
The syntax :
return_type function_name(formal-parameters);
Function call:
A function can be called by specifying its name followed by the list of arguments enclosed in the
parenthesis and separated by commas.
The Syntax:
Function Definition:
Function definition contains programming codes to perform specific task.
Syntax:
Where,
return_type is the data type that the function returns.
function_name refers the name of the function.
The formal parameters are comma separated list of variables that receive the values from
the main program when it is called.
The return statement returns the result of the function.
int sum(int a,int b);
main()
{
int a=2,b,=3,d;
d=sum(a,b);
printf(“%d”,d);
}
The arguments used in the “function declaration” are referred as formal arguments.
They are simply formal variables that accept or receive the values supplied by the calling
function.
The number of actual and formal arguments and their data types should be same.
Ex:
Program to add two integers. Make a function add integers and display sum in
main()function:
#include<stdio.h>
void display(int a)
{
printf(%d”,a);
}
void main()
{
int c[3]={2,3,4};
display(c[2]);
}
Output: 4
void main()
int m[7]={60,50,70,80,40,80,70};
average(m);
}
Output:
Aggregate marks=70
1.Function with no arguments and no return value(void and parameter less functions):
This type of functions will not have any parameter and they will not return any value
to the calling functions.
There is no data transfer between the calling function and called function.So calling
function cannot send values and hence called function cannot receive data.
#include<stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a ,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d”,sum);
}
2.Functions with no arguments and with return type:
Here there is no data transfer from the calling function to the called function.But there is
a data transfer from the called function to called function.
When the function definition returns a value the calling function receives one value from
the called function.
#include<stdio.h>
int add();
void main()
{
int sum;
sum= add();
printf(“sum=%d”,sum);
}
int add()
{
int a ,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
return sum;
}
Here there is a data transfer from the calling function to the called function.
There is no data transfer from the called function to the calling function.The
called function will have the parameters but no return type.
#include<stdio.h>
void add(int a,int b);
void main()
{
int a,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add(int a,int b)
{
sum=a+b;
printf(“Sum=%d”,sum);
}
#include<stdio.h>
int add(int a,int b);
void main()
{
int a,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum= add(a,b);
printf(“Sum=%d”,sum);
Pass by value:
When a function is called with actual parameters,the values of actual parameters are copied into
formal parameters.If the values of the formal parameter changes in the function,the values of
actual parameters are not changed.
Ex:
#include<stdio.h>
void exchange(int m,int n)
{
int temp;
printf(“before exchange\n”);
printf(“m=%d,n=%d\n”,m,n);
temp=m;
m=n;
n=temp;
printf(“after exchange\n”);
printf(“m=%d,n=%d\n”,m,n);
}
main()
{
int a,b;
a=10,b=20;
printf(“before exchange\n”);
printf(“a=%d,b=%d\n”,a,b);
exchange(a,b);
printf(“after exchange\n”);
printf(“a=%d,b=%d\n”,a,b);
}
Pass by reference:
Ex:
#include<stdio.h>
void exchange(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}
main()
{
int a,b;
a=10,b=20;
exchange(&a,&b);
printf(“a=%d,b=%d\n”,a,b);
}
PROGRAMS ON USERDEFINED FUNCTIONS:
#include <stdio.h>
int fact(int n);
void main()
{
int no,factorial;
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
#include <stdio.h>
int reverse(int n); //func declaration
void main()
{
int n,r;
reverse(n);
if(n==r)
printf(“palindrome\n”);
else
printf(“not a palindrome”);
}
int reverse(int n)
{
int digit,r;
r=0;
while(n!=0)
{
digit=n%10;
n=n/10;
r=r*10+digit;
}
return n;
3.Write a program to find GCD and LCM of two numbers using functions.
#include <stdio.h>
void main()
{
int no1,no2;
printf("Enter two Numbers\n");
scanf("%d %d",&no1,&no2);
lcm_gcd(no1,no2);
}
4.Write a program to find whether a number is prime number or not using functions
#include<stdio.h>
int isprime(int n)
{
int i;
for(i=2;i<=n/2;i++)
{
if (n%i==0)
return 0;
}
return 1;
}
int main()
{
int n,prime;
printf(“enter the number\n”);
scanf(“%d”,&n);
prime=isprime(n);
if(prime==1)
printf(“ %d is prime number \n”,n);
else
printf(“%d is not prime number \n”,n);
}
#include<stdio.h>
char newstr[100];
char str1[100],str2[100];
}
int stringcmp(char str1[],char str2[])
{
int i,len1,len2,j;
len1=stringlen(str1);
len2=stringlen(str2);
if(len1!=len2)
return 1;
for(i=0;i<=len1;i++)
if(str1[i] !=str2[i])
return 1;
return 0;
}
for(i=0,j=0;str1[i]!='\0';i++,j++)
newstr[j]=str1[i];
for(i=0;str2[i]!='\0';i++,j++)
newstr[j]=str2[i];
newstr[j]='\0';
return;
}
void main()
{
int len;
printf("enter first strings\n");
scanf("%s",str1);
printf("enter first strings\n");
scanf("%s",str2);
printf("\nlength of string 1 = %d\n",stringlen(str1));
printf("\nlength of string 2 = %d\n",stringlen(str2));
stringcat(str1,str2);
printf("\n new string=%s\n",newstr);
if (stringcmp(str1,str2)==0)
printf("\n %s and %s are same\n",str1,str2);
else
printf("\n %s and %s are not same\n",str1,str2);
}
Scope of variables
What is the Scope and Lifetime of a Variable
The scope is the variable region in which it can be used. Beyond that area, you cannot use
a variable. The local and global are two scopes for C variables. The local scope is limited
to the code or function in which the variable is declared.
Global scope is the entire program. Global variables can be used anywhere throughout
the program.
Lifetime is the life or alive state of a variable in the memory. It is the time for which a
variable can hold its memory. The lifetime of a variable is static and automatic. The static
lifetime variable remains active till the end of the program.
An automatic lifetime variable or global variable activates when they are called else they
vanish when the function executes.
#include <stdio.h>
void person()
{
// Local Variables of the function
int age = 20;
float height = 5.6;
int main()
{
person();
return 0;
}
Global Variables
The scope of the global variable is the entire program. They are not defined inside any
function and can be used in any function.
#include <stdio.h>
void function1()
{
// Function using global variable a
printf("The number is %d \n", a);
}
void function2()
{
// Function using global variable a
printf("The number is %d \n", a);
}
int main()
{
// Calling functions
function1();
function2();
return 0;
}
Storage classes
A lifetime of a variable.There are two storage location in computer:CPU registers and main
memory
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).
register:
Ex:
#include <stdio.h>
int main()
register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
printf("%d",a);
}
static:
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.
extern:
extern stands for external storage class. Extern storage class is used when we have global functions
or variables which are shared between two or more files.
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.
The main purpose of using extern variables is that they can be accessed between two different files
which are part of a large program.
Recursive Functions
A function that calls itself is known as recursion.
The rule to be followed for a recursive function is that
- Establish a boundary conditions that terminate recursive calls.
- Implement the recursive calls so that each call brings one step closer to the
solution.
Every recursive function must be provided with a way to end the recursion.
Ex:
The recursion refers to the process where a function calls itself either directly or indirectly.
1:Direct recursion
2: Indirect recursion
Direct Recursion:
Indirect Recursion:
It refers to a process where a function calls another function and that function calls back the
original function.The process of indirect recursion takes place as below.
Ex:
#include<stdio.h>
int fibonacci(int);
int main()
{
int terms;
return 0;
}
//base condition
if(num == 0 || num == 1)
{
return num;
}
else
{
// recursive call
return fibonacci(num-1) + fibonacci(num-2);
}
How it works:
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
ARRAYS
Arrays are the collection of elements of same data type.Ordered set of similar data
elements.
All the data elements of an array are stored sequentially in consecutive memory locations
one after the other in memory(RAM).
Array is a derived data type.
The elements of an array are of the same data type and each element can be accessed by
using the same name of the array.
To refer an element in the array ,the name of the array along with the position of the
element.The position of the element must be writtern within square brackets( []) . The
position of the element is enclosed within square br-ackets called “subscript” or “index”.
Each value in the array is a reference by a single name , which is the name of the array and
the subscript or index , which indicates the position of the value in the array.
The subscript is always a positive integer number,which is enclosed in pair of square brackets.
During declaration the size of the array has to be specified.This informs the
compiler to allocate and reserve the specified memory locations.
data_type array_name[array_size];
where
data_type can be a basic datatype int,float or char etc.
array_name is the name of the array which is taken from the rules of
identifier.
array_size indicatesthe number of elements in the array which is always a
positive number.
Ended with semicolon
Example : int age[5];
Here the size of the array “age” is 5 times the size of int because there are 5
elements.
i.e for int age[5],
the total amount of memory is 20bytes .(i.e 5*2)
Initialization of elements of arrays can be done in same way as ordinary variables are done when
they are declared.
Syntax:
Example:
Partial initialization:
If the number of values to be initialized is less than the size of the array,then the remaining
locations will be initialized to zero automatically by the compiler .
Example:
int age[5]={2,3};
Here,even though the exact number of elements to be used in array is not specified ,then the array
size will be set to the total number of values specified.The array size will be set automatically.
Example:
Example:
Even though the string “COMPUTER” contains 8 charecters,because it is a string ,it always ends
with null character.So the srray size is 9 bytes.(i.e string length + 1 byte for null charecter )
Example :
int age[5];
//Reading
for(i=0;i<5;i++)
{
scanf(“%d”,&age[i]);
}
//Writing
for(i=0;i<5;i++)
{
printf(“%d\n”,age[i]);
}
Programs:
1) Program to find sum and average of N numbers using 1D array.
#include<stdio.h>
main()
{
int num[100],sum=0,Avg;
int n,i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter elements one by one\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&num[i]);
}
//Adding all elements
for(i=0i<n;i++)
{
sum=sum+num[i];
}
Avg = sum/n;
printf(“Sum o f elements=%d\n”,sum);
printf(“Average of elements=%d\n”,Avg);
}
2) Program to find sum of positive and negative numbers and their average.
#include<stdio.h>
main()
{
int num[100],psum=0,nsum=0,Avg;
int n,i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter elements one by one\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&num[i]);
}
//Adding all positive and negative elements
for(i=0;i<n;i++)
{
if(num[i]>=0)
psum=psum+num[i];
else
nsum=nsum+num[i];
}
Avg =(psum+nsum)/n;
printf(“Sum o f positive numbers=%d\n”,psum);
printf(“Sum o f negative numbers=%d\n”,nsum);
printf(“Average of all numbers=%d\n”,Avg);
}
#include<stdio.h>
int main()
{
int n,i,a[100];
printf(“Till what term you want the Fibonacci series\n”);
scanf(“%d”,&n);
a[0]=0;
a[1]=1;
#include<stdio.h>
main()
{
int A[100],n,i,large,pos;
Searching:
The process of finding a particular elements in the large amount of data is called searching.
1) Linear Search
2) Binary Search
Linear Search:Sequential search
In this technique, we search for a given key item in the list in linear order one by one other.The
element to be searched is often called key item.
#include<stdio.h>
#include<stdlib.h>
main()
{
int A[20],n,i,key;
for(i=0;i<n;i++)
{
if(A[i] == key)
{
Binary Search:
This technique can be applied if the elements to be compared are either in ascending or descending
order.
For a given sorted array of n elements.Binary search is used to search for a key element by the
following steps:
1. Binary search locates the middle element of the array and compares the search value by
having the low and high boundary values as low=0,high=n-1 and finding mid as
(low+high)/2.
2. If they are equal, it displays the subscript of that element , otherwise the search is reduced
to one-half .
3. If the search value is less than the middle value of the array, the first half is searched
,otherwise the second half is searched.
4. This continues until the search value is equal to the middle value of the array or until the
search value is not found.
6) Program to perform Binary Search:
#include<stdio.h>
#include<stdlib.h>
main()
{
int A[20],n,i,key,high,low,mid;
Sorting:
More often programmers will be working with large amount of data and is necessary to arrange
them in ascending or descending order. The process of rearranging the given elements so that they
are in ascending or descending order is called sorting.
Two techniques of sorting are :
1) Bubble sort
2) Selection sort
Bubble Sort:
Simplest sorting technique. In this technique the two successive items A[i] and A[i+1] are
exchanged whenever A[i] >= A[i+1].
In step 1)
- First element i.e 7 is compared with Second element i.e 4 in the list. Since 7>4, 7 is moved
ahead of 4.
- Then Second element i.e 7 is compared with third element i.e 5,Since 7 > 5, 7 is moved
ahead.
- Again third i.e 7 and fourth element i.e 2 is compared , 7>2 if so exchange of elements is
taken place.
- Since all the other elements are of a lesser value than 7, 7 is moved to the end of the array.
NOTE: In any of the above points if the 1st elements is less than than the 2 nd elements then
exchange of elements will not take place.(in step1)
In step 2)
- 4 is compared with 5. Since 5>4 and both 4 and 5 are in ascending order, these elements are
not swapped.
- However, when 5 is compared with 2, 5>2 and these elements are in descending order.
Therefore, 5 and 2 are swapped.
In step 3)
- the element 4 is compared with 2. Since 4>2 and the elements are in descending
order, 4 and 2 are swapped.
7)Develop a program to sort the given set of N numbers using Bubble sort.
#include<stdio.h>
int main()
{
int n,i,j,A[10],temp;
Arrays with two sets of square brackets [][] are called 2D arrays.
Data elements are arranged in the matrix form-arranged in row wise and column wise in tabular
fashion.
int A[][];
int b[10][3];
int b[2][4][1];
Declaration of 2D arrays:
Syntax:
data_type array_name[size1][size2];
where
A[1][0] A[1][1]
Row1
A[2][0] A[2][1]
Row2
Initialization of 2D array:
Syntax:
data_type array_name[size1][size2]={
{a1,a2 ,…..,aN},
{b1,b2,……bN},
.
.
{z1,z2,…….zN}
};
where
Ex:
{40,5,6}
};
11 26 3
a[0][0] a[0][1] a[0][2]
40 5 6
a[1][0] a[1][1] a[1][2]
OR
11 2 3
a[0][0] a[0][1] a[0][2]
41 25 6
a[1][0] a[1][1] a[1][2]
Ex:
{4,56}
};
1 a[0][0] 2 0
a[0][1] a[0][2]
4 56 0
a[1][0] a[1][1] a[1][2]
Ex:
{4,56}
};
1 a[0][0] 2
a[0][1]
4 56
a[1][0] a[1][1]
Run time initialization:
int age[5][5],i,j;
//Reading
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&age[i][j]);
}
}
//Writing
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,age[i][j]);
}
}
Programs:
1) Write a C program to read m*n elements from the keyboard and display the m*n
elements on the screen.
#include<stdio.h>
main()
int A[10][10];
int m,n,i,j;
scanf(“%d%d”,&m,&n);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d ”,A[i][j]);
printf(“\n”);
To find addition and subtraction of the matrices ,both rows and columns should be same for both
the matrices.
A= 1 2 3
4 5 6
B= 1 2 3
4 5 6
#include<stdio.h>
main()
{
int A[10][10],B[10][10],C[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);
A= 10 12 3
4 5 6
B= 1 2 3
1 5 2
C[i][j]=A[i][j]-B[i][j]
#include<stdio.h>
main()
{
int A[10][10],B[10][10],C[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the elements of the matrix A\n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“enter the elements of the matrix B\n”);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&B[i][j]);
//subtraction of two matrices
for (i=0;i<m;i++)
for(j=0;j<n;j++)
C[i][j]=A[i][j]-B[i][j];
printf(“The resultant matrix C is\n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}
A= 1 2 3
4 5 6
= 1 4
2 5
3 6
#include<stdio.h>
main()
{
int A[10][10],B[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);
A= 1 1 1
1 3 2
B= 2 1 2
2 12 2
2 2 2
Matix multiplication 1st row*1st column then 1st row * 2nd column…
Then 2nd row *1st column,2nd row*2 nd column..
= 6 15 6
6 45 12
#include<stdio.h>
#include<stdlib.h>
main()
{
int A[10][10],B[10][10],C[10][10];
int m,n,p,q,i,j,k;
printf(“Enter the order of the matrix A\n”);
scanf(“%d%d”,&m,&n);
Extra Programs
1)A and B are two arrays each with 10 elements .Write a program to find array C
such that.
C[0] = A[0] + B[9]
C[1]= A[1] + B[8]
C[2] = A[2]+ B[7]
.
.
.
.
C[9] = A[9]+ B[0]
#include<stdio.h>
main()
{
int A[10],B[10],C[10],i,j,n;
scanf("%d",&n);
for(i=0;i<n;i++)
C[i]=A[i]+B[n-1-i];
printf("array C is\n");
for(i=0;i<n;i++)
printf("C[%d]=A[%d]+B[%d]\n",i,i,(n-1-i));
2)Write a C program to check whether the two given matrices are equal or not//
#include<stdio.h>
main()
{
int m,n,A[20][20],B[20][20],i,j;
printf(“enter the size of matrix A\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the size of matrix B\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the elements of matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“enter the elements of matrix B\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&B[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if (A[i][j]==B[i][j])
{
printf(“matrix A is equal to matrix B\n”);
return 0;
}
else
{
printf(“matrix A is not equal to matrix B\n”);
return 0;
}
}
}
}
Applications of Arrays in C
In c programming language, arrays are used in wide range of applications. Few of them are as
follows...
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.
two dimensional arrays can be used to create matrix. We can perform various operations on
matrices using two dimensional arrays.
We use single dimensional arrays to implement search algorihtms like Linear Search, Binary
Search
● Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorihtms like Insertion Sort,Bubble
Sort,Selection Sort,Quick Sort,Merge Sort, etc.,