0% found this document useful (0 votes)
3 views63 pages

Module 3

Module 3 covers functions, structures, and storage classes in programming, emphasizing modular programming as a design technique that separates functionality into independent modules. It discusses the advantages of modular programming, such as improved readability, testability, reusability, and easier collaboration, while also noting disadvantages like increased time and budget requirements. The document includes examples, definitions, and previous university questions related to functions and modular programming.

Uploaded by

nitinkshaju2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views63 pages

Module 3

Module 3 covers functions, structures, and storage classes in programming, emphasizing modular programming as a design technique that separates functionality into independent modules. It discusses the advantages of modular programming, such as improved readability, testability, reusability, and easier collaboration, while also noting disadvantages like increased time and budget requirements. The document includes examples, definitions, and previous university questions related to functions and modular programming.

Uploaded by

nitinkshaju2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-3.

Functions and structure


Syllabus:
Functions - Function definition, Function call, Function prototype, Parameter passing;
Recursion; Passing array to function; Macros - Defining and calling macros; Command line
Arguments.
Structures - Defining a Structure variable, Accessing members, Array of structures, Passing
structure to function; Union.
Storage Class - Storage Classes associated with variables: automatic, static, external and
register.

What is modular programming?


The concept of modular programming originated in the 1960s to help users.
Programmers began to divide the more extensive programs into smaller parts.

Definition
Modular programming is defined as a software design technique that focuses on
separating the program functionality into independent, interchangeable
methods/modules. Each of them contains everything needed to execute only one aspect
of functionality.

Talking of modularity in terms of files and repositories, modularity can be on different


levels -
o Libraries in projects
o Function in the files
o Files in the libraries or repositories

Modularity is all about making blocks, and each block is made with the help of other
blocks. Every block in itself is solid and testable and can be stacked together to create
an entire application. Therefore, thinking about the concept of modularity is also like
building the whole architecture of the application.

Examples of modular programming languages - All the object-oriented programming


languages like C++, Java, etc., are modular programming languages.

Module
A module is defined as a part of a software program that contains one or more routines. When
we merge one or more modules, it makes up a program. Whenever a product is built on an
enterprise level, it is a built-in module, and each module performs different operations and
business. Modules are implemented in the program through interfaces. The introduction of
modularity allowed programmers to reuse prewritten code with new applications. Modules
are created and merged with compilers, in which each module performs a business or routine
operation within the program.

For example - SAP(System, Applications, and Products) comprises large modules like
finance, payroll, supply chain, etc. In terms of softwares example of a module is Microsoft
Word which uses Microsoft paint to help users create drawings and paintings.

Advantages of modular programming


The following are advantages of modular programming -

o Code is easier to read - Working on modular programming makes code easier to read
because functions perform different tasks as compared to monolithic codes.
Sometimes modular programming can be a bit messy if we pass arguments and
variables in different functions. The use of modules should be done in a sensible
manner so as to avoid any problem. Functions should be neat, clean, and descriptive.
o Code is easier to test - In software, some functions perform fewer tasks and also
functions that perform numerous tasks. If the software is easily split using modules, it
becomes easier to test. We can also focus on the riskier functions during testing and
need more test cases to make it bug-free.
o Reusability - There are times where a piece of code is implemented everywhere in
our program. Instead of copying and pasting it, again and again, modularity gives us
the advantage of reusability so that we can pull our code from anywhere using
interfaces or libraries. The concept of reusability also reduces the size of our program.
o Faster fixes - Suppose there is an error in the payment options in any application, and
the bug needs to be removed. Modularity can be a great help because we know that
there will be a separate function that will contain the code of payments, and only that
function will only be rectified. Thus using modules to find and fixing bugs becomes
much more smooth and maintainable.
o Low-risk update - In modular programming, a defined layer of APIs protects things
that use it from making changes inside the library. Unless there is a change in the API,
there is a low risk for someone's code-breaking. For example, if you didn't have
explicit APIs and someone changed a function they thought was only used within that
same library (but it was used elsewhere), they could accidentally break something.
o Easy collaboration - Different developers work on a single piece of code in the team.
There are chances of conflicts when there's a git merge. This conflict can be reduced
if the code is split between more functions, files, repos, etc. We can also provide
ownership to specific code modules, where a team member can break them down into
smaller tasks.

Disadvantages of modular programming


The following are disadvantages of modular programming -

o There is a need for extra time and budget for a product in modular programming.
o It is a challenging task to combine all the modules.
o Careful documentation is required so that other program modules are not affected.
o Some modules may partly repeat the task performed by other modules. Hence,
Modular programs need more memory space and extra time for execution.
o Integrating various modules into a single program may not be a task because different
people working on the design of different modules may not have the same style.
o It reduces the program's efficiency because testing and debugging are time-
consuming, where each function contains a thousand lines of code.
Previous Years University questions:
Q.1) Explain function call, function definition and function prototype with anexample. (5)
(July 2021)
Q.2) What is the purpose of function declaration and function definition and functioncall?
With examples illustrate their syntax. (5) (January 2017)
Q.3) What are the advantages of functions? Explain how it is implemented in C Language. (4)
(May 2019)
Q.4) enumerate three advantages of using functions. (3) (January 2017)
Q.5) What are functions? Explains the different types of functions in detail with an example
program for each type. (10) (January 2017)

Functions
• A function is a named unit of a group of program statements .This unit can be invoked
from other parts of the program.
• To write a program using function it contain three parts.
1. Function declaration/ function prototype
2. Function definition
3. Function call/ Accessing a function

1. Function declaration/ function prototype


• A function prototype is a declaration of the function that tells the program about the
1. type of the value returned by the function
and
2. the number and type of arguments.
Syntax:
type function name(parameter list);
Eg: void area(int r);
int fact(int n);
Note:
void
• If a function does not return a result, declare the result type as void.

2. Function definition
• The general form of a function definition is as given below.
type function name( parameter list)
{
body of the function;
}
• Where type is the basic data type, function name is the name of the function, the parameter
list is a comma-separated list of variables of a function referred to as its arguments.

3. Function call/ Accessing a function


• A function is called / invoked by providing the function name, followed by the parameters
being sent enclosed in parentheses.
• Fact(num);
• Area(l,b);

Previous Years University questions:


Q.1) Differentiate formal and actual arguments in a function. (3) (September 2020)
Q.2) Define formal parameters and actual parameters. Illustrate with an example.(3)
(January 2017)

Note:
Actual Parameters:
The parameters that appear in a function call statement are actual parameters.
Formal parameters :
The parameters that appear in function definition are formal parameters.
Eg:
Previous Years University questions:
Q.1) What is the purpose of „return‟ statement? Can multiple „return‟ statements be
included in a function? Justify your answer. (3) (September 2020)
Q.2) give the purpose of return statement. (January 2017)

Return Statement

• A C function may or may not return a value from the function. If you don't have
to return any value from the function, use void for the return type.
• If you want to return any value from the function, you need to use any data type
such as int, long, char, etc. The return type depends on the value to be returned
from the function.
purpose of return statement
• A return statement ends the execution of a function, and returns control to the
calling function. Execution resumes in the calling function at the point
immediately following the call. A return statement can return a value to the
calling function.

Can multiple „return‟ statements beincluded in a function?


• A function can have multiple return statements but only one of them will be
executed because once a return statement is executed, the program control
moves back to the caller function skipping the remaining statements of the
current function.
Q.1) WAP to print the cube of a given number using function. (function does not return a value)

Method:1

Method:2
Q.2) WAP to print the cube of a given number using function. (function should return a value)
Q.2 ) WAP to find the factorial of a given number. (Function does not return a value)

Why are Functions Needed?


1. It makes programs significantly easier to understand and maintain by breaking up a
program into easily manageable chunks.
2. Functions may be reused in multiple programs.
3. Function can be used to protect data.
4. The another benefit of using functions is that different programmers working on one
large project can divide the workload by working different functions
Q.2) WAP to find the factorial of a given number. (function should return a value)
Q.3) WAP to check whether given number is prime or not using function.

#include<stdio.h>
#include<conio.h>
void check(int num)
{
int f=1,i; //assume given number is prime
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
f=0; //given number is not a prime
break;
}
} Output

if(f==1) Enter a number : 7


{
printf("\n %d is prime",num); 7 is prime
}
else
{
printf("\n %d is not a prime",num);
}
}
void main()
{
int num;
clrscr();
printf("\n Enter a number : ");
scanf("%d",&num);
check(num);
getch();
return;
}
Previous Years University questions:
Write a C program to reverse a number using a function. (3) (July 2021)

#include<stdio.h>
#include<conio.h>

void rev(int num)


{
int r,rev=0;
while(num>0)
{
r=num%10;
rev=rev*10+r;
num=num/10;
}
Output
printf("\nReverse of the given number is :%d",rev);
}

void main()
{
int num;
clrscr();
printf("\nEnter a Number :");
scanf("%d",&num);
printf("\nGiven Number is : %d",num);
rev(num);
getch();
return;
}
Previous Years University questions:
Q.1) Define a C function checkprime( ) that accepts an integer argument and returns 1 if
the argument is prime, a 0 otherwise. Write a C program that invokes this function to
generate prime numbers between the given ranges. (5) (September 2020)
Q.2) Write a function for checking whether a counting number is prime or not. Using
this function write a program for displaying the prime numbers in first N
counting numbers. (5) (July 2021)

#include<stdio.h>
#include<conio.h>
int checkprime(int num)
{ Output
int i,f;
f=1;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
f=0;
break;
}
}
return f;
}

void main()
{
int i,f,l,u;
clrscr();
printf("\n Enter the lower limit");
scanf("%d",&l);
printf("\n Enter the upper limit");
scanf("%d",&u);

for(i=l;i<=u;i++)
{
f=checkprime(i);

if(f==1)
{
printf("\n%d is prime",i);
}
else
{
printf("\n%d is not prime",i);
}
}
getch();
return;
}
[Link]. Ajayakumar.M.V, Department of IT, Toc
Q.4) WAP to check whether given number is Armstrong or not.
#include<stdio.h>
#include<conio.h>
void check (int num)
{
int temp,r,sum=0;
temp=num;
while(num>0)
{
r=num%10;
sum=sum+(r*r*r);
num=num/10;
}
if(temp==sum)
{
printf("\n%d is Armstrong Number",temp);
}
else
{
printf("\n%d is not Armstrong Number",temp);
}
}

void main()
Output
{
int num;
clrscr(); Enter a number : 153
printf("\nEnter a number : ");
153 is Armstrong Number
scanf("%d",&num);
check(num);
getch();
return;
}

Previous Years University questions:


Q.1) With examples show how:
(i) an array is passed as argument of a function.
(ii) individual elements of an array is passed as argument of a function.
(5) (January 2017)

Arrays as Function Parameters


Array & function
Q,1 ) WAP to read ‘n’ numbers into the array and then display the array elements in
the reverse order using function.
#include<stdio.h>
#include<conio.h>
void rev(int A[10],int n)
{
int i;
printf("\nGiven Array elements are in the reverse
order:\n");
for(i=n-1;i>=0;i--)
{
printf("\n%d",A[i]);
}
}
void main()
{
int A[10],n,i;
clrscr();
printf("\nEnter the value of n :");
scanf("%d",&n);
printf("\nEnter the %d numbers into the array :",n); Out put

for(i=0;i<n;i++) Enter the value of n: 5


{ Enter the 5 numbers into the array:
10
scanf("%d",&A[i]); 20
} 30
40
printf("\n given array elements are :\n"); 50
for(i=0;i<n;i++) Given array elements are:
10
{ 20
printf("\n%d",A[i]); 30
40
} 50
rev(A,n); Given Array elements are in the reverse order:
50
getch(); 40
return; 30
20
} 10
Previous Years University questions:
Q.1) Write a C program to find sum and average of an array of integers using userdefined
functions. (5) (January 2017)

Q.2 ) WAP to find the sum of array elements are using function.

