0% found this document useful (0 votes)
51 views

Module 3 Notes C Programming

Uploaded by

Khushi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Module 3 Notes C Programming

Uploaded by

Khushi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

PRINCIPLES OF PROGRAMMING USING C

22POP13
MODULE-3
INTRODUCTION

A function is a block of code to perform a specific task.


• Every C program has at least one function main(). Without main() function,
there is technically no C program.
• In modular programming, the program is divided into separate small
programs called modules. Each module is designed to perform specific
function. Modules make our actual program shorter, hence easier to read and
understand.
Advantages of functions:
• Reusability: Particular set of instructions can be used repeatedly from
several different places within the program.
• Easy debugging: since each function is smaller and has a logical clarity, it is
easy to locate and correct errors in it.
• Build library: Functions allows a programmer to build a customized library
of frequently used routines or system-dependent features. Each routine can
be programmed as a separate function and stored within a special library file.

Types of C Function

• There are 2 types of functions in C programming:


1. Library function
2. User defined function

1. Library function
Library functions are the in-build function in C compiler.
For example:
main() //the execution of every C program starts from this main() function
printf() //printf() is used for displaying output in C
sqrt(x); // finds the square root of x
scanf() //scanf() is used for taking input in C
2. User defined function
C allows programmer to define their own function according to their
requirement. These types of functions are known as user-defined functions.

Advantages
• User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.
• If repeated code occurs in a program. Function can be used to include those
code and execute when needed by calling that function.
• Programmer working on large project can divide the workload by making
different functions.

Function and Program Structure

#include<stdio.h>
global declarations;
void function_name(parameter list); //function declaration or function prototype
void main()
{
local declarations;
Statements;
Function_name(parameter list); //function call
...........
..........
}
void function_name(parameter list) //function definition
{
local declarations;
Statements;
}
• Where:
– return_type is the data type that the function returns.
– Function_name refers to the name of the function.
– The formal parameters are a comma separated list of variables that
receive the values from the main program when a function is called.
– The return statement returns the results of the function.
Program to add two integers. Marks a function add integers and display sum
in main() function.

#include<stdio.h>
int add(int a,int b); // function prototype
void main()
{
int a, b, sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=add(a,b); //actual arguments
printf(“\n sum=%d”,sum);
}
int add(int a,int b) //formal arguments
{
int sum; //local declaration
sum=a+b;
return sum;
}
2. Function with no arguments and with return value:
– In this , there is no data transfer from the calling function to the called
function. But there is a data transfer from called function to the calling
function.
– When the function definition returns a value the calling function
receives one value from the called function.

Example: Program to illustrate function with no arguments and return value.


