[go: up one dir, main page]

0% found this document useful (0 votes)
23 views51 pages

POP Module 3

Uploaded by

ykishanrao05
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)
23 views51 pages

POP Module 3

Uploaded by

ykishanrao05
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
You are on page 1/ 51

MODULE 3

Functions: Introduction using functions, Function definition,


function declaration, function call, return
statement, passing parameters to functions, scope of
variables, storage classes, recursive functions

Introduction using functions


A function is a block of code to perform 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:

 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 allow programmer to build a customized library of frequently


used routines .Each routine can be programmed separate function and stored within special
library file.

TYPES OF C FUNCTIONS:

There are two types of functions in C Programming.


1.Library Function/Built-in functions.
2. User defined Function

Library Function:
Library functions are in-built function in C compiler.
Ex:
main(), printf(),sqrt(),scanf() etc.,

User defined Function:


C allows programmers to define their own function according to their requirement. These
types of functions are called user defined functions.

Advantages of user defined functions:


1. These functions helps to decompose the large program into small segments/modules
which makes programmer easy to understand, maintain and debug.
2. If the repeated code occurs in the program ,Function can be used to include those codes
and execute when needed by calling that function.
3. Programmer working a large project can divide the workload by making different
functions.

Function definition, function declaration, function call


Basic structure of C program with function:

#include<stdio.h>
Global declarations;
void function_name(parameter-list); //function declaration or function prototype
main()
{
local declarations;
statements;
function_name (parameter-list); //function call
…….
……….
}

void function_name(parameter-list) //function definition


{
local declarations;
statements;
}

 Every C program begins from main() and program starts executing the codes inside main()
functions.
 When the control of the program reaches to function_name() inside main() function, the
control of the program jumps to void function_name() and executes the code inside it.
 When all the codes inside the user defined function are executed the control of the program
jumps to the statement just after function_name() from where it is called.

Function Declaration:
 Every function must be declared before they are used in the program.
 Function declaration gives compiler information about
o function Name
o types of arguments to be passed and
o return type

 The syntax :
return_type function_name(formal-parameters);
Function call:
A function can be called by specifying its name followed by the list of arguments enclosed in the
parenthesis and separated by commas.

The Syntax:

function_name (actual parameters);

Function Definition:
Function definition contains programming codes to perform specific task.

Syntax:

return_type function_name(formal parameters)


{
Variable declaration;
Statement1;
Statement 2;
return value;
}

Where,
 return_type is the data type that the function returns.
 function_name refers the name of the function.
 The formal parameters are comma separated list of variables that receive the values from
the main program when it is called.
 The return statement returns the result of the function.
int sum(int a,int b);
main()
{
int a=2,b,=3,d;
d=sum(a,b);
printf(“%d”,d);
}

Actual and Formal Parameters:

 Argument/parameter refers to data that is passed to function (function definition)while


calling the function.

 Arguments listed in “function call” statements are referred as actual arguments.These


actual values are passed to a function to compute a value or to perform a task.

 The arguments used in the “function declaration” are referred as formal arguments.
 They are simply formal variables that accept or receive the values supplied by the calling
function.

 The number of actual and formal arguments and their data types should be same.
Ex:
Program to add two integers. Make a function add integers and display sum in
main()function:

Differences between Actual Parameters and Formal Parameters.


ARRAYS and FUNCTIONS:
The arrays can be passed to functions using two methods.

1. Passing individual elements of array.


All the arrays elements are passed as individual elements to a function like any other
variable.
The array element is passed as a value parameter i.e any change in the formal parameters
will not affect the actual parameters i.e actual element.

Ex:program to illustrate passing individual element of an array to a function.

#include<stdio.h>
void display(int a)
{
printf(%d”,a);
}

void main()
{
int c[3]={2,3,4};
display(c[2]);
}

Output: 4

2. Passing the whole array


#include<stdio.h>
void average(int m[])
{
int i,avg;
int sum=0;
for(i=0;i<7;i++)
sum=sum+m[i];
avg=sum/7;
printf(“Aggregate marks=%d”,avg);
}

void main()

int m[7]={60,50,70,80,40,80,70};

average(m);

}
Output:

Aggregate marks=70

CLASSIFICATION OF USER-DEFINED FUNCTIONS


1.Function with no arguments and no return value

2.Functions with no arguments and return value

3.Functions with arguments but no return value

4.Functions with arguments and return value

1.Function with no arguments and no return value(void and parameter less functions):

 This type of functions will not have any parameter and they will not return any value