#include<stdio.h>
#include<conio.h>
void Arraysum(int A[10],int n)
{
int i,sum=0;
float avg;
for(i=0;i<n;i++)
{
sum=sum+A[i];
}
avg=sum/n;
printf("\n Sum =%d",sum);
printf("\n Average =%f",avg);
}
void main()
{
int A[10],n,i;
clrscr();
printf("\nEnter the value of n :");
scanf("%d",&n); Output
printf("\nEnter the %d numbers into the array :",n);
for(i=0;i<n;i++)
Enter the value of n : 5
{
scanf("%d",&A[i]); Enter the 5 numbers into the array :
10
}
20
printf("\n given array elements are :\n");
30
for(i=0;i<n;i++)
40
{
50
printf("\n%d",A[i]);
}
Given array elements are:
Arraysum(A,n);
10
getch();
20
return;
30
}
40
50

Sum = 150
Average=30.0
Q,3 ) WAP for Bubble sort using function.

#include<stdio.h>
#include<conio.h>
void Bsort(int A[10],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(A[j]>A[j+1])
{
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
}

printf("\nAfter sorting array elements are \n");


for(i=0;i<n;i++)
{
printf("\n%d",A[i]);
} Output
}

void main() Enter the value of n: 5


{ Enter the 5 numbers into the
int A[10],n,i; array:
clrscr(); 3
printf("\nEnter the value of n :"); 1
scanf("%d",&n); 5
2
printf("\nEnter the %d numbers into the array :",n); 4
for(i=0;i<n;i++) Given array elements are:
{ 3
scanf("%d",&A[i]); 1
} 5
printf("\n given array elements are :\n"); 2
for(i=0;i<n;i++) 4
{ After sorting array elements are
printf("\n%d",A[i]);
} 1
Bsort(A,n); 2
getch(); 3
return; 4
} 5
Previous Years University questions:
Q.1) Write a C program to find the largest and smallest element in an integer array
using function. (6) (DECEMBER 2018)
Q.2) Write a C program for finding the smallest of N integer numbers. (4) (July 2021)
Q.4) WAP to find the largest element from the array using function.

#include<stdio.h>
#include<conio.h>

void ArrayLargest(int A[10],int n)


{
int i,largest, smallest;
largest=A[0];
smallest=A[0];
for(i=1;i<n;i++)
{
if(A[i]>largest)
{
largest=A[i];
}
if(A[i]<smallest)
{
smallest=A[i];
}
}
printf("\n Largest element of the array is : %d",largest);
printf("\n Smallest element of the array is : %d",smallest);
}
void main() Output
{
int A[10],n,i;
clrscr(); Enter the value of n : 5
printf("\nEnter the value of n :"); Enter the 5 numbers into the array:
scanf("%d",&n); 30
printf("\nEnter the %d numbers into the array :",n); 50
for(i=0;i<n;i++) 20
{ 40
scanf("%d",&A[i]); 10
} Given array elements are:
printf("\n given array elements are :\n"); 30
for(i=0;i<n;i++) 50
{ 20
printf("\n%d",A[i]); 40
} 10
ArrayLargest(A,n); Largest element of the array is : 50
getch(); Smallest element of the array is : 10
return;
}
Q.5) WAP for Linear Search.

#include<stdio.h>
#include<conio.h>
void Lsearch(int A[10],int n,int snum)
{
int i,flag=0;

for(i=0;i<n;i++)
{
if(A[i]==snum)
{
flag=1;
break;
}
}
if(flag==1)
{
printf("\n Searching number %d is found in the array at
position: %d",snum,i+1);
}
else
{
printf("\nSearching number %d is not found in the
array",snum);
}
}
void main()
{
int A[10],n,i,snum;
clrscr();
printf("\nEnter the value of n :");
scanf("%d",&n);
printf("\nEnter the %d numbers into the array :",n);
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
printf("\n given array elements are :\n");
for(i=0;i<n;i++)
{
printf("\n%d",A[i]);
}
printf("\nEnter the searching number:");
scanf("%d",&snum);
Lsearch(A,n,snum);
getch();
return;
}
Output

Enter the value of n : 5


Enter the 5 numbers into the array:
30
50
20
40
10
Given array elements are:
30
50
20
40
10
Enter the searching number:20
Searching number 20 is found in the array at position :3

One-dimensional character array & function

Q.1) WAP to find the length of the given string using function.

#include<stdio.h>
#include<conio.h>
void slength(char str[10])
{
int i;
for(i=0;str[i]!='\0';i++)
{
}
printf("\nLength of the given String is %d",i);
}

void main()
{ Output
char str[10];
clrscr(); Enter a string : Anil
printf("\nEnter a string :");
gets(str); Given string is : Anil
printf("\n Given string is : %s",str);
slength(str); Length of the given String is 4
getch();
return;
}
Q.2) WAP to find the reverse of the given string using function.

include<stdio.h>
#include<conio.h>
void slength(char str[10])
{
int i,j;
for(i=0;str[i]!='\0';i++)
{
}
printf("\nLength of the given String is %d",i);

printf("\nReverse of the given string is :");


for(j=i-1;j>=0;j--)
{
printf("%c",str[j]); Output
}
Enter a string : anil
}
Given string is : anil
void main() Length of the given String is 4
{
char str[10]; Reverse of the given string is : lina
clrscr();
printf("\nEnter a string :");
gets(str);
printf("\n Given string is : %s",str);
slength(str);
getch();
return;
}
Q.3) WAP to check whether given string is palindrome or not using function.

#include<stdio.h>
#include<conio.h>
void pal(char str[10])
{
int i,j,l,f=1;
for(i=0;str[i]!='\0';i++) //find the length of the given string
{
}
l=i;

j=i-1;
for(i=0;i<l/2;i++)
{
if(str[i]!=str[j])
{
f=0;
break;
}
j--;
}
if(f==1)
{
printf("\nGiven string is palindrome");
}
else
{
printf("\n Given string is not palindrome");
}
}

void main()
{
char str[10];
clrscr(); Output
printf("\nEnter a String :");
gets(str); Enter a string : amma
printf("\nGiven string is : %s",str);
pal(str); Given string is : amma
getch(); Given string is palindrome
return;
}
Q.4) WAP to concatenate two strings using function