#include<stdio.h>
int add();
void main()
{
int sum;
sum=add ( );
printf(“\nsum=%d”,sum);
}
int add( )
{
int a,b,sum;
printf(“enter two numbers to add\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
return sum;
}

4. FUNCTION WITH ARGUMENTS AND RETURN VALUE:


– In this category there is a data transfer between the calling function
and called function.
– When parameters are passed , the called function can receive values
from the calling function. When the function returns a value the
calling function can receive a value from the called function.
Example: program to illustrate function with arguments and return value
#include<stdio.h>
int add(int a, int b);
void main()
{
int a, b,sum;
printf(“enter two number to add\n”);
scanf(“%d%d”,&a,&b);
sum=add(a,b);
printf(“\n sum=%d”,sum);
}
int add(int a, int b)
{
int sum;
sum=a+b;
return sum;
}

Parameter Passing Techniques

• The calling and called function need to communicate with each other to
exchange the data.
• The data flow between the calling and called functions can be divided into
– Call-by-value
– Call-by-reference
• Call by value:
– It is a one-way communication. The calling function can send data to
the called function, but the called function cannot send any data to the
calling function.
– The called function may change the values passed, but the original
values in the calling function remain unchanged.
• Call by reference:
– We may often come across situations where we need to modify the
values of actual parameter in the called function.
Scope of variable:
Variable have a defined scope. by scope we mean the accessibility and
visibility of the variables at different points in the program.
There are 4 types:
1. Block scope
2. Function scope
3. Program scope
4. File scope

1. Block scope
 Statements block is a group of statements enclosed within
opening and closing curly brackets{}.
 If a a variables is declared within a statement block then as soon
as the control exists that block, the variable will stop to exist.
Such a variable is also known as local variable is said to have a
block scope.
 Blocks of statements may be placed one after the other in a
program, such blocks that are placed at the same level are
known as parallel blocks.
 For example: a program may also contain a nested block, like a
while loop inside main(). If an integer x is declared and
initialized in main() and then it is re-declared and re-initialized
in a while loop, then the integer variable x will occupy different
memory slots and will be considered as different variables
#include<stdio.h>
Void main()
{
int x=10;
int i=0;
printf(“\n the value of x outside the while loop is %d”,x);
while(i<3)
{
int x=I;
printf(\n the value of x inside the while loop is
%d”,x);
i++;
}
printf(“\n the value of x outside the while loop is %d”,x);
}
2. Function scope
 Function scope indicates that a variable is active and visible
from the beginning to the end of a function.
 In C, only the goto label has function scope.( it is applicable to
goto statements)
 This means that the programmer cannot have the same label
names inside a function.
 For example: int main()
{
Loop: /*a goto label has function scope*/
.
.
.
.
Goto Loop;
}

3. Program scope
 Local variable are automatically created when they are declared
in the function and are usable only within that function.
 The local variables are unknown to other functions in the
programs
 Such variable stops to exists after the function in which they are
declared is exited and have to be re-created each time the
function is called.
 To avoid these, we can declare the variables outside any
function blocks called as global variable where are accessed
from any point in the program.
 Global variable are created at the beginning of program
execution and remain in existence throughout period of
execution of the program.
 If we have a variable declared in a function that has some name
as that of the global variable, then the function will use the local
variable declared within it and ignore the global variable
 Example:
#include<stdio.h>
int x=10;
void print();
void main()
{
printf(“\n the value of x in the main()=%d”,x);
int x=2;
printf(“\n the value of local variable x in the
main()=%d”,x);
print();
}
void print()
{
printf(“the value of x in the print(0=%d”,x);
}

4. File scope
 When a global variable is accessible until the end of the file, the
variable is said to have file scope.
 To allow variable to have file scope, declare that variable with
the static keyword before specifying its data type
static int x=10;
 A global static variable can be used anywhere from the file in
which it is declared but it is not accessible by any other file.

Storage class
It defines the scope (visibility) and lifetime of variable/functions declared in
a program. Storage class tells the information about variable/functions
 The storage class of a function or a variable determines the part
of memory where storage space will be allocated for that
variable or function.
 It specifies how long the storage allocation will continue to
exist.
 It specifies the scope of the variable or function i.e which
variable name is visible or accessible.
 It specifies whether the variable or function has internal,
external or no linkage.
 It specifies whether the variable/ function will be automatically
initialized to zero or to any undetermined value.
 There are 4 types
o Automatic
o External
o Register
o Static

1. Auto storage class


 Accessible within the function or block in which it is declared.
 It is stored in main memory.
 It exists when the function or block in which it is declared is
entered. Stops to exist when the control returns from the
function or the block in which it was declared.
 Its default value is garbage value.
#include<stdio.h>
void fun1()
{
int a=10;
printf(\n a=%d”, a);
}
void fun2()
{
int a=20;
printf(\n a=%d”, a);
}
void main()
{
Int a=30;
fun1();
fun2();
printf(\n a=%d”, a);
}

2. External storage class


 Accessible within all program file that are a part of the
program.
 It is store in main memory.
 Exists throughout the execution of the program.
 Its default value is zero
#include<stdio.h>
#include<FILE2.C>
int x;
void print(void);
int main()
{
x=10;
printf(“\n x in file1=%d”,x);
print();
return 0;
}

#include<stdio.h>
extern int x;
void print()
{
printf(“\n x in file 2-=%d”,x);
}
main()
{
//statements
}

3. Register storage class


 Accessible within the function or block in which is declared.
 It is stored in CPU register
 Exists when the function or block in which it is declared is
entered, stops to exist when the control returns from the
function or the block in which it was declared.
 Its default value is garbage.
#include<stdio.h>
int exp(int a, int b);
void main
{
int a=3, b=5,res;
res=exp(a,b);
printf(“\n %d to the power of %d=%d”,a,b,res);
}
int exp(int a, int b)
{
register int res=1;
int I;
for(i=1;i<=b;i++)
res=res*a;
return res;
}
4. Static storage class
 Local: accessible within the function or block in which it is
declared.
 Global:accessible within the program in which it is declared.
 It stored in main memory.
 Local: retains value between function calls or block entries.
 Global: preserves value in program file.
 Its default value is zero.
#include<stdio.h>
void print(void);
int main()
{
printf(“\n first call”);
print();
printf(“\n second call”);
print();
printf(“\n third call”);
print();
}
void print(void)
{
static int x;
int y=0;
printf(“\n static integer variable x=%d”,x);
printf(“\n integer variable y=%d”,y);
x++;
y++;
}

Recursion
• A function that calls itself is known as recursive function.
• The rule to be followed for recursive function is
– Establish boundary conditions that terminate the recursive calls
– Implement the recursive calls so that each call brings one steps closer
to the solution.
• Every recursive function must be provided with a way to end the recursion.
In this example when, n is equal to 0, there is no recursive call and recursion
ends.
Types of Recursion

1. Direct Recursion
A function is said to be directly recursive if it explicitly calls itself.

int func(int n)
{
if(n==0)
return 1;
else
return (func(n-1));
}
2. Indirect Recursion
It refers to a process where a function calls another function and that
function calls back the original function. The process of indirect
recursion takes place as illustrated below:

int func1(int n)
{
if(n==0)
return 1;
else
return (func2(n));
}
int func2(int x)
{
Return func1(x-1);
}
These two functions are indirectly recursive as they both call each
other.

3. Tail Recursion
 A recursion function is said to be tail recursive if no operations
are pending to be performed when the recursive function
returns to its caller.
 Tail recursive functions are highly desirable because they are
much more efficient to use as the amount of information that
has to be stored on the system stack is independent of the no.of
recursive calls.
 Ex1: the factorial function that we have written is a non-tail
recursive function in the below code:
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

 Because there is a pending operation of multiplication to be


performed on return from each recursive call.
 Whenever there is a pending operation to be performed, the
function becomes non-tail recursive.
 In such a non-tail recursive function, information about each
pending operation must be stored, so the amount of information
directly depends on the number of calls.
 Ex2: same factorial function can be written in tail recursive
manner
int fact(int n)
{
return fact1(n,1);
}
int fact1(int n, int res)
{
if(n==1)
return res;
else
return fact1(n-1,n*res);
}
 In this fact1 function preserves the syntax of fact(n)
 Here the recursion occurs in the fact1 function and not in fact
function.
 In the fact1 function there is no pending operation to be
performed on return from recursive calls
 In this case, the amount of information to be stored on the
system stack is constant and is independent of the number of
recursive calls.

4. Linear and Tree Recursion


 Recursive function can also be characterized depending on the
way in which recursion grows i.e in a linear fashion or forming
a tree structure.
 A recursive function is said to be linearly recursive when the
pending operation does not make another recursive call to the
function.
Ex: return fact1(n-1,n*res);
 A recursive function is said to be tree recursive, if the pending
operation makes another recursive call to the function.
 Ex:
ARRAYS
OPERATION ON ARRAY
1. Traversing an array
2. Inserting an element in an array
3. Deleting an element in an array
4. Merging two arrays
5. Searching an element in an array
6. Sorting an array in ascending or descending order

1. Traversing an array
 Traversing an array means accessing each and every element of
the array for a specific purpose.
 If A is an array of homogeneous data elements, then traversing
the data elements can include printing every element, counting
the total no.of elements, or performing any process on these
elements.
 Since array is linear data structure, traversing its element is very
simple and straightforward.
 The algorithm for array traversal
Step1: [initialization] set i=lower_bound
Step2: repeat steps 3 to 4 while i<=upper_bound
Step3: apply process to a[i]
Step4: set i=i+1 [end of loop]
Step5: exit
 Ex: write a program to print the position of the smallest of n
numbers using arrays.
Write a program to find the second largest number in an given
array.

2. Inserting an element in an array


Inserting an element in an array means adding a new data element to
an already existing array
 If the element has to be inserted at the end of the existing array,
then it is simple, we just have to add 1 to the upper_bound and
assign the value.
 Algorithm for inserting a new element to the end of the array.
Step1:start
Step2: set upper_bound=upper_bound+1
Step3: set A[upper_bound]=val
Step4: exit
 If the elements have to be inserted in the middle of the array,
we may have to move half of the elements from their position
in order to accommodate space for the new element.
 Algorithm for inserting a new element in middle of the array.
Step1:start
Step2: [initialization] set I=N
Step3: repeat steps 3 and 4 while I>=pos
Step4: set a[I+1]=A[I]
[end of loop]
Step5:set N=N+1
Step6: set A[pos]=val
Step7: exit
 Write a program to insert a number at a given location in a array
 Write a program insert a number in an array that is already sorted
in ascending order.
3. Deleting an element from an array
Deleting an element from an array means removing a data element
from an already existing array.
 If we have delete from the end of the existing array, then we have
to subtract 1 from the upper_bound
 Algorithm
Step1:start
Step2: set upper_bound=upper_bound-1
Step3:exit
 If we have to delete the element from the middle of the array, we
might have to move as much as half of the elements from their
position in order to occupy the space of the deleted element
 Algorithm
Step1: [initialization] set i=pos
Step2: repeat step 3 and 4 while I<=N-1
Step3: set a[I]=A[I+1]
Step4: set I=I+1
[end of loop]
Step5: set N=N-1
Step6: exit
 Write a program to delete a number from a given location in an array
 Write a program to delete a number from an array that is already
sorted in ascending order

4. Merging two arrays


Merging two arrays in a third array means first copying the contents
of the first array into the third array and then copying the contents of
the second array into the third array.
 Write a program to merging of two unsorted array
 Write a program to merge two sorted array
5. Searching for a value in an array
The process of finding a particular item in the large amount of data is
called searching.
The element to be searched is called key element. There are two methods
of searching:
1. Linear search.
2. Binary search.
1. Linear Search
 Linear search also called sequential search is a simple searching
technique.
 In this technique we search for a given key item in linear order i.e, one
after the other from first element to last element.
 The search may be successful or unsuccessful.
 If key item is present, the search is successful, otherwise unsuccessful
search.
Advantages of linear search

• Very simple Approach.


• Works well for small arrays.
• Used to search when elements are not sorted.

Disadvantages of linear search

• Less efficient if array size is large


• If the elements are already sorted, linear search is not efficient.

Algorithm

Step1:start
Step2: [initialize] set pos=-1
Step3: [initialize] set i=1
Step4: repeat step4 while I<=N
Step5: if A[I]=val
Set pos=I
Print pos
Goto step 7
[end of loop]
Step6:if pos=-1
Print” value is not present in the array”
[end of loop]
Step7: exit
Write the program to implement linear search
2. Binary search

Advantages of binary search


• Simple technique
• Very efficient searching technique Disadvantages
• The elements should be sorted.
• It is necessary to obtain the middle element, which are stored in array. If the
elements are stored in linked list, this method cannot be used.

Algorithm
Step1: start
Step2: [initialize] set beg=lower_bound, end=upper_bound,pos=-1
Step3: repeat step4 and 5 while beg<=end
Step4: set mid=(beg+end)/2
Step5: if a[mid=val, then pos=mid
Print pos
Goto step7
Else if a[mid]>val, then set end= mid-1
Else
Set beg=mid+1
[end of if]
[end of loop]
Step6: if pos=-1,then
Print “ value is not present in the array”
[end of if]
Step7: exit

6. Sorting an array in ascending or descending order


The process of arranging elements in either ascending order or
descending order is called Sorting.

Bubble Sort

• This is the simplest and easiest sorting technique.


• In this technique two successive elements of an array such as a[j] and a[j+1]
are compared.
• If a[j]>=a[j+1] the they are exchanged, this process repeats till all elements
of an array are arranged in ascending order.
• After each pass the largest element in the array is sinks at the bottom and the
smallest element in the array is bubble towards top. So this sorting technique
is also called as sinking sort and bubble sort.
Program to sort the given number using bubble sort

#include<stdio.h>
void main()
{
int a[20],n,.temp,i,j;
printf(“enter the number of elements\n”):
scanf(“%d”,&n);
printf(“enter the unsorted array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
If( a[ J ] > a[ J+1 ] )
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“the sorted elements arer\n”);
for(i=0;i<n;i++)
printf(“ %d\t”, a[i]);
}

Selection Sort
Passing arrays to function
Two dimensional arrays
Write a c program to read & print 2d array as a Array.
#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“eneter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“array elements are\n”); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
}

Write a c program to add two matrices.


#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3] ,c[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter array b elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“resultant matrix c is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}

Write a c program to copy one 2d array in to another 2d array


#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3];
clrscr();
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf(“%d”, &a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
}
}
printf(“matrix b is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
Write a c program to find biggest element in a matrix or 2D array.
#include<stdio.h>
void main()
{

int m,n,i,j,a[3][3]; clrscr();


printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
big=a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(big>a[i][j])
big=a[i][j];
}
}
printf(“big is %”,big);
}

