EST102 Programming in C
EST102 Programming in C
PROGRAMMING IN C
MODULE IV
SYLLABUS
Working with functions
Introduction to modular programming,
writing functions, formal parameters, actual
parameters.
Pass by Value, Recursion,
Arrays as Function Parameters, structure,
union,
Storage Classes, Scope and life time of
variables,
Simple programs using functions
Important!!
➔ Advantages of using functions
➔ Parts of a user defined function
➔ Categories of function
➔ Parameter passing techniques - Pass by value and
Pass by reference - Example
➔ Recursion
➔ C Programs using recursion - Factorial, Fibonacci
Series
➔ Structure VS Array
➔ Structure VS Union
➔ C Programs using structure and union
➔ Scope and Lifetime of Variables
➔ Types of Storage Classes
Introduction to
Modular Programming
Modular Programming
Modular Programming is a software design
technique that emphasizes separating the
functionality of a program into independent,
interchangeable modules, such that each
contains everything necessary to execute only
one aspect of the desired functionality.
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
3) Programming errors are easy to detect
4) Allows reuse of codes
5) Improves manageability
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
Allows development to be divided by
splitting down a program into smaller
programs in order to execute a variety of
tasks.
2) Readable programs
3) Programming errors are easy to detect
4) Allows reuse of codes
5) Improves manageability
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
Helps develops programs that are much
easier to read since they can be enabled as
user - defined functions.
3) Programming errors are easy to detect
4) Allows reuse of codes
5) Improves manageability
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
3) Programming errors are easy to detect
Minimizes the risks of ending up with
programming errors and also makes it
easier to spot errors, if any.
4) Allows reuse of codes
5) Improves manageability
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
3) Programming errors are easy to detect
4) Allows reuse of codes
A program module is capable of being
reused in a program which minimizes the
development of redundant codes.
5) Improves manageability
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
3) Programming errors are easy to detect
4) Allows reuse of codes
5) Improves manageability
Having a program broken into smaller sub
programs allows for easier management.
6) Collaboration
Advantages of using Modular
Programming
1) Development can be divided
2) Readable programs
3) Programming errors are easy to detect
4) Allows reuse of codes
5) Improves manageability
6) Collaboration
With modular programming, programmers
can collaborate and work on the same
application.
Functions
• A function is a group of statements that together
perform a task.
• Every C program has at least one function, main( ).
• Most programs can define additional functions.
Types of Functions
There are two types of function in C programming :
For example,
Syntax
return_type function_name(parameter list);
• Return Type
A function may return a value. The return_type
is the data type of the value the function
returns. Some functions perform the desired
operations without returning a value. In this
case, the return_type is the keyword void.
• Function Name
The actual name of the function.
• Parameter List or Arguments
When a function is invoked, we pass a value to
the parameter. This value is referred to as
actual parameter or argument.
Function Definition
• A function definition consists of a function
header and a function body.
Syntax
return_type function_name(parameter list)
{
function body
}
• Function Body
The function body contains a collection of
statements that define what the function does.
Function Call
• Control of the program is transferred to the
user - defined function by calling it.
• When a program calls a function, the program
control is transferred to the called function.
• A called function performs a defined task.
• When its return statement is executed or when
its closing brace is reached, it returns the
program control back to the main program.
Syntax
function_name(parameter list);
Formal and Actual Parameters
• Formal Parameter
A variable and its type as they appear in the
function prototype.
• Actual Parameter
A variable corresponding to a formal
parameter as they appear in the function call.
Return Statement
• The return statement terminates the
execution of a function.
• Returns a value to the calling function.
• The program control is transferred to the
calling function after the return statement.
#include<stdio.h>
return_type function_name(parameter list);
int main( )
{
……..
function_name(parameter list);
……..
}
return_type function_name(parameter list)
{
function body
}
Question No. 1
Write a C program to print hello world using
function.
Program : C program to print hello world
without using function
#include<stdio.h>
int main()
{
printf("Hello World\n");
return 0;
}
Output
Hello World
Program : C program to print hello world
using function
#include<stdio.h>
void display();
int main()
{
display();
return 0;
}
void display()
{
printf("Hello World\n");
}
Output
Hello World
Categories of Functions
Depending on whether arguments are present or not
and whether a value is returned or not, functions are
categorized into,
1) Functions without arguments and without
return values
2) Functions without arguments and with
return values
3) Functions with arguments and without
return values
4) Functions with arguments and with return
values
Question No. 2
Write a C program to find sum of two numbers
using function.
Program : C program to find sum of two
numbers without using function
#include<stdio.h>
int main()
{
int a,b,s;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
s=0;
s=a+b;
printf("Sum=%d\n",s);
return 0;
}
Output
Enter two numbers
10
20
Sum=30
Program : C program to find sum of two numbers using function
without arguments and without return values
#include<stdio.h>
void add();
int main()
{
add();
return 0;
}
void add()
{
int a,b,s;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
s=0;
s=a+b;
printf("Sum=%d\n",s);
}
Output
Enter two numbers
10
20
Sum=30
Program : C program to find sum of two numbers using function
without arguments and with return values
#include<stdio.h>
int add();
int main()
{
int c;
c=add();
printf("Sum=%d\n",c);
return 0;
}
int add()
{
int a,b,s;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
s=0;
s=a+b;
return s;
Output
Enter two numbers
10
20
Sum=30
Program : C program to find sum of two numbers using function
with arguments and without return values
#include<stdio.h>
void add(int,int);
int main()
{
int a,b;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
add(a,b);
return 0;
}
void add(int p,int q)
{
int s;
s=0;
s=p+q;
printf("Sum=%d\n",s);
}
Output
Enter two numbers
10
20
Sum=30
Program : C program to find sum of two numbers using function with
arguments and with return values
#include<stdio.h>
int add(int,int);
int main()
{
int a,b,c;
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("Sum=%d\n",c);
return 0;
}
int add(int p,int q)
{
int s;
s=0;
s=p+q;
return s;
Output
Enter two numbers
10
20
Sum=30
Pass by Value
• Passing arguments by value which means contents
of actual arguments in the calling function is copied
to the formal arguments in the called function.
• Change in formal arguments is not reflected in
actual arguments.
Question No. 3
Write a C program to swap two numbers using
function (Pass by value).
Program : C program to swap two numbers without
using function
#include<stdio.h>
int main()
{
int i,j,temp;
printf("Enter two numbers\n");
scanf("%d%d",&i,&j);
printf("Before Swapping:\ni=%d\nj=%d \n", i,j);
temp=i;
i=j;
j=temp;
printf("After Swapping:\ni=%d\nj=%d\n",i,j);
return 0;
}
Output
Enter two numbers
10
20
Before Swapping:
i=10
j=20
After Swapping:
i=20
j=10
Program : C program to to swap two numbers using
function (Pass by value)
#include<stdio.h>
void swap(int,int);
int main()
{
int i,j;
printf("Enter two numbers\n");
scanf("%d%d",&i,&j);
printf("Before Swapping:\ni=%d\nj=%d\n",i,j);
swap(i,j);
printf("After Swapping:\ni=%d\nj=%d\n",i,j);
return 0;
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
Does not reflect in
actual parameters
Before swapping,
1000 10 i i = 10
j = 20
1004 20 j
After swapping, swap(i,j)
i = 10 => swap(10,20)
j = 20 => swap(a,b)
2000 a a = 10 temp = a
10 20
b = 20 temp = 10
2005 20 10 b Changes in
a = b
formal
parameters a = 20
2010 10 temp
b = temp
b = 10
Output
Enter two numbers
10
20
Before Swapping:
i=10
j=20
After Swapping:
i=10
j=20
Pass by Reference
• Passing arguments by reference which means
address of actual arguments in the calling function
is copied to the formal arguments in the called
function.
• When we pass addresses to a function, the
arguments receiving the address should be pointers.
• Change in formal arguments is reflected in actual
Question No. 4
Write a C program to swap two numbers using
function (Pass by reference).
Program : C program to swap two numbers without
using function
#include<stdio.h>
int main()
{
int i,j,temp;
printf("Enter two numbers\n");
scanf("%d%d",&i,&j);
printf("Before Swapping:\ni=%d\nj=%d \n", i,j);
temp=i;
i=j;
j=temp;
printf("After Swapping:\ni=%d\nj=%d\n",i,j);
return 0;
}
Output
Enter two numbers
10
20
Before Swapping:
i=10
j=20
After Swapping:
i=20
j=10
Program : C program to to swap two numbers using function
(Pass by reference)
#include<stdio.h>
void swap(int *,int *);
int main()
{
int i,j;
printf("Enter two numbers\n");
scanf("%d%d",&i,&j);
printf("Before swapping:\ni=%d\nj=%d\n",i,j);
swap(&i,&j);
printf("After swapping:\ni=%d\nj=%d\n",i,j);
return 0;
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Reflect in actual parameters
Before swapping,
1000 10 20 i i = 10
j = 20
1004 20 10 j
After swapping, swap(&i,&j)
i = 20 => swap(1000,1004)
j = 10 => swap(a,b)
temp = *a
2000 1000 a a = 1000
temp = i = 10
b = 1004
2005 1004 b Changes in
*a = *b
formal i=j
parameters
2010 10 temp i = 20
*b = temp
j = 10
Output
Enter two numbers
10
20
Before Swapping:
i=10
j=20
After Swapping:
i=20
j=10
Recursion
• Recursion is a process while which a function
called itself repeatedly until some specified
condition has been satisfied.
• The process is used for repetitive computation in
which each action is stated in terms of previous
results.
Question No. 5
Write a C program to find factorial of a number
using recursion.
Program : C program to find factorial of a number without
using recursion
#include<stdio.h>
int main()
{
int n,i,f;
printf("Enter a number\n");
scanf("%d",&n);
if(n==0)
{
printf("Factorial is 1\n");
}
else if(n<0)
{
printf("Factorial does not exist\n");
}
else
{
f=1;
for(i=n;i>=1;i--)
{
f=f*i;
}
printf("Factorial=%d\n",f);
}
return 0;
}
Output 1
Enter a number
0
Factorial is 1
Output 2
Enter a number
-9
Factorial does not exist
Output 3
Enter a number
5
Factorial=120
Program : C program to find factorial of a number using recursion
#include<stdio.h>
int fact(int);
int main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
if(n<0)
{
printf("Factorial does not exist\n");
}
else
{
printf("Factorial=%d\n",fact(n);
}
return 0;
}
int fact(int i)
{
if(i==0)
{
return 1;
}
else
{
return i*fact(i-1);
}
}
Output 1
Enter a number
0
Factorial is 1
Output 2
Enter a number
-9
Factorial does not exist
Output 3
Enter a number
5
Factorial=120
Question No. 6
Write a C program to print fibonacci series using
recursion.
Program : C program to to print fibonacci series
without using recursion
#include<stdio.h>
int main()
{
int n,n1,n2,n3,i;
printf("Enter the limit\n");
scanf("%d",&n);
printf("Fibonacci series:\n");
n1=0;
n2=1;
printf("%d\t%d\t",n1,n2);
for(i=3;i<=n;i++)
{
n3=n1+n2;
printf("%d\t",n3);
n1=n2;
n2=n3;
}
return 0;
}
Output
Enter the limit
5
Fibonacci series:
0 1 1 2 3
Program : C program to to print fibonacci series using
recursion
#include<stdio.h>
int fib(int);
int main()
{
int n,i;
printf("Enter the limit\n");
scanf("%d",&n);
printf("Fibonacci series:\n");
for(i=1;i<=n;i++)
{
printf("%d\t",fib(i));
}
return 0;
}
int fib(int k)
{
if(k==1)
{
return 0;
}
else if(k==2)
{
return 1;
}
else
{
return fib(k-1)+fib(k-2);
}
}
Output
Enter the limit
5
Fibonacci series:
0 1 1 2 3
Array as Function Parameters
• It is also possible to pass an entire array as an
argument to a function.
• For this, it is sufficient to list the name of the
array and size of the array as arguments.
• The name of the array interpreted as the
address of the memory location containing
the first address element.
• The formal argument declaration needs a set
of empty square brackets to indicate that it is
an array.
Question No. 7
Write a C program to find largest element among n
numbers using function.
Program : C program to to find largest element among
n numbers without using function
#include<stdio.h>
int main()
{
int a[10],n,i,l,j;
printf("Enter the size\n");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
l=a[0];
for(j=1;j<n;j++)
{
if(a[j]>l)
{
l=a[j];
}
}
printf("Largest=%d\n",l);
return 0;
}
Output
Enter the size
5
Enter elements:
689
2000
23
45
6
Largest=2000
Program : C program to to find largest element among n numbers
using function
#include<stdio.h>
int largest(int [],int);
int main()
{
int a[10],n,i,l;
printf("Enter the size\n");
scanf("%d",&n);
printf("Enter elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
l=largest(a,n);
printf("Largest=%d\n",l);
return 0;
}
int largest(int p[],int k)
{
int b,j;
b=p[0];
for(j=1;j<k;j++)
{
if(p[j]>b)
{
b=p[j];
}
}
return b;
}
Output
Enter the size
5
Enter elements:
689
2000
23
45
6
Largest=2000
Structure and Union
Structure
• A structure is a group of variables of
different types under one name.
• It is also called conglomerate data type.
• Here, we can refer collectively to a set of data
items that differ among themselves in type.
• The individual data items are said to occupy
fields within the structure.
• The individual elements within the structure
are called members.
Defining a Structure
• The general form of structure declaration is:
struct
{
member_1;
member_2;
…………...
}variable_list;
which can also be declared as:
struct name
{
member_1;
member_2;
…………...
};
int main( )
{
struct name variable_list;
…………………….
…………………….
return 0;
}
• struct is the keyword indicating a structure
definition.
• variable_list is the names of structure type
variables.
• Individual fields are declared inside the
braces, separated by a ;.
• The declaration member_1 declares the first
field, member_2 declares the second field
and so on.
• Syntax for declaring members are,
data_type field_name;
Processing Structure Variables
• The members within a structure have no
separate identity without the structure
variable name.
• The link between a member and structure
variable is established by using the member
operator ., which is also known as dot
operator or period operator.
Question No. 1
Write a C program to store information of a student
using structure.
Program
#include<stdio.h>
struct
{
char n[10];
int rn;
int sem;
}st;
int main()
{
printf("Enter name,roll number and semester details of student
1\n");
scanf("%s%d%d",st.n,&st.rn,&st.sem);
printf("Entered name,roll number and semester details of
student 1\n");
printf("%s\n%d\n%d\n",st.n,st.rn,st.sem);
return 0;
}
Output
Enter name,roll number and semester details of
student 1
Harsha
20
2
Entered name,roll number and semester details of
student 1
Harsha
20
2
Question No. 2
Using structure, read and print data of n employees
(Name, Employee Id and Salary).
Program
#include<stdio.h>
struct
{
char n[10];
int id;
float s;
}e[10];
int main()
{
int m,i;
printf("Enter the limit\n");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("Enter name,id and salary of Employee %d:\n",i+1);
scanf("%s%d%f",e[i].n,&e[i].id,&e[i].s);
}
for(i=0;i<m;i++)
{
printf("Entered name,id and salary of Employee %d:\n",i+1);
printf("%s\n%d\n%0.2f\n",e[i].n,e[i].id,e[i].s);
}
return 0;
}
Output
Enter the limit
3
Enter name,id and salary of Employee 1:
Maya
120
20000
Enter name,id and salary of Employee 2:
Hari
258
65000
Enter name,id and salary of Employee 3:
Laya
125
25000
Entered name,id and salary of Employee 1:
Maya
120
20000.00
Entered name,id and salary of Employee 2:
Hari
258
65000.00
Entered name,id and salary of Employee 3:
Laya
125
25000.00
Difference between Array and Structure
Union
• A union is a group of variables of different
types under one name.
• The syntax of union is same as that of
structure.
• In structures, each member has its own
storage location, whereas all the members of
union uses the same location.
Defining a Union
• The general form of union declaration is:
union
{
member_1;
member_2;
…………...
}variable_list;
Difference between Structure and Union
Question No. 3
Write a C program to store information of a student
using union.
Program
#include<stdio.h>
union
{
char n[10];
int rn;
int sem;
}st;
int main()
{
printf("Enter name of student 1\n");
scanf("%s",st.n);
printf("Entered name of student 1: %s\n",st.n);
printf("Enter roll number of student\n");
scanf("%d",&st.rn);
printf("Entered roll number of student: %d\n",st.rn);
printf("Enter semester details of student\n");
scanf("%d",&st.sem);
printf("Entered semester details of student: %d\n",st.sem);
return 0;
}
Output
Enter name of student 1
Hari
Entered name of student 1: Hari
Enter roll number of student
1
Entered roll number of student: 1
Enter semester details of student
2
Entered semester details of student: 2
Question No. 4
Write a C program to declare a structure Student to
store the details (roll number, name, mark_for_C) of
a student. Display the average mark obtained by the
students in the class for the subject Programming in
C (using the field mark_for_C). Use an array of
structures to store the required data.
Program
#include<stdio.h>
struct Student
{
int roll_number;
char name[10];
float mark_for_c;
}s[20];
int main()
{
int n,i,sum;
float avg;
printf("Enter the limit\n");
scanf("%d",&n);
sum=0;
for(i=0;i<n;i++)
{
printf("Enter roll number, name and mark obtained for the
subject Programming in C of student %d:\
n",i+1);
scanf("%d%s%f",&s[i].roll_number,s[i].name,
&s[i].mark_for_c);
sum=sum+s[i].mark_for_c;
}
avg=sum/n;
printf("Average mark obtained by the students in the class for
the subject Programming in C=%0.2f\n",avg);
return 0;
}
Output
Enter the limit
3
Enter roll number, name and mark obtained for
the subject Programming in C of student 1:
1
Maya
30
Enter roll number, name and mark obtained for
the subject Programming in C of student 2:
12
Akhil
40
Enter roll number, name and mark obtained for
the subject Programming in C of student 3:
3
Vishnu
45
Average mark obtained by the students in the class
for the subject Programming in C=38.00
Storage Classes
Scope and Lifetime of Variables
Scope
• Scope defines the visibility of a variable.
• It defines where a variable can be accessed.
• The scope of a variable is local or global.
• The variable defined within the block has
local scope. They are visible only to the block
in which they are defined.
• The variable defined in global area is visible
from their definition until the end of program.
It is visible everywhere in program.
Lifetime
• The lifetime of a variable defines the duration for which
the computer allocates memory for it.
• The duration between allocation and deallocation of
memory.
• In C language, a variable can have automatic, static or
dynamic lifetime.
Automatic − A variable with automatic lifetime are
created. Every time, their declaration is encountered and
destroyed. Also, their blocks are exited.
Static − A variable is created when the declaration is
executed for the first time. It is destroyed when the
execution stops/terminates.
Dynamic − The variables memory is allocated and
deallocated through memory management functions.
Storage Classes
• Storage classes specify the scope, lifetime and
binding of variables.
• To fully define a variable, one needs to mention
not only its ‘type’ but also its storage class.
• A variable name identifies some physical
location within computer memory, where a
collection of bits are allocated for storing
values of variable.
Storage class tells us
• Where the variable is stored (in memory or cpu
register)?
• What will be the initial value of variable, if
nothing is initialized?
• What is the scope of variable (where it can be
accessed)?
• What is the life of a variable?
Storage class tells us
• Where the variable is stored (in memory or cpu
register)? - Storage area
• What will be the initial value of variable, if
nothing is initialized? - Default initial value
• What is the scope of variable (where it can be
accessed)?- Scope
• What is the life of a variable? - Lifetime
Storage Classes in C
There are four storage classes in C.
1) Automatic
2) Static
3) Register
4) External
The keywords auto, static, register and extern are
used for above storage classes respectively.
We can specify a storage class while declaring a
variable.
Syntax
storage_class data_type variable_name;
Automatic storage class
• Syntax to declare automatic variable is:
auto data_type variable_name;
• Features
Storage area : Memory
Default initial value : Garbage value
Scope : Local to the block in which the variable
is defined
Lifetime : Till the control remains within the
block in which the variable is defined
• All the variables which are declared inside a
block or function without any storage class
specifier are automatic variables.
• Automatic variables came into existence each
time the function is executed and destroyed
when execution of the function completes.
Question No. 8
What will be the output of the following C code?
#include<stdio.h> ➢ When the function test( ) is
void test( ); called for the first time, k is
void main( ) created and initialized to 10.
{ When the control returns to
main( ) function, k is destroyed.
test( );
➢ When the function test( ) is
test( ); called for the second time, k is
test( ); again created and initialized to
} 10. When the control returns to
void test( ) main( ) function, k is destroyed.
{ ➢ When the function test( ) is
called for the third time, k is
auto int k=10;
again created and initialized to
printf(“%d\n”,k); 10. When the control returns to
k++; main( ) function, k is destroyed.
}
Output
10
10
10
Register storage class
• Syntax to declare register variable is:
register data_type variable_name;
• Features
Storage area : CPU Registers
Default initial value : Garbage value
Scope : Local to the block in which the variable
is defined
Lifetime : Till the control remains within the
block in which the variable is defined
• Register storage class can be applied only to
automatic variables.
• Its scope, lifetime and default initial value are
same as that of automatic variables.
• Automatic variables are stored in memory but
register values are stored in CPU registers.
• Registers are small storage units present in the
processor.
• Variables stored in registers can be accessed
much faster than the variables stored in
memory.
Static storage class
• Syntax to declare static variable is:
static data_type variable_name;
• Features
Storage area : Memory
Default initial value : Zero
Scope : Local to the block in which the variable
is defined
Lifetime : Value of the variable continues to
exist between different function calls
• Static variables are initialized to zero if not
initialized.
• Static variables does not disappear when the
function is no longer active.
Question No. 9
What will be the output of the following C code?
#include<stdio.h> ➢ When the function test( ) is
void test( ); called for the first time,
void main( ) k = 10
{ k++
k = 11
test( );
➢ When the function test( ) is
test( ); called for the second time,
test( ); k = 11
} k++
void test( ) k = 12
{ ➢ When the function test( ) is
called for the third time,
static int k=10;
k = 12
printf(“%d\n”,k); k++
k++; k = 13
}
Output
10
11
12
External storage class
• Syntax to declare external variable is:
extern data_type variable_name;
• Features
Storage area : Memory
Default initial value : Zero
Scope : Global
Lifetime : Till the program’s execution does not
comes to an end
• External variables are declared outside all the
functions, therefore are available to all functions
that want to use them.
Thank you…….