#include<stdio.h>
#include<conio.h>
void stringcon(char str1[10],char str2[10])
{
int i,j;
char str3[20];

for(i=0;str1[i]!='\0';i++)
{
str3[i]=str1[i];
}
for(j=0;str2[j]!='\0';j++)
{
str3[i+j]=str2[j];
}
str3[i+j]='\0';
printf("\n First string is : %s",str1);
printf("\n Second string is : %s",str2);
printf("\nConcatenated String is : %s",str3);
}
void main()
{
char str1[10],str2[10],str3[20]; Output
int i,j;
clrscr(); Enter the first string : anil
printf("\nEnter the first string :");
gets(str1); Enter the second string :kumar
printf("\nEnter the second string :");
gets(str2); First string is : anil
stringcon(str1,str2); Second string is : kumar
getch();
return; Concatenated String is: anilkumar
}
Previous Years University questions:
Q.5) Write a C program to find the total number of vowels in a string using a
function. (3) (July 2021)

#include<stdio.h>
#include<conio.h>
void cvowels(char str[20])
{
int i,scount=0,ccount=0,vcount=0;
for(i=0;str[i]!='\0';i++)
{
if(str[i]==' ')
{
scount++;
}
else if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||
str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
{
vcount++;
}
else
{
ccount++;
}
}
printf("\nNumber of Space=%d",scount);
printf("\nNumber of Vowels=%d",vcount);
printf("\nNumber of consonant=%d",ccount);
}
void main()
{
char str[20];

clrscr();
printf("\nEnter a String : ");
gets(str);
printf("\n Given String is :%s",str);
cvowels(str);
getch();
return;
}

Output
Two-dimensional array & function
Q.1) WAP to find the transpose of the given matrix using function

#include<stdio.h>
#include<conio.h>

void trans(int A[3][3],int r,int c)


{
int i,j;
printf("\n Transpose of Matrix A is \n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf("\t%d",A[j][i]);
}
printf("\n");
}
}

void main()
{
int i,j,m,n,A[3][3];
clrscr(); Output
printf("\nEnter the order matrix : A\n");
scanf("%d%d",&m,&n);
Enter the order matrix A : m n
printf("\n Read Matrix A\n");
Read Matrix A
for(i=0;i<m;i++)
{ 1 2
for(j=0;j<n;j++)
{ 3 4
scanf("%d",&A[i][j]);
5 6
}
} Given matrix A is
printf("\n Given matrix A is \n");
for(i=0;i<m;i++) 1 2
{
3 4
for(j=0;j<n;j++)
{ 5 6
printf("\t%d",A[i][j]);
} Transpose of Matrix A is
printf("\n");
1 3 5
}
trans(A,m,n); 2 4 6
getch();
return;
}
Q.2) WAP for Matrix Addition using function

#include<stdio.h> void main()


#include<conio.h> {
void madd(int A[3][3],int B[3][3],int m,int n) int i,j,m,n,p,q,A[3][3],B[3][3],C[3][3];
{ clrscr();
int i,j,C[3][3]; printf("\nEnter the order of Matrxi A");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++) printf("\nEnter the order of seconf matrixB");
{ scanf("%d%d",&p,&q);
for(j=0;j<n;j++) if(m==p&&n==q)
{ {
C[i][j]=A[i][j]+B[i][j]; printf("\n Read Matrix A");
} for(i=0;i<m;i++)
} {
printf("\n Given Matrix A\n"); for(j=0;j<n;j++)
for(i=0;i<m;i++) {
{ scanf("%d",&A[i][j]);
for(j=0;j<n;j++) }
{ }
printf("\t%d",A[i][j]); printf("\n Read Matrix B");
} for(i=0;i<p;i++)
printf("\n"); {
} for(j=0;j<q;j++)
printf("\n Given Matrix B\n"); {
for(i=0;i<m;i++) scanf("%d",&B[i][j]);
{ }
for(j=0;j<n;j++) }
{ madd(A,B,m,n);
printf("\t%d",B[i][j]); }
} else
printf("\n"); {
} printf("\nMatrix addition is not possible");
printf("\n Matrix C\n"); }
for(i=0;i<m;i++) getch();
{ return;
for(j=0;j<n;j++) }
{
printf("\t%d",C[i][j]);
}
printf("\n");
}

}
Output
Q.3) WAP for Matrix Multiplication using function.

#include<stdio.h> void main()