to the calling functions.
 There is no data transfer between the calling function and called function.So calling
function cannot send values and hence called function cannot receive data.

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

#include<stdio.h>
void add();

void main()
{
add();
}

void add()
{
int a ,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d”,sum);
}
2.Functions with no arguments and with return type:

 Here there is no data transfer from the calling function to the called function.But there is
a data transfer from the called function to called function.
 When the function definition returns a value the calling function receives one value from
the called function.

Ex: Program to illustrate function with no arguments and return values.

#include<stdio.h>
int add();

void main()
{
int sum;
sum= add();
printf(“sum=%d”,sum);
}

int add()
{
int a ,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
return sum;
}

3.Functions with arguments but no return value

 Here there is a data transfer from the calling function to the called function.
 There is no data transfer from the called function to the calling function.The
called function will have the parameters but no return type.

Ex: Program to illustrate Functions with arguments but no return value

#include<stdio.h>
void add(int a,int b);

void main()
{
int a,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);

add(a,b);
}
void add(int a,int b)
{
sum=a+b;
printf(“Sum=%d”,sum);
}

4.Functions with arguments and return value

 There is a data transfer between calling and called function


 When parameters are passed the called function receives the values from the
calling function.when the function returns a value tha calling function can receive
a value from the called function.

Ex: Program to illustrate Functions with arguments and return value

#include<stdio.h>
int add(int a,int b);

void main()
{
int a,b,sum;
printf(“enter two numbers\n”);
scanf(“%d%d”,&a,&b);

sum= add(a,b);
printf(“Sum=%d”,sum);

int add(int a,int b)


{
int sum;
sum=a+b;
return sum;
}
Passing parameters to functions
 The variables used while invoking the called function are called actual parameters.
 The variables used in function header of the called function are called formal parameters.
 The various ways of passing parameters to the functions are:

1)pass by value/call by value

2) pass by reference/call by reference

Pass by value:

When a function is called with actual parameters,the values of actual parameters are copied into
formal parameters.If the values of the formal parameter changes in the function,the values of
actual parameters are not changed.

This way of passing parameters is called pass by value.

Ex:

#include<stdio.h>
void exchange(int m,int n)
{
int temp;
printf(“before exchange\n”);
printf(“m=%d,n=%d\n”,m,n);
temp=m;
m=n;
n=temp;
printf(“after exchange\n”);
printf(“m=%d,n=%d\n”,m,n);
}

main()
{
int a,b;
a=10,b=20;
printf(“before exchange\n”);
printf(“a=%d,b=%d\n”,a,b);
exchange(a,b);
printf(“after exchange\n”);
printf(“a=%d,b=%d\n”,a,b);
}

Pass by reference:

 A function is called with addresses of actual parameters.


 In the function header the formal parameters receive the addresses of actual parameters.
 The formal parameters donot contain the values,instead contain the addresses.
 Any variable if it contains an address ,it is called pointer variable.

Ex:

#include<stdio.h>
void exchange(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}

main()
{
int a,b;
a=10,b=20;
exchange(&a,&b);
printf(“a=%d,b=%d\n”,a,b);
}
PROGRAMS ON USERDEFINED FUNCTIONS:

1. write a program to find the factorial of given number using functions:

#include <stdio.h>
int fact(int n);

void main()
{
int no,factorial;

printf("Enter a number to calculate it's factorial\n");


scanf("%d",&no);
factorial=fact(no);
printf("Factorial of the num(%d) = %d\n",no,factorial);
}

int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

2.Write a userdefined function for reversing a number.Write a program to check for a


number a palindrome or not.

#include <stdio.h>
int reverse(int n); //func declaration

void main()
{
int n,r;

printf(“enter the number\n”);


scanf(“%d”,&n);

reverse(n);
if(n==r)
printf(“palindrome\n”);
else
printf(“not a palindrome”);
}

