Module 3 C Programming Notes
Module 3 C Programming Notes
MODULAR PROGRAMMING
Advantages
• Ease of use: This approach allows simplicity, as rather than focusing on the entire
thousands and millions of lines code in one go, we can access it in the form of
modules.
• Programming errors are easy to detect: Minimizes the risks of ending up with
programming errors and makes it easier to spot errors, if any.
• Allows re-use of codes: A program module is capable of being re-used in a program
which minimizes the development of redundant codes
• Improves manageability: Having a program broken into smaller sub-programs
allows for easier management.
FUNCTION
A function is a group of statements that together perform a task. Every C program has
at least one function, which is main(), and can have additional functions.
Types of Functions
USER-DEFINED FUNCTIONS
Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Function Declaration
A function prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body. A function prototype
gives information to the compiler that the function may later be used in the program.
Note:
✓ If function definition is written after main, then only we write prototype declaration in
global declaration section.
✓ If function definition is written above the main function, then, no need to write
prototype declaration.
Function Definition
A function definition in C programming consists of a function header and a function
body. Function header consists of return type, function name, arguments(parameters).
• 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. The function name and the
parameter list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. Parameters are optional; that is, a function may contain no
parameters.
• Function Body: The function body contains a collection of statements that define
what the function does.
Syntax:
return_type function_name (argument list) {
body of the function
}
Function Call
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is executed
or when its function-ending closing brace is reached, it returns the program control back to
the main program.
Syntax:
functionName(parameter list);
Example:
int add(int,int,int);
void main()
{
int x=10,y=20,z=30,res;
res = add(x,y,z); // function call
printf(“Result=%d”,res);
}
int add(int a, int b, int c) // function definition
{
int sum;
sum = a+ b + c;
return sum; //return statement
}
Return Statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after the return
statement.
In the above example, the value of the sum variable is returned to the main function.
The res variable in the main() function is assigned this value.
Formal and Actual Parameters
There are different ways in which parameters can be passed into and out of functions.
Let us assume that a function B() is called from another function A(). In this case A is called
the “caller function” and B is called the “called function or callee function”.
• Formal Parameter: A variable and its type as they appear in the prototype of the
function or method.
• Actual Parameter: The variable or expression corresponding to a formal parameter that
appears in the function call in the calling environment.
In the above example, x, y and z in the main function are the actual parameter of add
function. Formal parameter of add function are a, b and c.
PASS BY VALUE
This method copies the actual value of an argument into the formal parameter of the
function. Changes made to the formal parameter inside the function will have no effect on the
actual parameters.
#include<stdio.h>
int swap(int a,int b)
{
int temp;
temp=a;
a= b;
b=temp;
}
void main()
{
int x,y;
printf("Enter the numbers:");
scanf("%d%d",&x,&y);
printf("Before swapping : x=%d\ty=%d\n",x,y);
swap(x,y);
printf("After swapping : x=%d\ty=%d",x,y);
}
Output
Enter the numbers:10 20
Before swapping: x=10 y=20
After swapping: x=10 y=20
In above program we expect the program to swap the value of x and y after calling the
function swap with x and y as actual parameter. But swapping does not take place as this uses
call by value as parameter passing technique. During swap call, a copy of actual parameters
are created and changes are made on that copy. So, the value of x and y does not change.
void main()
{
int n1,n2;
printf("Enter two num");
scanf("%d%d",&n1,&n2);
add(n1,n2);
}
void main()
{
int res;
res = add();
printf(“Sum is %d”, res);
}
Functions with arguments and one return value
// function that takes two arguments and print their sum.
#include<stdio.h>
int add(int a,int b)
{
int sum;
sum = a + b;
return sum;
}
void main()
{
int n1,n2, res;
printf("Enter two num");
scanf("%d%d",&n1,&n2);
res = add(n1,n2);
printf("Sum is %d",res);
}
void main()
{
int n, res;
printf("enter number");
scanf("%d",&n);
res=even(n);
printf("%d", res);
}
RECURSIVE FUNCTION
In some problems, it may be natural to define the problem in terms of the problem itself.
Recursion is useful for problems that can be represented by a simpler version of the same
problem.
Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
A function that calls itself is known as a recursive function. And, this technique is known
as recursion. While using recursion, programmers need to be careful to define a termination
condition from the function; otherwise, it will go into an infinite loop. Termination condition
will be the base case where the problem can be solved.
if( n == 0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("Factorial=%d",fact(n));
}
OUTPUT
Enter the number:5
Factorial=120
void main()
{
int n,r;
float C,P;
printf("Enter the numbers:");
scanf("%d%d",&n,&r);
P = (float) fact(n) /fact(n-r);
C = (float)fact(n) / (fact(r) * fact(n-r));
printf("nCr=%f\n",C);
printf("nPr=%f",P);
}
Output
Enter the numbers:5 3
nCr=10.000000
nPr=60.000000
if(n == 0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n,i;
float sum=0.0;
printf("Enter the limit:");
scanf("%d",&n);
for(i=1;i<=n;i++)
sum = sum + 1.0 / fact(i);
printf("Sum=%f",sum);
}
OUTPUT
Enter the limit:5
Sum=1.716667
Write a recursive function to print Fibonacci series
#include<stdio.h>
int fib(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fib(n-2)+fib(n-1);
}
void main()
{
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d\t",fib(i));
}
OUTPUT
Enter the limit:7
0 1 1 2 3 5 8
void main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("Sum=%d",sod(n));
}
OUTPUT
Enter the number:124
Sum=7
if(n<=0)
return 0;
else
return n + sum(n-1);
}
void main()
{
int n,res;
printf("Enter the number:");
scanf("%d",&n);
res=sum(n);
printf("Sum is %d",res);
}
OUTPUT
Enter the number:5
Sum=15
OUTPUT
Enter the order of matrix:2 4
Enter the element:12
Enter the element:4
Enter the element:25
Enter the element:7
Enter the element:8
Enter the element:5
Enter the element:16
Enter the element:2
4 7 12 25
2 5 8 16
Write a program to pass a 2D matrix as parameter and find sum of all the elements.
#include<stdio.h>
int sum(int A[][30],int m,int n)
{
int i,j,sum =0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum = sum + A[i][j];
}
}
printf("\nSum=%d",sum);
}
void main()
{
int A[30][30];
int i,n,m,j;
printf("Enter the order of matrix:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the element:");
scanf("%d",&A[i][j]);
}
}
sum(A,m,n);
}
OUTPUT
Enter the order of matrix:2 2
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Sum=10
STRUCTURE
A structure is a user defined data type in C. A structure is a collection of related data
items, possibly of different types. A structure is heterogeneous in that it can be composed of
data of different types. In contrast, array is homogeneous.
The general format of a structure definition is as
follows struct structure_name{
data_type member1;
data_type member2;
};
Consider we want to create the structure of a person with following variables
name, age and address. Then such a structure can be created as
struct Person
{
char name[30];
int age;
char addr[50];
};
In defining a structure, you may note the following syntax:
Array Structure
An array is a collection of related data Structure can have elements of different
elements of same type. types.
An array is derived data type Structure is a programmer defined one
Any array behaves like built in data type. In structure we have to design and declare a
All we have to do is to declare an array data structure before the variable of that
variable and use it type is declared and used.
Write a program to create a structure employee with member variables name, age,
bs, da, hra and tsalary. Total Salary is calculated by the equation tsalary=
(1+da+hra)* bs. Read the values of an employee and display it.
#include<stdio.h>
struct Employee{
char name[30];
int age;
float bs;
float da;
float hra;
float tsalary;
};
void main()
{
struct Employee e;
printf("Enter the name:");
scanf("%s",[Link]);
printf("Enter the age:");
scanf("%d",&[Link]);
printf("Enter the basic salary:");
scanf("%f",&[Link]);
printf("Enter the da:");
scanf("%f",&[Link]);
printf("Enter the hra:");
scanf("%f",&[Link]);
[Link]=(1+[Link]+[Link])*[Link];
printf("Name=%s\n",[Link]);
printf("Basic Salary=%.2f\n",[Link]);
printf("DA=%.2f\n",[Link]);
printf("HRA=%.2f\n",[Link]);
printf("Total Salary=%.2f\n",[Link]);
}
OUTPUT
Enter the name:John
Enter the age:31
Enter the basic salary:10000
Enter the da:12
Enter the hra:7.5
Name=John
Age=31
Basic Salary=10000.00
DA=12.00
HRA=7.50
Total Salary=205000.00
Write a program to create a structure Complex with member variables real and
img. Perform addition of two complex numbers using structure variables.
#include<stdio.h>
struct Complex
{
int real;
int img;
};
void main()
{
struct Complex a,b,c;
printf("Enter the real and img part of a:");
scanf("%d%d",&[Link],&[Link]);
printf("Enter the real and img part of b:");
scanf("%d%d",&[Link],&[Link]);
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
printf("c = %d + %di\n",[Link],[Link]);
}
OUTPUT
Enter the real and img part of a:10 20
Enter the real and img part of b:30 40
c = 40 + 60i
ARRAY OF STRUCTURES
Structure is used to store the information of one object but if we need to store the
information of many such objects then Array of Structure is used.
Example :
struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];
Declare a structure namely Student to store the details (roll number, name,
mark_for_C) of a student. Then, write a program in C to find the average mark
obtained by the students in a class for the subject Programming in C (using the field
mark_for_C). Use array of structures to store the required data.
#include<stdio.h>
struct Student{
char name[30];
int rollnum;
int mark_for_C;
};
void main(){
struct Students[30];
int i,n,sum=0;
float avg;
printf("Enter the no of Student:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Student name:");
scanf("%s",s[i].name);
printf("Enter the Student rollnum:");
scanf("%d",&s[i].rollnum);
printf("Enter the Student Mark for C:");
scanf("%d",&s[i].mark_for_C);
}
printf("Name\tRoll Number\tMark for C\n");
for(i=0;i<n;i++)
{
sum = sum + s[i].mark_for_C;
}
avg = (float)sum / n; printf("Average Mark=%.2f\n",avg);
}
OUTPUT
Enter the no of Student:3
Enter the Student name:John
Enter the Student rollnum:27
Enter the Student Mark for C:35
Enter the Student name:Miya
Enter the Student rollnum:24
Enter the Student Mark for C:40
Enter the Student name:Anu
Enter the Student rollnum:26
Enter the Student Mark for C:45
Name Roll Number Mark for C
John 27 35
Miya 24 40
Anu 26 45
Average Mark=40.00
Write a program to create a structure employee with member variables name, age,
bs, da, hra and tsalary. Total Salary is calculated by the equation tsalary=
(1+da+hra)* bs. Read the values of 3 employees and display details based on
descending order of tsalary.
#include<stdio.h>
struct Employee{
char name[30];
int age;
float bs;
float da;
float hra;
float tsalary;
};
void sort(struct Employee e[],int n)
{
int i,j;
struct Employee t;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(e[j].tsalary < e[j+1].tsalary)
{
t=e[j];
e[j]=e[j+1];
e[j+1]=t;
}
}
}
}
void main()
{
struct Employee e[5];
int i;
for(i=0;i<3;i++)
{
printf("Enter the name:");
scanf("%s",e[i].name);
printf("Enter the age:");
scanf("%d",&e[i].age);
printf("Enter the basic salary:");
scanf("%f",&e[i].bs);
printf("Enter the da:");
scanf("%f",&e[i].da);
printf("Enter the hra:");
scanf("%f",&e[i].hra);
e[i].tsalary=(1+e[i].da+e[i].hra)*e[i].bs;
}
sort(e,3);
printf("Name\t Age\tBasic Salary\tDA\t HRA\t Total Salary\n");
for(i=0;i<3;i++)
{
printf("%s\t%d\t%.2f\t",e[i].name,e[i].age,e[i].bs);
printf("%.2f\t%.2f\t%.2f\n",e[i].da,e[i].hra,e[i].tsalary);
}
}
OUTPUT
Enter the name:John
Enter the age:31
Enter the basic salary:14000
Enter the da:6
Enter the hra:7.5
Enter the name:Miya
Enter the age:28
Enter the basic salary:15000
Enter the da:7.6
Enter the hra:8
Enter the name:Anu
Enter the age:29
Enter the basic salary:15000
Enter the da:8
Enter the hra:9
Name Age Basic Salary DA HRA Total Salary
Anu 29 15000.00 8.00 9.00 270000.00
Miya 28 15000.00 7.60 8.00 249000.00
John 31 14000.00 6.00 7.50 203000.00
UNION
A union is a user-defined type like structure in C programming. We use the keyword
‘union’ to define unions. When a union is defined, it creates a user-defined type.
However, no memory is allocated. To allocate memory for a given union type and work
with it, we need to create variables.
Example of Employee Union creation and declaration
union Employee
{
char name[30];
int age;
double salary;
};
union Employee e;
Structure Union
struct keyword is used to define a union keyword is used to define a union
structure
Any member can be retrieved at any time Only one member can be accessed at a time
in a structure in a union.
Several members of a structure can be Only the first member can be initialized.
initialized at once.
Predict the output
#include<stdio.h>
struct Person
{
char pincode[6]; // Size = 6 bytes
int age; // Size = 4 bytes
double salary; // Size = 8 bytes
};
union Employee
{
char pincode[6];
int age;
double salary;
};
void main()
{
struct Person p;
union Employee e;
printf("Size of Structure Person=%d\n",sizeof(p));
printf("Size of Union Employee=%d",sizeof(e));
}
OUTPUT
Size of Structure Person=18
Size of Union Employee=8
AUTOMATIC VARIABLES
Automatic variables are declared inside a function in which they are to be utilized.
They are created when the function is called and destroyed automatically when the function is
exited, hence the name automatic. Automatic variables are therefore private or local to the
function in which they are declared. Because of this property, automatic variables are also
referred to as local or internal variables.
✓ Storage location − main memory
✓ Default initial value − An unpredictable value, which is often called a garbage
value
✓ Scope − Local to the block in which the variable is defined
✓ Life − Till the control remains within the block in which the variable is defined
✓ Keyword auto is used to declare these variables
Example:
auto int i;
Note: A variable declared inside a function without storage class specification is by
default an automatic variable.
void main(){
int num;
}
is same as
void main(){
auto int num;
Example
#include<stdio.h>
void func1()
{
int max=10;
printf("Max in func1()=%d\n",max);
}
void func2()
{
int max=20;
printf("Max in func2()=%d\n",max);
}
void main()
{
int max=30;
func1();
func2();
printf("Max in main()=%d\n",max);
}
Output
Max in func1()=10
Max in func2()=20
Max in main()=30
REGISTER VARIABLES
We can tell the compiler that a variable should be kept in one of the machine’s
registers instead of keeping in the memory. Since a register access is faster than a memory
access, keeping the frequently accessed variables in the register will lead to faster execution
of programs. This is done as follows
register int count;
Since only a few variables can be placed in the register, it is important to carefully select
the variables for these purposes. However, C will automatically convert register variables
into non register variable once limit is reached.
✓ Storage - CPU registers
✓ Default initial value - Garbage value
✓ Scope - Local to the block in which the variable is defined
✓ Life - Till the control remains within the block in which the variable is defined
✓ Keyword register is used to declare these variables
Example:
register int i;
Example void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}
Here, even though we have declared the storage class of i as register, we cannot say for
sure that the value of i would be stored in a CPU register. Because the number of CPU
registers are limited, and they may be busy doing some other task. In such situations, the
variable works as if its storage class is auto.
STATIC VARIABLES
As the name suggests, the value of static variables persists until the end of the
program. A variable can be declared static using the keyword static like static int x;
✓ Storage− main memory
✓ Default initial value − Zero
✓ Scope − Local to the block in which the variable is defined
✓ Life − Value of the variable persists between different function calls. ie they
retain the latest value
✓ Keyword static is used to declare these variables
Example:
static int i;
A static variable tells the compiler to persist the variable until the end of the program.
i.e., they retain the latest value. Instead of creating and destroying a variable every time when
it comes into and goes out of scope, static is initialized only once and remains into existence
till the end of program.
#include<stdio.h>
void func1()
{
static int x=10; //static variable
++x;
printf("x in func1()=%d\n",x);
}
void func2()
{
int x=10; // local variable
++x;
printf("x in func2()=%d\n",x);
}
void main(){
func1();
func1();
func2();
func2();
}
OUTPUT
x in func1()=11
x in func1()=12
x in func2()=11
x in func2()=11
EXTERNAL VARIABLES
Variables that are both alive and active throughout the entire program are known as
external variables. They are called global variables. Unlike local variables, global variables
can be accessed by any function in the program. External variables are declared outside a
function.
✓ Storage −main memory
✓ Default initial value − Zero
✓ Scope− Global
✓ Life− till the end of program
✓ Keyword extern is used to declare these variables
Example: extern int i;
✓
#include<stdio.h>
float pi=3.14; // One way of declaring external variable
float area(int r)
{
return (pi*r*r);
}
float perimeter(int r){
return (2 * pi * r);
}
void main()
{
// extern float pi=3.14; Another way of declaring external variable
int r;
float a,p;
printf("Enter the radius:");
scanf("%d",&r);
a=area(r);
p=perimeter(r);
printf("Area=%f\n",a);
printf("Perimeter=%f\n",p);
}
OUTPUT
Enter the radius:5
Area=78.500000
Perimeter=31.400002