#include<conio.h> {
void matrixmul(int A[3][3],int m,int n,int int i,j,m,n,p,q,A[3][3],B[3][3],C[3][3];
B[3][3],int p,int q) clrscr();
{ printf("\nEnter the order of Matrxi A");
int i,j,k,C[3][3]; scanf("%d%d",&m,&n);
for(i=0;i<m;i++) printf("\nEnter the order of seconf matrixB");
{ scanf("%d%d",&p,&q);
for(j=0;j<n;j++) if(n==p)
{ {
C[i][j]=0; printf("\n Read Matrix A");
for(k=0;k<p;k++) for(i=0;i<m;i++)
{ {
C[i][j]=C[i][j]+A[i][k]*B[k][j]; for(j=0;j<n;j++)
} {
} scanf("%d",&A[i][j]);
} }
printf("\n Given Matrix A\n"); }
for(i=0;i<m;i++) printf("\n Read Matrix B");
{ for(i=0;i<p;i++)
for(j=0;j<n;j++) {
{ for(j=0;j<q;j++)
printf("\t%d",A[i][j]); {
} scanf("%d",&B[i][j]);
printf("\n"); }
} }
printf("\n Given Matrix B\n"); matrixmul(A,m,n,B,p,q);
for(i=0;i<p;i++) }
{ else
for(j=0;j<q;j++) {
{ printf("\nMatrix multiplication is not possible");
printf("\t%d",B[i][j]); }
} getch();
printf("\n"); return;
} }
printf("\n Matrix C\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("\t%d",C[i][j]);
}
printf("\n");
}
}
Lab cycle program
Q.1) Write a menu driven program for performing matrix addition, multiplication and
finding the transpose. Use functions to (i) read a matrix, (ii) find the sum of two
matrices, (iii) find the product of two matrices, (i) find the transpose of a matrix and (v)
display a matrix.
#include<stdio.h>
void main()
#include<conio.h>
void add(int A[3][3],int B[3][3],int m, int n)
{
{ int ch,m,n,p,q,A[3][3],B[3][3],i,j;
int C[3][3],i,j; char c;
for(i=0;i<m;i++) clrscr();
{ do
for(j=0;j<n;j++) {
{ printf("\[Link] matrix \n [Link] matrix \n [Link]
C[i][j]=A[i][j]+B[i][j]; matrix \n ");
} printf("\nEnter your choice (1-3): ");
} scanf("%d",&ch);
printf("\nResultant Matrix C\n");
switch(ch)
for(i=0;i<m;i++)
{ {
for(j=0;j<n;j++) case 1:printf("\nEnter the order of matrix A :");
{ scanf("%d%d",&m,&n);
printf("\t%d",C[i][j]); printf("\nEnter the order of matrix B :");
} scanf("%d%d",&p,&q);
printf("\n"); if(m==p&&n==q)
} {
} printf("\n Read Matrix A \n");
void mul(int A[3][3],int m,int n,int B[3][3],int p, int q) for(i=0;i<m;i++)
{
int C[3][3],i,j,k;
{
for(i=0;i<m;i++) for(j=0;j<n;j++)
{ {
for(j=0;j<q;j++) scanf("%d",&A[i][j]);
{ }
C[i][j]=0; }
for(k=0;k<p;k++) printf("\n Read Matrix B \n");
{ for(i=0;i<p;i++)
C[i][j]=C[i][j]+A[i][k]*B[k][j]; {
} for(j=0;j<q;j++)
}
{
}
printf("\nResultant Matrix C\n"); scanf("%d",&B[i][j]);
for(i=0;i<m;i++) }
{ }
for(j=0;j<q;j++) add(A,B,m,n);
{
printf("\t%d",C[i][j]); }
} else
printf("\n"); {
}
printf("\n Matrix Addition is not possible");
}

void transpose(int A[3][3],int m,int n) }


{ break;
int i,j;
printf("\nTranspose of Matrix A\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("\t%d",A[j][i]);
}
printf("\n");
}
[Link]. Ajayakumar.M.V, Department of IT, Toc H Institute of Science & Technology Page 30
}
case 2:printf("\nEnter the order of matrix A :");
scanf("%d%d",&m,&n);
printf("\nEnter the order of matrix B :");
scanf("%d%d",&p,&q);
if(n==p)
{
printf("\n Read Matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n Read Matrix B \n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&B[i][j]);
}
}
mul(A,m,n,B,p,q);

}
else
{
printf("\n Matrix Addition is not possible");

}
break;
case 3:printf("\nEnter the order of matrix A :");
scanf("%d%d",&m,&n);
printf("\n Read Matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&A[i][j]);
}
}
transpose(A,m,n);
break;

default:printf("\nInvalid choice");
}
printf("\n Do you wants to continue(y/n) :");
scanf("%s",&c);

}while(c=='y'||c=='Y');
getch();
return;
}
Previous Years University questions:
Q.1) Write a C program to find the largest element of each row of an m x n matrix and
place it in the last column of the corresponding row. Use function. (6) (December 2019)

#include<stdio.h>
#include<conio.h>
void mrlargest(int A[3][3],int m,int n)
{
int i,j,l;
printf("\n Given matrix A and Largest element of each raw\n");
for(i=0;i<m;i++)
{
``
l=A[i][0];
for(j=0;j<n;j++)
{
printf("\t%d",A[i][j]);
if(A[i][j]>l)
Output
{
l=A[i][j];
}
}
printf("\t%d",l);
l=0;
printf("\n");
}
}