int reverse(int n)
{
int digit,r;
r=0;
while(n!=0)
{
digit=n%10;
n=n/10;
r=r*10+digit;
}
return n;

3.Write a program to find GCD and LCM of two numbers using functions.

#include <stdio.h>

void lcm_gcd(int ,int);

void main()
{
int no1,no2;
printf("Enter two Numbers\n");
scanf("%d %d",&no1,&no2);
lcm_gcd(no1,no2);
}

void lcm_gcd(int n1,int n2)


{
int gcd,lcm,remainder,numerator,denominator;
if (n1>n2)
{
numerator=n1;
denominator=n2;
}
else
{
numerator=n2;
denominator=n1;
}
remainder=numerator%denominator;
while (remainder!=0)
{
numerator=denominator;
denominator=remainder;
remainder=numerator%denominator;
}
gcd = denominator;
lcm = n1*n2/gcd;
printf("GCD of %d and %d = %d\n",n1,n2,gcd);
printf("LCM of %d and %d = %d\n",n1,n2,lcm);
}

4.Write a program to find whether a number is prime number or not using functions

#include<stdio.h>
int isprime(int n)
{
int i;
for(i=2;i<=n/2;i++)
{
if (n%i==0)
return 0;
}
return 1;
}

int main()
{
int n,prime;
printf(“enter the number\n”);
scanf(“%d”,&n);
prime=isprime(n);
if(prime==1)
printf(“ %d is prime number \n”,n);
else
printf(“%d is not prime number \n”,n);
}

5.Write functions to implement string operations such as compare, concatenate, string


length. Convince the parameter passing techniques.

#include<stdio.h>

char newstr[100];
char str1[100],str2[100];

int stringlen(char str[])


{
int i,len=0;
for(i=0;str[i]!='\0';i++)
len++;
return len;

}
int stringcmp(char str1[],char str2[])
{
int i,len1,len2,j;
len1=stringlen(str1);
len2=stringlen(str2);
if(len1!=len2)
return 1;
for(i=0;i<=len1;i++)
if(str1[i] !=str2[i])
return 1;
return 0;
}

void stringcat(char str1[], char str2[])


{
int i,j;

for(i=0,j=0;str1[i]!='\0';i++,j++)
newstr[j]=str1[i];
for(i=0;str2[i]!='\0';i++,j++)
newstr[j]=str2[i];
newstr[j]='\0';
return;
}

void main()
{

int len;
printf("enter first strings\n");
scanf("%s",str1);
printf("enter first strings\n");
scanf("%s",str2);
printf("\nlength of string 1 = %d\n",stringlen(str1));
printf("\nlength of string 2 = %d\n",stringlen(str2));

stringcat(str1,str2);
printf("\n new string=%s\n",newstr);

if (stringcmp(str1,str2)==0)
printf("\n %s and %s are same\n",str1,str2);
else
printf("\n %s and %s are not same\n",str1,str2);

}
Scope of variables
What is the Scope and Lifetime of a Variable
The scope is the variable region in which it can be used. Beyond that area, you cannot use
a variable. The local and global are two scopes for C variables. The local scope is limited
to the code or function in which the variable is declared.

Global scope is the entire program. Global variables can be used anywhere throughout
the program.

Lifetime is the life or alive state of a variable in the memory. It is the time for which a
variable can hold its memory. The lifetime of a variable is static and automatic. The static
lifetime variable remains active till the end of the program.

An automatic lifetime variable or global variable activates when they are called else they
vanish when the function executes.

Types of Variables in C programming


The variables in C programming can be divided into different types based on their scope
and storage classes.

Types of Variables on the Basis of Scope


Local Variables
Types of Variables on the Basis of Scope
The variable that is declared in a function or code is called a local variable. The scope of
Local variables is within the defined function only. You cannot use a local variable
outside the function (in which it is declared).

Program of local variables.

#include <stdio.h>

void person()
{
// Local Variables of the function
int age = 20;
float height = 5.6;

printf("age is %d \n", age);


printf("height is %f", height);
}

int main()
{
person();
return 0;
}

Global Variables
The scope of the global variable is the entire program. They are not defined inside any
function and can be used in any function.

Program to use a global variable in C

#include <stdio.h>

// Declaring global variable


int a = 23;

void function1()
{
// Function using global variable a
printf("The number is %d \n", a);
}

void function2()
{
// Function using global variable a
printf("The number is %d \n", a);
}

int main()
{
// Calling functions
function1();
function2();

return 0;
}
Storage classes

Declaration of a Storage class:

A storage class represents the visibility and a location of a variable.

A storage class in C is used to describe the following things:

The variable scope.

The location where the variable will be stored.

The initialized value of a variable.

A lifetime of a variable.There are two storage location in computer:CPU registers and main
memory

auto:
This is the default storage class for all the variables declared inside a function or a block. Hence,
the keyword auto is rarely used while writing programs in C language.

Auto variables can be only accessed within the block/function they have been declared and not
outside them (which defines their scope).

register:

Ex:

#include <stdio.h>

int main()

register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.

printf("%d",a);

}
static:

Static variables have the property of preserving their value even after they are out of their scope!
Hence, static variables preserve the value of their last use in their scope. So we can say that they
are initialized only once and exist till the termination of the program. Thus, no new memory is
allocated because they are not re-declared.

extern:

extern stands for external storage class. Extern storage class is used when we have global functions
or variables which are shared between two or more files.

extern storage class simply tells us that the variable is defined elsewhere and not within the same
block where it is used.

Basically, the value is assigned to it in a different block and this can be overwritten/changed in a
different block as well.

So an extern variable is nothing but a global variable initialized with a legal value where it is
declared in order to be used elsewhere. It can be accessed within any function/block.

The main purpose of using extern variables is that they can be accessed between two different files
which are part of a large program.
Recursive Functions
 A function that calls itself is known as recursion.
 The rule to be followed for a recursive function is that
- Establish a boundary conditions that terminate recursive calls.
- Implement the recursive calls so that each call brings one step closer to the
solution.
 Every recursive function must be provided with a way to end the recursion.

Ex:

1)Program to find the factorial of a number using recursion.


#include<stdio.h>
int fact(int n)
{
if(n==1)
return 1;
return (n*fact(n-1));
}
void main()
{
int n,res;
printf(“enter the value of n\n”);
scanf(“%d”,&n);
res=fact(n);
printf(“result=%d”,res);
}

The recursion refers to the process where a function calls itself either directly or indirectly.

There are two types of recursion.

1:Direct recursion

2: Indirect recursion

Direct Recursion:

It refers to a process where function calls itself directly as below.

Indirect Recursion:

It refers to a process where a function calls another function and that function calls back the
original function.The process of indirect recursion takes place as below.
Ex:

2) Program to generate Fibonacci series using recursion:

#include<stdio.h>
int fibonacci(int);

int main()
{
int terms;

printf("Enter terms: ");


scanf("%d", &terms);

for(int i = 0; i < terms; i++)


{
printf("%d ", fibonacci(i));
}

return 0;
}

int fibonacci(int num)


{

//base condition
if(num == 0 || num == 1)
{
return num;
}
else
{
// recursive call
return fibonacci(num-1) + fibonacci(num-2);
}

How it works:

Let us see the evaluation of Fibonacci(5).

fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)

ARRAYS
 Arrays are the collection of elements of same data type.Ordered set of similar data
elements.
 All the data elements of an array are stored sequentially in consecutive memory locations
one after the other in memory(RAM).
 Array is a derived data type.
 The elements of an array are of the same data type and each element can be accessed by
using the same name of the array.
 To refer an element in the array ,the name of the array along with the position of the
element.The position of the element must be writtern within square brackets( []) . The
position of the element is enclosed within square br-ackets called “subscript” or “index”.
Each value in the array is a reference by a single name , which is the name of the array and
the subscript or index , which indicates the position of the value in the array.

The subscript is always a positive integer number,which is enclosed in pair of square brackets.

Example: int age[5];


Classification Of Arrays:
The arrays are classified based on how the data elements are arranged for human understanding.

Arrays are classified into 2 types:

1)Single dimensional array(1-Dimension or 1D)

2)Multidimensional array(2D,3D etc.,)

SINGLE DIMENSIONAL ARRAY (1D)


 A single dimensional array is a linear list consisting of related elements of the same data
type.
 In memory all elements are stored in continuous memory location on after the other.

Declaration of One Dimensional Arrays:

 An array must be declared before it is being used in program.

 During declaration the size of the array has to be specified.This informs the
compiler to allocate and reserve the specified memory locations.

 A one dimensional array can be declared using the syntax :

data_type array_name[array_size];

where
 data_type can be a basic datatype int,float or char etc.
 array_name is the name of the array which is taken from the rules of
identifier.
 array_size indicatesthe number of elements in the array which is always a
positive number.
 Ended with semicolon
Example : int age[5];

What is the size of array?


The size of the array depends on the type of the data elements stored and the number of
elements.

Array size or Total amount of memory = size *sizeof(data_type)


Here,
size – the number of data elements
data_type – the data type of data elements.

 Here the size of the array “age” is 5 times the size of int because there are 5
elements.
i.e for int age[5],
the total amount of memory is 20bytes .(i.e 5*2)

Initialization of One Dimensional array:


Assigning the values to array is called initialization of an array.

Two methods of initialization:

1) Compile time initialization:


2) Run time initialization:

1) Compile time initialization:

Initialization of elements of arrays can be done in same way as ordinary variables are done when
they are declared.

Syntax:

data_type array name[array_size] = {v1,v2,v3…vn};


where
 data_type can be a basic datatype int,float or char etc.
 array_name is the name of the array which is taken from the rules of
identifier.
 array_size indicates the number of elements in the array which is always a
positive number.
 v1,v2,v3….vn are the values of the same data type.values are enclosed in
curly braces ‘{‘ and ‘}’ and are separated by comma .
These values are assigned to the array elements in the same order as the
order of these values.
 Ended with semicolon

Example:

int age[5] = {2,3,34,3,4};

Partial initialization:

If the number of values to be initialized is less than the size of the array,then the remaining
locations will be initialized to zero automatically by the compiler .

Example:

int age[5]={2,3};

Initialization without size:

Here,even though the exact number of elements to be used in array is not specified ,then the array
size will be set to the total number of values specified.The array size will be set automatically.
Example:

int age[] = {2,3,34,3,4};

Array initialization with a string:

Example:

char b[] = “COMPUTER”;

Even though the string “COMPUTER” contains 8 charecters,because it is a string ,it always ends
with null character.So the srray size is 9 bytes.(i.e string length + 1 byte for null charecter )

2) Run time initialization:


- Initialization is done during the run time.

Example :

Reading and Writing one dimensional array at run time:

int age[5];
//Reading
for(i=0;i<5;i++)
{
scanf(“%d”,&age[i]);
}
//Writing
for(i=0;i<5;i++)
{
printf(“%d\n”,age[i]);
}
Programs:
1) Program to find sum and average of N numbers using 1D array.

#include<stdio.h>
main()
{
int num[100],sum=0,Avg;
int n,i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter elements one by one\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&num[i]);
}
//Adding all elements
for(i=0i<n;i++)
{
sum=sum+num[i];
}

Avg = sum/n;
printf(“Sum o f elements=%d\n”,sum);
printf(“Average of elements=%d\n”,Avg);
}

2) Program to find sum of positive and negative numbers and their average.

#include<stdio.h>
main()
{
int num[100],psum=0,nsum=0,Avg;
int n,i;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter elements one by one\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&num[i]);
}
//Adding all positive and negative elements
for(i=0;i<n;i++)
{
if(num[i]>=0)
psum=psum+num[i];
else
nsum=nsum+num[i];
}

Avg =(psum+nsum)/n;
printf(“Sum o f positive numbers=%d\n”,psum);
printf(“Sum o f negative numbers=%d\n”,nsum);
printf(“Average of all numbers=%d\n”,Avg);
}

3) Program to generate Fibonacci numbers using arrays.

Fibonacci series is of the form : 0,1,1,2,3,5,8….


i.e first two numbers are 0 and 1.
The third number number is calculated with adding the first two numbers.
The fourth number is calculated by adding 2 nd and 3rd number. And soon
Ex: number1=0 and number2=1
number3= number1 + number2
= 0+1=1
number4=number2+number3
=1+1=2
.
.
.
.and soon

#include<stdio.h>
int main()
{
int n,i,a[100];
printf(“Till what term you want the Fibonacci series\n”);
scanf(“%d”,&n);

a[0]=0;
a[1]=1;

for(i=2;i < n;i++)


{
a[i] = a[i-1] + a[i-2];
}
printf(“Fibonacci numbers are : “);
for (i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
}

4)Program to find the largest of N numbers:

#include<stdio.h>
main()
{
int A[100],n,i,large,pos;

printf(“enter the number of elements\n”);


scanf(“%d”,&n);

printf(“Enter the elements\n”);


for(i=0;i<n;i++)
{
scanf(“%d”,&A[i]);
}

large = A[0]; //1st element as large


pos=0; //position is 0

for(i=1;i<n;i++) ///Starting from second element


{
if(A[i]> large)
{
large =A[i];
pos=i;
}
}

printf(“Largest number is =%d\n”,large);


printf(“Its position=%d\n”,i+1);
}

Searching:

The process of finding a particular elements in the large amount of data is called searching.

Two important searching techniques are

1) Linear Search
2) Binary Search
Linear Search:Sequential search

In this technique, we search for a given key item in the list in linear order one by one other.The
element to be searched is often called key item.

5) Program to perform linear search:

#include<stdio.h>
#include<stdlib.h>
main()
{
int A[20],n,i,key;

printf(“enter the number of elements\n”);


scanf(“%d”,&n);

printf(“Enter the elements\n”);


for(i=0;i<n;i++)
{
scanf(“%d”,&A[i]);
}

printf(“Enter the element to be searched\n”);


scanf(“%d”,&key);

for(i=0;i<n;i++)
{
if(A[i] == key)
{

printf(“Successful search …. %d found at %d position”,key,(i+1));


exit(0);
}
}
printf(“Un-successful search … %d not found\n”,key);
}

Binary Search:

This technique can be applied if the elements to be compared are either in ascending or descending
order.

For a given sorted array of n elements.Binary search is used to search for a key element by the
following steps:

1. Binary search locates the middle element of the array and compares the search value by
having the low and high boundary values as low=0,high=n-1 and finding mid as
(low+high)/2.
2. If they are equal, it displays the subscript of that element , otherwise the search is reduced
to one-half .
3. If the search value is less than the middle value of the array, the first half is searched
,otherwise the second half is searched.
4. This continues until the search value is equal to the middle value of the array or until the
search value is not found.
6) Program to perform Binary Search:

#include<stdio.h>
#include<stdlib.h>
main()
{
int A[20],n,i,key,high,low,mid;

printf(“enter the number of elements\n”);


scanf(“%d”,&n);

printf(“Enter the elements\n”);


for(i=0;i<n;i++)
{
scanf(“%d”,&A[i]);
}

printf(“Enter the element to be searched\n”);


scanf(“%d”,&key);
low=0; //initialization of low and high values
high=n-1;

while(low <= high)


{
mid = (low+high)/2;
if(key== A[mid])
{

printf(“Successful search …. %d found at %d position”,key,(i+1));


exit(0);
}

if( key < A[mid])


high=mid-1;
else
low=mid+1;
}

printf(“Un-successful search … %d not found\n”,key);


}

Sorting:

More often programmers will be working with large amount of data and is necessary to arrange
them in ascending or descending order. The process of rearranging the given elements so that they
are in ascending or descending order is called sorting.
Two techniques of sorting are :

1) Bubble sort
2) Selection sort

Bubble Sort:

Simplest sorting technique. In this technique the two successive items A[i] and A[i+1] are
exchanged whenever A[i] >= A[i+1].

Lets try to understand with an example:

Take the array of elements : A [ ] = { 7, 4, 5, 2}

In step 1)

- First element i.e 7 is compared with Second element i.e 4 in the list. Since 7>4, 7 is moved
ahead of 4.
- Then Second element i.e 7 is compared with third element i.e 5,Since 7 > 5, 7 is moved
ahead.
- Again third i.e 7 and fourth element i.e 2 is compared , 7>2 if so exchange of elements is
taken place.
- Since all the other elements are of a lesser value than 7, 7 is moved to the end of the array.

Now the array is A[]={4,5,2,7}.

NOTE: In any of the above points if the 1st elements is less than than the 2 nd elements then
exchange of elements will not take place.(in step1)
In step 2)

- 4 is compared with 5. Since 5>4 and both 4 and 5 are in ascending order, these elements are
not swapped.
- However, when 5 is compared with 2, 5>2 and these elements are in descending order.
Therefore, 5 and 2 are swapped.

Now the array is A[]={4,2,5,7}.

In step 3)

- the element 4 is compared with 2. Since 4>2 and the elements are in descending
order, 4 and 2 are swapped.

The sorted array is A[]={2,4,5,7}.

7)Develop a program to sort the given set of N numbers using Bubble sort.

#include<stdio.h>