Write a program to find sum of each row and sum of each column
#include<stdio.h>
void main()
{
int m,n,i,j,rsum,csum,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
rsum=0;
for(j=0;j<n;j++)
{
rsum=rsum+a[i][j];
}
printf(“sum is %d”,rsum);
}
for(i=0;i<m;i++)
{
csum=0;
for(j=0;j<n;j++)
{
csum=csum+a[i][j];
}
printf(“sum is %d”,csum);
}
}
Write a C program to implement Matrix Multiplication
#include<stdio.h>
void main()
{
int m,n,i,j,sum,p,q,k,a[3][3],b[3][3],c[3][3];
printf(“enter number of rows and columns of matrix a \n”);
scanf(“%d %d”,&m,&n);
printf(“enter number of rows and columns of matrix b \n”);
scanf(“%d %d”,&p,&q);
if(n!=p)
{
printf(“multiplication not possible\n”);
exit(0);
}
printf(“enter matrix a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter array b elements\n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf(“%d”,&b[i][j]);
}
}

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(“resultant matrix A is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix B is \n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
Multidimensional array
• The multidimensional array can have three, four or more dimensions.
• The first dimension is called as plane, which consists of rows and
columns.
• The c language considers the three dimensional array i.e an array of
two-dimensional arrays
Declaration:
Syntax: type array_name[planes][rows][columns]
Ex: int table[3][2][3];
Initialization:
Ex: int table[3][2][3] ={
{ {0,1,2},{3,4,5}},
{{6,7,8},{9,10,11}},
{{12,13,14},{15,16,17}}
};
Write a program to read and display a 2*2*2 array
Applications of array
• Arrays are widely used to implement mathematical vectors, matrices,
and other kinds of rectangular tables.
• Many databases include one-dimensional array whose elements are
records.
• Arrays are also used to implement other data structures such as
strings, stacks, queues, heaps, and tables.
• Arrays can be used for sorting elements in ascending or descending
order.

You might also like