void main()
{
int A[3][3],m,n,i,j;
clrscr();
printf("\nEnter the order of matrix A");
scanf("%d%d",&m,&n);
printf("\nRead the matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
` scanf("%d",&A[i][j]);
}
}
mrlargest(A,m,n);
getch();
return;
}
Two-dimensional character array & function
Q.1) WAP to sort the ‘n’ names using function.

#include<stdio.h> void main()


#include<conio.h> {
void namesort(char name[5][10],int n) int i=1,n;
{ char name[5][10];
int i,j; clrscr();
char temp[10]; printf("\nEnter the value of n:");
for(i=0;i<n;i++) scanf("%d",&n);
{ printf("\n enter the %d students name :",n);
for(j=0;j<n-1;j++) for(i=0;i<n;i++)
{ {
if(strcmp(name[j],name[j+1])>0) scanf("%s",&name[i]);
{ }
strcpy(temp,name[j]); printf("\n Given %d students names are:
strcpy(name[j],name[j+1]); \n",n);
strcpy(name[j+1],temp); for(i=0;i<n;i++)
} {
} printf("\n%s",name[i]);
} }
printf("\nAfter sorting names are :\n"); namesort(name,n);
for(i=0;i<n;i++) getch();
{ return;
printf("\n%s",name[i]); }
}
}

Output
Call by value and Call by reference
• A function can be invoked in two manners.
1. Call by value and
2. Call by reference
Note:
Actual Parameters:
The parameters that appear in a function call statement are actual parameters.
Formal parameters :
The parameters that appear in function definition are formal parameters.

Call by value Call by reference


• The call by value method copies • The call by reference method,
the value of actual parameter reference to the original
into the formal parameters. variable is passed
• In call by value method, the • In call by reference method, the
changes are not reflected back to changes are reflected back to
the original values. the original values.

Note:
• Two special operator * and & are used with pointers.
1. & : The & is a unary operator that returns memory address of its operand.
2. * (Asterisk) : The * is a unary operator that returns the value of the variable.

Q.1) WAP to swap two values, by call by value method


#include<stdio.h>
#include<conio.h>
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\nin function definition After swapping , the values are a=%d b=%d",x,y);
}

void main()
{
int a,b;
clrscr();
printf("\n Enter the values of a and b");
scanf("%d%d",&a,&b);
printf("\n Given values are , a=%d and b=%d",a,b);
swap(a,b);
printf("\n After the swap function, a=%d b=%d",a,b);
getch();
return;
}

Output
Q.2) WAP to swap two values, by call by reference method

#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\nin function definition After swapping , the values are a=%d b=%d",*x,*y);
}

void main()
{
int a,b;
clrscr();
printf("\n Enter the values of a and b");
scanf("%d%d",&a,&b);
printf("\n Given values are , a=%d and b=%d",a,b);
swap(&a,&b);
printf("\n After the swap function, a=%d b=%d",a,b);
getch();
return;
}

Output
Previous Years University questions:
Q.1) Define recursion with an example. Differentiate between iteration and recursion.
(4) (December 2019)
Q.2) Using an example, explain the concept of recursion. (5) (December 2019)
Q.3) What are the advantages of recursive function? (2) (May 2019)
Q.4) With suitable example explain what you understand by recursion. (5) (January 2017)

Recursion
• In C, a function can call itself, this is called recursion.
• A function is said to be recursive if a statement in the body of the function calls
itself.

What is needed for implementing recursion


1. Decomposition into smaller problems of same type.
2. Recursive calls must diminish problem size.
3. Necessity of base case.
4. Base case must be reached.
5. It act as a terminating condition.

Comparison Table for Advantages and Disadvantages of a Recursion


Differentiate between iteration and recursion. (4) (December 2019)
Previous Years University questions:
Q.1) Write a recursive function for finding the n! (factorial of n). (3) (July 2021)
Q.2) Write a c program to find factorial of given number using recursive function. (5) (July 2021)
Q.3) What are the advantages of recursive function? Write a recursive function using C to
find the factorial of a number. (5) (May 2019)

Q.1) WAP to find the factorial of given number using recursion

#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Output
void main()
{ Enter a number : 5
int n,res;
clrscr(); Factorial of 5 is 120
printf("\nEnter a number:");
scanf("%d",&n);
res=fact(n);
printf("\nFactorial of %d is %d",n,res);

getch();
return;
}
Previous Years University questions:
Q.1) Write a C program to print the Fibonacci series using recursion.(3) (DECEMBER 2018)
Q.2) Write a recursive function for finding the kth fibonacci number. Fibonacciseries is 1,
1, 2, 3, 5, 8, 13, 21, ........... (5) (July 2021)

Q.2) WAP to print the Fibonacci series using recursion.

#include<stdio.h>
#include<conio.h>
int fib(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fib(n-1)+fib(n-2);
}

void main()
{
int n,i,res;
clrscr();
printf("\nEnter number of terms:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
res=fib(i);
printf("\t%d",res);
}

Enter number of terms: 5


0 1 1 2 3
Previous Years University questions:
Write a C program to find the GCD of two numbers using recursive function.
(4) (December 2019)

Q.3) WAP to find the GCD of two numbers using Recursion

#include<stdio.h>
#include<conio.h>
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}

void main()
{
int a,b,res;
clrscr();
printf("\nEnter the two numbers");
scanf("%d%d",&a,&b);
res=gcd(a,b);
printf("\tgcd( %d, %d)is%d",a,b,res);

getch();
return;
}

Enter the two numbers : 7 35


gcd( 7, 35) is 7
Lab cycle program
Q.4) Find the factorial of a given Natural Number n using recursive and non recursive
functions
#include<stdio.h>
#include<conio.h>
int rfact(int n)
{
if(n==1)
return 1;
else
return n*rfact(n-1);
}
int fact(int n)
{
int res=1;
while(n>=1)
{
res=res*n;
n--;
}
return res;
}
void main()
{
int ch,n,res;
char c;
clrscr();
do
{
printf("\n1. Recursive Function \n 2. Non Recursive Function \n");
printf("\Enter your choice(1-2) :");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n Enter a number");
scanf("%d",&n);
res=rfact(n);
printf("\n Factorial of %d is %d",n,res);
break;
case 2:printf("\n Enter a number");
scanf("%d",&n);
res=fact(n); Output
printf("\n Factorial of %d is %d",n,res);
break;
default:printf("\nInvalid choice");
}
printf("\n Do you wants to continue(y/n):");
scanf("%s",&c);
}while(c=='y'||c=='Y');
getch();
return;
}
Previous Years University questions:
Q.1) Compare structure and union in C language. (3) (July 2021)
Q.2) Differentiate Structure and Union. (2) (December 2019)
Q.3) Differentiate between structure and union with example. (5) (July 2021)
Q.4) Distinguish between structures and unions with an example (5) (January 2017)
Q.5) compare structure and union (5) (January 2017)
Q.6) What are unions? How are they different from structures? (5) (December 2019)
Q.7) Explain union data-type with an example. How does a union differ from a
structure? (3) (July 2021)
Q.8) Define a structure and union with following as members - an integer variable, a character
array having 20 characters, and a floating point variable. How many bytes are allotted for
each? Illustrate and explain. (5) (May 2019)

Difference between Structure & Union

Structure
• One of the user defined data types
• Structure is a collection of variables of different data types that are referenced under
one name.
• Its keyword is struct
• The syntax of a structure definition takes the following form.
Accessing Structure elements

• Once a structure variable has been defined ,its members can be accessed through the
use of the . (dot) operator.
• The syntax for accessing structure element is
Structure variable . element name;

Union
• One of the user defined data types.
• Union have the same syntax as structure.
• Union is a collection of variables of different data types that are referenced under one
name.
• Its keyword is union.
• The syntax of a union definition takes the following form.
Difference between Structure & Union

[Link]. Ajayakumar.M.V, Department of IT, Toc H Institute of Science & Technology Page 45
[Link]. Ajayakumar.M.V, Department of IT, Toc H Institute of Science & Technology Page 46
Previous Years University questions:
Q.1) How does an array differ from a structure? (2) (DECEMBER 2018)

Difference between Structure and Array

Sr. Key Structure Array


No.

Structure can be defined On other hand Array is a type of


as a data structure used data structure used as container
1 Definition as container which can which can hold variables of same
hold variables of different type and do not support multiple
types. data type variables.

Memory allocation for While in case of array the input


input data in structure data stored in contiguous memory
Memory does not necessary to be allocation which implies that
Allocation in consecutive memory array stores data in such memory
2
location. model where it assigns consecutive
memory blocks (that is, memory
blocks having consecutive
addresses).

In order to access the On other hand in case of Array


element in Structure we we can access the element by
require to have the name index.
3 Accessibility of that element i.e it is
mandatory to have
element name for its
retrieval from Structure.

Structure do not have On other hand in case of Array it


Pointer concept of Pointer internally implements Pointer
4
internally. which always points to the first
element of Array.

Structure object can be On other hand in case of Array


5 Instantiation created after declaration we can't create its object after
later in the program. declaration.

Structure supports On other hand in case of Array


multiple data-type we can't have different data-type
6 DataType variables as input. variable as input as it only
supports same type data
variables.
Q.1 ) Write a structure program to read (register number ,name and marks of three
subjects) and then calculate (total and percentage) and display the all information.

#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[10];
int marks[3];
int total;
double per;
}stud;
void read()
{ int i;
printf("\nEnter the roll number");
scanf("%d",&[Link]);
printf("\nEnter the name");
scanf("%s",[Link]);
printf("\nEnter the marks of 3 subjects");
[Link]=0;
for(i=0;i<3;i++)
{
scanf("%d",&[Link][i]);
[Link]=[Link]+[Link][i];
}
[Link]=[Link]/3;
}
void display()
{
Output
printf("\nMarklist\n");
printf("\n=========\n");
printf("\nRoll no:%d",[Link]);
printf("\nName:%s",[Link]);
printf("\nPhysics:%d",[Link][0]);
printf("\nChemistry:%d",[Link][1]);
printf("\nMathematics:%d",[Link][2]);
printf("\nTotal:%d",[Link]);
printf("\nPercentage:%lf",[Link]);
}

void main()
{
clrscr();
read();
display();
getch();
return;
}
Previous Years University questions:
Q.1) Explain array for structure with example. (3) (July 2021)

Array of Structures in C

• An array of structres in C can be defined as the collection of multiple structures


variables where each variable contains information about different entities.
• The array of structures in C are used to store information about multiple entities
of different data types.
• The array of structures is also known as the collection of structures.

Previous Years University questions:


Q.1) Write a C program to create a structure student with details roll no, name,
marks and grade. Read the details of ‘n’ students and display the details of the
student if student name is given as input. (5) (DECEMBER 2018)
Q.2 ) Using structure, read and print data of n students (Roll no, Name, and
Percentage)

#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[10];
int per;
}stud[5];

void read(int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter the roll number: ");
scanf("%d",&stud[i].rno);
printf("\nEnter the Name: ");
scanf("%s",stud[i].name);
printf("\n enter the percentage: ");
scanf("%d",&stud[i].per);
}
}
void display(int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\n%d",stud[i].rno);
printf("\t%s ",stud[i].name);
printf("\t%d",stud[i].per);
}
}
void main()
{
int n;
clrscr();
printf("\nEnter the value of n:");
scanf("%d",&n);
read(n);
printf("\nRoll No\tName\tpercentage\n");
display(n);
getch();
return;
}
Q.3 ) Using structure, read and print data of one employee (Name, Employee Id and
Salary)
#include<stdio.h>
#include<conio.h>
struct employee
{
int eid;
char name[10];
double salary;
}emp; Output
void read()
{
printf("\nEnter the employee id : ");
scanf("%d",&[Link]);
printf("\nEnter the employee name: ");
scanf("%s",[Link]);
printf("\nEnter the employee salary :");
scanf("%ld",&[Link]);

}
void display()
{
printf("\nEmployee id: %d",[Link]);
printf("\nEmployee name:%s",[Link]);
printf("\nEmployee salary:%ld",[Link]);
}
void main()
{

clrscr();
read();
display();
getch();
return;
}

Previous Years University questions:


Define a structure Employee with employee number, name and experience as members.
Write a C program to print a list of all employees (from amongst 100 employees) having
more than 3 years of experience. (6) (December 2018)
Previous Years University questions:
Create a structure for an employee with following information:- empid, name and
salary. Write a program to read the details of ‘n’ employees and display thedetails of employees whose salary
is above 10000. Use pointer to structure. (5) (December 2019)

Q.4 ) Using structure, read and print data of n employees (Name, Employee Id and
Salary)
#include<stdio.h>
#include<conio.h>
struct employee
{
int eid;
char name[10];
double salary;
}emp[5];
void read(int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter the employee id : ");
scanf("%d",&emp[i].eid);
printf("\nEnter the employee name: ");
scanf("%s",emp[i].name);
printf("\nEnter the employee salary :");
scanf("%ld",&emp[i].salary);
}
} Output
void display(int n)
{
int i;
printf("\nEmp ID\tEmp Name\tEmp Salary\n");
for(i=0;i<n;i++)
{
printf("\n%d",emp[i].eid);
printf("\t%s",emp[i].name);
printf("\t\t%ld",emp[i].salary);
}
}
void main()
{
int n;
clrscr();
printf("\nEnter the value of n :");
scanf("%d",&n);
read(n);
display(n);
getch();
return;
}
Lab Cycle program

Q. 5) Read two input each representing the distances between two points in the
Euclidean space, store these in structure variables and add the two distance values.

#include<stdio.h>
#include<conio.h>
struct distance
{
int feet; // structure members
int inches;
}d1,d2,d3; //structure variables

void read()
{
printf("\nEnter the first distance (in Feet and Inches) :");
scanf("%d%d",&[Link],&[Link]);

printf("\nEnter the second distance (in Feet and Inches) :");


scanf("%d%d",&[Link],&[Link]);
}

void display()
{
printf("\n %d feet %d inches",[Link],[Link]);
printf("\n %d feet %d inches",[Link],[Link]);
printf("\n %d feet %d inches",[Link],[Link]);
}

void cal()
{
[Link]=([Link]+[Link])%12;
[Link]=([Link]+[Link])+([Link]+[Link])/12;
}

void main() Output


{
clrscr();
read();
cal();
display();
getch();
return;
}
Q.6) Write a structure program to add two times.

#include<stdio.h>
#include<conio.h>
struct Time
{
int hours;
int minutes;
int seconds;
}t1,t2,t3;

void read()
{
printf("\nEnter the first time(in Hours, Minutes and Seconds):");
scanf("%d%d%d",&[Link],&[Link],&[Link]);
printf("\nEnter the second time(in Hours, Minutes and Seconds):");
scanf("%d%d%d",&[Link],&[Link],&[Link]);
}
void display()
{
printf("\nTime 1 : %d Hours %d Minutes %d Seconds",[Link],[Link],[Link]);
printf("\nTime 2 : %d Hours %d Minutes %d Seconds",[Link],[Link],[Link]);
printf("\nTime 3 : %d Hours %d Minutes %d Seconds",[Link],[Link],[Link]);
}
void cal()
{
[Link]=([Link]+[Link])%60;
[Link]=(([Link]+[Link])+([Link]+[Link])/60)%60;
[Link]=([Link]+[Link])+(([Link]+[Link])+([Link]+[Link])/60)/60;
}

Output
void main()
{
clrscr();
read();
cal();
display();
getch();
return;
Q.1 Declare a union containing 5 string variables (Name, House Name, City Name,
State and Pin code) each with a length of C_SIZE (user defined constant). Then, read
and display the address of a person using a variable of the union.

#include<stdio.h>
#include<conio.h>
#define size 10
union address
{
char name[size];
char hname[size];
char cname[size];
char state[size];
char pin[size];
}s1;

void read()
{
printf("\nEnter the Name : ");
scanf("%s",[Link]);
printf("\nName:%s",[Link]);
printf("\nEnter the House Name : ");
scanf("%s",[Link]);
printf("\nHouse Name:%s",[Link]);
printf("\nEnter the City Name : ");
scanf("%s",[Link]);
printf("\nCity Name:%s",[Link]); Output
printf("\nEnter the State : ");
scanf("%s",[Link]);
printf("\nState:%s",[Link]);
printf("\nEnter the pin : ");
scanf("%s",[Link]);
printf("\npin :%s",[Link]);
}

void main()
{
int n;
clrscr();
read();
getch();
return;
}
Previous Years University questions:
Q.1) Explain register storage class with an example.( 3) (DECEMBER 2018)
Q.2) With suitable examples explain the various storage classes in C (8) (DECEMBER 2018)
Q.3) Compare different storage classes based on scope and lifetime of a variable. (3) (July 2021)
Q.4) Compare the features of automaic and static variables in C. (3) (July 2021)
Q.5) What are different storage classes in C? Give examples for each.(7) (January 2017)
Q.6) Explain the storage classes in C with appropriate example. (10) (January 2017)
Q.7) What is the use of a static variable? Explain with example. (5) (May 2019)
Q.8) with proper examples explain the storage classes in C (6) (January 2017)
Q.9) Describe the various storage classes in C. (4) (December 2019)
Q.10)Explain static storage class with an example. (3) (DECEMBER 2019)

Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C

o Automatic
o External
o Static
o Register

• In storage class specifier, the syntax for declaration statement for a variable.
Syntax :
<storage class specifier> <data type> <variable name>;
Automatic storage class variable
• By default , all variables declared within the body of any functions are automatic.
• Its keyword is auto.
• They are created when the function is called and destroyed automatically when the
function is exited , hence the name automatic.
• Automatic variables are local to the function in which they are declared.
• Automatic variables are also referred to as local or internal variables.
• A variable declared inside a function without storage class specification is, by
default , an automatic variable.
• One important feature of automatic variables is that their value cannot be changed
accidentally by what happens in some other function in the program.
2. External storage class variables

• Variables that are active throughout the entire program are known as external
variable.
• They are also known as global variables.
• Unlike local variables, global variables can be accessed by any function in the
program.
• External variables are declared outside all function.

3. The Register storage class variable

• Variables stored in registers of the CPU are accessed in much lesser time than those
stored in the primary memory.
• To allow the fastest access time for variables, the register storage class specifier is
used.
• The keyword for this storage class is register.

4. The static storage class variable

• The value of static variables exists (persists) until the end of the program.
• A variable can be declared static using the keyword static.
• A static variable may be either an internal type or an external type, depending on
the place of declaration.
• Internal static variables are those which are declared inside a function.
• The scope of internal static variables extend upto the end of the function in which
they are defined.
• Therefore , internal static variables can be used to retain values between function
calls.
Previous Years University questions:
Q.1) What are global variables? Give examples. (3) (September 2020)
Q.2) Differentiate between local variable and global variable.(3) (July 2021)
Q.3) Point out the difference between external variable definition and external variable
declaration. (3) (July 2021)

Scope and life time of variables


Scope of Variable
Each variable is defined and can be used within its scope and determines that wherein
the program this variable is available to use. The scope means the lifetime of that
variable. It means the variable can only be accessed or visible within its scope.

The scope of variables can be defined with their declaration, and variables are declared
mainly in two ways:

o Global Variable: Outside of all the functions


o Local Variable: Within a function block:

What is a Global Variable?


o Global variables are those variables which are declared outside of all the
functions or block and can be accessed globally in a program.
o It can be accessed by any function present in the program.
o Once we declare a global variable, its value can be varied as used with different
functions.
o The lifetime of the global variable exists till the program executes. These
variables are stored in fixed memory locations given by the compiler and do not
automatically clean up.
o Global variables are mostly used in programming and useful for cases where all
the functions need to access the same data.
In the above example, a and b are the global variables.

Advantages of Global Variable


o Global variables can be accessed by all the functions present in the program.
o Only a single declaration is required.
o Very useful if all the functions are accessing the same data.

Disadvantages of Global Variable


o The value of a global variable can be changed accidently as it can be used by any
function in the program.
o If we use a large number of global variables, then there is a high chance of error
generation in the program.

What is a Local Variable?


o Variables that are declared within or inside a function block are known as Local
variables.
o These variables can only be accessed within the function in which they are declared.
o The lifetime of the local variable is within its function only, which means the variable
exists till the function executes. Once function execution is completed, local variables
are destroyed and no longer exist outside the function.
o The reason for the limited scope of local variables is that local variables are stored in
the stack, which is dynamic in nature and automatically cleans up the data stored
within it.
o But by making the variable static with "static" keyword, we can retain the value of
local variable.

In the above example, we have declared x and y two variables inside the main
function. Hence these are local variables.

Advantages of Local Variable


o The same name of a local variable can be used in different functions as it is only
recognized by the function in which it is declared.
o Local variables use memory only for the limited time when the function is
executed; after that same memory location can be reused.

Disadvantages of Local Variables


o The scope of the local variable is limited to its function only and cannot be used
by other functions.
o Data sharing by the local variable is not allowed.
Comparison Chart Between Global Variable and
Local Variable

Difference between Definition and Declaration


Declaration of a variable is for informing the compiler of the following information: name
of the variable, type of value it holds, and the initial value if any it takes. i.e., declaration
gives details about the properties of a variable.
Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the
variable is allocated during the definition of the variable. In C language definition and
declaration for a variable takes place at the same time. i.e. there is no difference between
declaration and definition

End of Module 3

You might also like