int main()
{
int n,i,j,A[10],temp;

printf("Enter the no. of elements :\n");


scanf("%d",&n);
printf("Enter the array elements \n”);
for(i=0;i<n;i++)
{
scanf("%d",&A[i]);
}
printf("The elements before sorting are \n");
for(i = 0 ; i < n ; i++)
{
printf("%d \t",A[i]);
}

//Bubble sort logic

for(j=1 ; j < n ; j++) // Number of Passes


{
for(i= 0 ; i< n-j; i++) // Comparisons
{
if(A[i] >= A[i+1])
{
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
}

printf("\n The elements after sorting are \n");


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

Multi Dimensional Array:

Arrays with two or more dimensions .

Two Dimensional Arrays:

Arrays with two sets of square brackets [][] are called 2D arrays.

Data elements are arranged in the matrix form-arranged in row wise and column wise in tabular
fashion.

int A[][];

row number column number

int b[10][3];

int b[2][4][1];

Declaration of 2D arrays:

Syntax:

data_type array_name[size1][size2];

where

 data_type can be a basic datatype int,float or char etc.


 array_name is the name of the array which is taken from the rules of
identifier.
 size1 represents number of rows and size2 represents number of columns.
 Ended with semicolon

Ex: int A[3][2];


Here three rows and two columns.
Col-0 Col-1

Row0 A[0][0] A[0][1]

A[1][0] A[1][1]
Row1

A[2][0] A[2][1]
Row2

Initialization of 2D array:

Compile time initialization:

Syntax:
data_type array_name[size1][size2]={
{a1,a2 ,…..,aN},
{b1,b2,……bN},
.
.
{z1,z2,…….zN}
};

where

 data_type can be a basic datatype int,float or char etc.


 array_name is the name of the array which is taken from the rules of
identifier.
 size1 represents number of rows and size2 represents number of columns.
 a1,a2….aN are the array elements of 1 st row
 b1,b2,…..bN are the elements of 2 nd row and soon
 Ended with semicolon

Ex:

int a[2][3]={ {11,26,3},

{40,5,6}

};

11 26 3
a[0][0] a[0][1] a[0][2]
40 5 6
a[1][0] a[1][1] a[1][2]
OR

int a[2][3]= { 11,2,3,41,25,6};

11 2 3
a[0][0] a[0][1] a[0][2]
41 25 6
a[1][0] a[1][1] a[1][2]

Partial Array initialization:

Ex:

int a[2][3]={ {1,2},

{4,56}

};

1 a[0][0] 2 0
a[0][1] a[0][2]
4 56 0
a[1][0] a[1][1] a[1][2]

Without specifying the array size:

Ex:

int a[][]={ {1,2},

{4,56}

};

1 a[0][0] 2
a[0][1]
4 56
a[1][0] a[1][1]
Run time initialization:

Reading and Writing two dimensional array at run time:

int age[5][5],i,j;
//Reading
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&age[i][j]);
}
}
//Writing
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,age[i][j]);
}
}

Programs:

1) Write a C program to read m*n elements from the keyboard and display the m*n
elements on the screen.

#include<stdio.h>

main()

int A[10][10];

int m,n,i,j;

printf(“Enter the order of the matrix\n”);

scanf(“%d%d”,&m,&n);

//Read the elements of the matrix

printf(“enter the elements of the matrix A\n”);

for (i=0;i<m;i++)

for(j=0;j<n;j++)
{

scanf(“%d”,&A[i][j]);

//Display the elements of the matrix

for (i=0;i<m;i++)

for(j=0;j<n;j++)

printf(“%d ”,A[i][j]);

printf(“\n”);

2) Write a C program to add to matrices or addition of two matrices

To find addition and subtraction of the matrices ,both rows and columns should be same for both
the matrices.

Ex: A=2*3 matrix B=2*3 matrix

A= 1 2 3
4 5 6

B= 1 2 3
4 5 6

A+B = 1+1 2+2 3+3 2 4 6

4+4 5+5 6+6 8 10 12

Let A and B are two matrices of size m*n


C[i][j]=A[i][j]+B[i][j]

#include<stdio.h>

main()

{
int A[10][10],B[10][10],C[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);

printf(“enter the elements of the matrix A\n”);


for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“enter the elements of the matrix B\n”);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&B[i][j]);
//Addition of two matrices
for (i=0;i<m;i++)
for(j=0;j<n;j++)
C[i][j]=A[i][j]+B[i][j];
printf(“The resultant matrix C is\n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}

3) Write a C program to subtract to matrices.

Ex: A=2*3 matrix B=2*3 matrix

A= 10 12 3
4 5 6

B= 1 2 3
1 5 2

A-B = 10-1 12-2 3-3 8 10 0

4-1 5-5 6-2 3 0 4

Let A and B are two matrices of size m*n

C[i][j]=A[i][j]-B[i][j]

#include<stdio.h>

main()

{
int A[10][10],B[10][10],C[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the elements of the matrix A\n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“enter the elements of the matrix B\n”);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&B[i][j]);
//subtraction of two matrices
for (i=0;i<m;i++)
for(j=0;j<n;j++)
C[i][j]=A[i][j]-B[i][j];
printf(“The resultant matrix C is\n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}

4)Program to find Transpose of matrix.

Transpose of the matrix is changing rows to columns and columns to rows.

For 2*3 matrix

A= 1 2 3
4 5 6

Its transpose will be is 3*2

= 1 4
2 5
3 6
#include<stdio.h>

main()

{
int A[10][10],B[10][10];
int m,n,i,j;
printf(“Enter the order of the matrix\n”);
scanf(“%d%d”,&m,&n);

printf(“enter the elements of the matrix A\n”);


for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
//To obtain transpose of A
for (i=0;i<m;i++)
for(j=0;j<n;j++)
B[i][j]=A[j][i];
printf(“The orginal 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(“The Transpose Matrix is\n”);
for (i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf(“%d\t”,B[i][j]);
}
printf(“\n”);
}
}

5) Write a program to find the product of two matrices.


Multiplication of two matrices is possible iff the number of columns of the first matrix
and the number of rows of the second matrix are same.

Let m*n is the size of first matrix and

p*q is the size of the second matrix.

If n is equal to p , multiplication is possible.

If n is not equal to p,multiplication is not possible.

- If the size of A is m*n ,size of B is p*q,then the size of C is m*q

C[i][j] = Ʃk=0 to n-1 ( A[i][k] * B [k][j])

Ex: A = 2*3 matrix i.e m*n

B=3* 3 matrix i.e p*q

n==p , matrix multiplication possible.

A= 1 1 1

1 3 2

B= 2 1 2

2 12 2

2 2 2

Matix multiplication 1st row*1st column then 1st row * 2nd column…
Then 2nd row *1st column,2nd row*2 nd column..

1*2+1*2+1*2 1*1+1*12+1*2 1*2+1*2+1*2

1*2+1*2+1*2 3*1+3*12+3*2 2*2+2*2+2*2

= 6 15 6

6 45 12

#include<stdio.h>

#include<stdlib.h>

main()

{
int A[10][10],B[10][10],C[10][10];
int m,n,p,q,i,j,k;
printf(“Enter the order of the matrix A\n”);
scanf(“%d%d”,&m,&n);

printf(“Enter the order of the matrix A\n”);


scanf(“%d%d”,&p,&q);
if(n!=p)
{ printf(“Matrix multiplication not possible\n”);
exit(0);
}
printf(“enter the elements of the matrix A\n”);
for (i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&A[i][j]);

printf(“enter the elements of the matrix B\n”);


for (i=0;i<p;i++)
for(j=0;j<q;j++)
scanf(“%d”,&B[i][j]);
//product of two matrices
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(“The Product of 2 matrices is\n”);
for (i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,C[i][j]);
}
printf(“\n”);
}
}

Extra Programs
1)A and B are two arrays each with 10 elements .Write a program to find array C
such that.
C[0] = A[0] + B[9]
C[1]= A[1] + B[8]
C[2] = A[2]+ B[7]
.
.
.
.
C[9] = A[9]+ B[0]

#include<stdio.h>

main()
{

int A[10],B[10],C[10],i,j,n;

printf("enter the value of n\n");

scanf("%d",&n);

for(i=0;i<n;i++)

C[i]=A[i]+B[n-1-i];

printf("array C is\n");

for(i=0;i<n;i++)

printf("C[%d]=A[%d]+B[%d]\n",i,i,(n-1-i));

2)Write a C program to check whether the two given matrices are equal or not//
#include<stdio.h>
main()
{
int m,n,A[20][20],B[20][20],i,j;
printf(“enter the size of matrix A\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the size of matrix B\n”);
scanf(“%d%d”,&m,&n);
printf(“enter the elements of matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“enter the elements of matrix B\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&B[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if (A[i][j]==B[i][j])
{
printf(“matrix A is equal to matrix B\n”);
return 0;
}
else
{
printf(“matrix A is not equal to matrix B\n”);
return 0;
}
}
}
}

Applications of Arrays in C
In c programming language, arrays are used in wide range of applications. Few of them are as
follows...

● Arrays are used to Store List of values

In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.

● Arrays are used to Perform Matrix Operations

two dimensional arrays can be used to create matrix. We can perform various operations on
matrices using two dimensional arrays.

● Arrays are used to implement Search Algorithms

We use single dimensional arrays to implement search algorihtms like Linear Search, Binary
Search
● Arrays are used to implement Sorting Algorithms

We use single dimensional arrays to implement sorting algorihtms like Insertion Sort,Bubble
Sort,Selection Sort,Quick Sort,Merge Sort, etc.,

● Arrays are used to implement Datastructures


We use single dimensional arrays to implement datastructures like Stack Using Arrays,Queue
Using Arrays

● Arrays are also used to implement CPU Scheduling Algorithms

You might also like