Module 3 - C
Module 3 - C
Module 3 Notes
Functions: Introduction using functions, Function definition, function
declaration, function call, return statement, passing parameters to
functions, scope of variables, storage classes, recursive functions. Arrays:
Declaration of arrays, accessing the elements of an array, storing values in
arrays, Operations on arrays, Passing arrays to functions, two dimensional
arrays, operations on two-dimensional arrays, two-dimensional arrays to
functions, multidimensional arrays, applications of arrays.
1
Principles of Programming using C – BPOPS203 MODULE 3
MODULE-3
FUNCTIONS
A function is a block of statements that performs a particular task. Functions are basic building
blocks of C program. A function is a series of instructions or group of statements with one
specific purpose. A function is a program segment that carries out some specific, well defined
task. A function is a self-contained block of code that performs a particulartask.
1. Built-in functions:
The C compiler has a collection of functions which performs a predefined task. Thesefunctions
are defined in the library of C compiler which are used frequently in the C program. These
functions are written by designers of C compiler.
C supports many built in functions like
Mathematical functions ex: sqrt(), pow()
String manipulation functions ex: strcat(), strlen()
Input and output functions ex: printf(), scanf()
Memory management functions ex: malloc(), calloc()
2
Principles of Programming using C – BPOPS203 MODULE 3
Syntax:
return_type function_name(type(1) parameter(1), ...,type(n) parameter(n));
b. Function Call
Invocation of the function is called function call. Control from calling function will be transferred to
the called function when the function call is made. The parameters used in function call are called
actual parameters.
Syntax:
function_name(parameter(1), ... parameter(n));
c. Function Definition
Function definition contains programming codes to perform specific task. Function definition consists
of two parts. Function Header that identifies the function, followed by Function Body that contains
the executable code for that function. The parameters used in function definition are called formal
parameters.
Syntax:
return_type function_name(type(1) parameter(1),..,type(n) parameter(n))
{
Local variable declaration;
Statement1;
Statement2;
.
.
Statement-n;
return statement;
}
Example:
#include <stdio.h>
#include <conio.h>
int add(int a, int b); ------------- function declaration
void main()
{
int a, b, sum;
clrscr();
printf("Enter two numbers to add \n");
scanf("%d %d", &a, &b);
3
Principles of Programming using C – BPOPS203 MODULE 3
return statement:
The return statement terminates the execution of the called function and returns control to the
calling function. When the return statement is encountered, the program execution resumes in the
calling function at the point immediately following the function call. A return statement may or
may not return a value to the calling function.
Syntax: return <expression>;
Specifying expression is optional. The value of expression, if present, is returned to the calling
function. A function that has void as its return type cannot return any value to the calling function.
For functions that have no return statement, the control automatically returns to the calling function
after the last statement of the called function is executed.
Categories / Classification of user defined functions: (based on parameter passing and return
value)
The user defined function categorized into 4 types. They are
a. Function without parameters and no return value
b. Function without parameters and return value
c. Function with parameters and no return value
d. Function with parameters and return value
4
Principles of Programming using C – BPOPS203 MODULE 3
Program:
#include <stdio.h>
#include <conio.h>
void add();
void main()
{
clrscr();
add();
getch();
}
void add()
{
int a, b, sum;
printf("Enter two numbers to add : ");
scanf("%d %d", &a, &b);
sum=a+b;
printf("\n sum=%d", sum);
}
Output:
Enter two numbers to add: 2 3
sum=5
5
Principles of Programming using C – BPOPS203 MODULE 3
6
Principles of Programming using C – BPOPS203 MODULE 3
7
Principles of Programming using C – BPOPS203 MODULE 3
8
Principles of Programming using C – BPOPS203 MODULE 3
9
Principles of Programming using C – BPOPS203 MODULE 3
Program:
#include <stdio.h>
#include <conio.h>
void exchange(int a, int b);
void main()
{
int x,y,
clrscr();
printf(“Enter values of x & y : “);
scanf(“%d %d “, &x, &y);
printf(“\n old values x=%d y =%d”, x, y);
exchange(&x,&y) ;
printf(“\n new values x=%d y =%d”, x, y);
}
void exchange(int *a, int *b)
{
int *temp;
*temp=*a;
*a=*b;
*b=*temp;
}
Output:
Enter values of x & y: 2 3
old values x=2 y =3
new values x=3 y =2
10
Principles of Programming using C – BPOPS203 MODULE 3
RECURSION:
Usually a function (user defined function) is called from main function. If a function calls itself, it is
known as recursion. There are two types of recursion:
a. Direct Recursion
b. Indirect Recursion
Syntax:
function1()
{
11
Principles of Programming using C – BPOPS203 MODULE 3
function1();
}
Factorial using Recursion: Write a C Program to find factorial of a given number using recursion.
#include <stdio.h>
#include <conio.h>
int factorial(int);
void main()
{
int num,fact;
clrscr();
printf(“Enter the number to find it’s factorial:”);
scanf(“%d”,&num);
if(num<0)
{
printf(“\nFactorial of negative number is not possible”);
}
else
{
fact=factorial(num);
printf(“The factorial of %d is %d”, num,fact);
}
getch();
}
int factorial(int num)
{
if(num==0||num==1)
{
return 1;
}
else
{
return(num*factorial(num-1));
}
}
Output:
Enter the number to find its factorial:5
The factorial of 5 is 120
12
Principles of Programming using C – BPOPS203 MODULE 3
Fibonacci Series using Recursion: Write a C Program to print Fibonacci Series using recursion.
#include <stdio.h>
int Fibonacci(int Number)
{
if (Number ==0)
return 0;
else if (Number==1)
return 1;
else
return(Fibonacci(Number-1)+Fibonacci(Number-2));
}
void main()
{
int Number, i=0;
printf("Please enter How many Fibonacci number to be displayed:\n ");
scanf("%d",&Number);
printf("Fibonacci series are:\n");
for(i=0;i<Number;i++)
{
printf("%d\t", Fibonacci(i));
}
}
GCD using Recursion: Write a C Program to find GCD of two numbers using recursion.
#include <stdio.h>
int GCD(int, int);
void main()
{
int num1, num2, res;
printf("enter two numbers\n”);
scanf(“%d%d”,&num1,&num2);
res=GCD(num1, num2);
printf(“\n GCD of %d and %d = %d”, num1, num2, res);
getch();
}
intGCD(int x, int y)
{
int rem;
rem=x%y;
if(rem==0)
return y;
13
Principles of Programming using C – BPOPS203 MODULE 3
else
return (GCD(y,rem));
}
Write C Program to calculate exp(x,y) using recursion.
#include <stdio.h>
int exp_rec(int, int);
void main()
{
int num1, num2, res;
printf(“\nEnter two numbers”);
scanf(“%d%d”, &num1,&num2);
res=exp_rec(num1,num2);
printf(“\nRESULT=%d”,res);
getch();
}
int exp_rec(int x, int y)
{
if(y==0)
return 1;
else
return (x*exp_rec(x,y-1));
}
SCOPE OF VARIABLES
A scope in any program is a region of the program where a defined variable can have its existence
and beyond that it cannot be accessed. Scope is the accessibility and visibility of the variables at
different points in the program. A variable or constant in C has four types of scope: block, function,
program, file.
1. Block Scope: A statement block is a group of statements enclosed within opening and closing
curly brackets { }. If a variable is declared within a statement block then as soon as the control exits
that block, the variable will cease to exist. Such a variable also known as local variable is said to have
block scope.
#include <stdio.h>
int main()
{
int var = 34; // Scope of this variable is within main() function only.
printf("%d", var);
return 0;
}
14
Principles of Programming using C – BPOPS203 MODULE 3
2. Function Scope: The only type of identifier with function scope is a label name. A label is
implicitly declared by its appearance in the program text and is visible throughout the function that
declares it. A label can be used in a goto statement before the actual label is seen. Function scope
begins at the opening of the function and ends with the closing of it. Function scope is applicable to
labels only. A label declared is used as a target to goto statement and both goto and label statement
must be in same function.
void main()
{
……
……
loop:
……
……
……
goto loop;
…..
…..
}
In the above example label loop is visible from the beginning to the end of the main() function.
3. Program Scope: Program scope of variables in C is defined as having the availability of the
variable throughout the program. It means that the variable has a global scope, and it is available
all around for every function and every block in the program. Global variables declared outside the
function bodies have a program scope. The availability of global variables stays for the entire
program after its declaration. Moreover, global variables are initialized to zero automatically by the
compiler.
#include <stdio.h>
// variable with program scope
int x = 10;
void func()
{
// x is available in func() function,
// x now equals 10 + 10 = 20
x += 10;
printf("Value of x is %d\n", x);
}
void main()
{
func();
// x is also available in main() function
15
Principles of Programming using C – BPOPS203 MODULE 3
STORAGE CLASSES:
Storage Classes defines the scope and lifetime of variables and functions declared within a C
program.
Syntax: <storage_class_specifier> <data_type> <Variable_name>
printf("\nLoop started:\n");
for (i = 1; i< 5; i++)
{
static int y = 5;
int p = 10;
y++;
p++;
printf("\nThe value of y declared as static is %d\n",y);
printf("The value of non-static variable p is %d\n",p);
}
printf("\nLoop ended:\n");
}
void main()
{
printf("A program to demonstrate storage Classes in C\n\n");
autoStorageClass();
registerStorageClass();
externStorageClass();
staticStorageClass();
}
18
Principles of Programming using C – BPOPS203 MODULE 3
19
20
20
Principles of Programming using C – BPOPS203 Module 3
22
Principles of Programming using C – BPOPS203 Module 3
23
Principles of Programming using C – BPOPS203 Module 3
ARRAYS
Definition
An Array is a fixed-size sequenced collection of elements of the same data type.
Arrays are referred to as structured data types because they are used to represent data values that
have a structure of some sort and array is a derived data type.
Numerical arrays are arrays in which the values of array elements are numbers (integer/float).
Character arrays or Strings are arrays in which the values of array elements are characters.
Types of Arrays
1. One Dimensional Arrays (1-D Arrays)
2. Two Dimensional Arrays (2-D Arrays)
3. Multi Dimensional Arrays
Declaration:
Declaration of array is used for creation of memory space based on the type to store the values of
array.
24
Principles of Programming using C – BPOPS203 Module 3
Example:
int n[5];
float avg[5];
char city_name[10];
Initialization:
Initialization is assigning values to array elements during declaration. Initialization of array can be
done in TWO ways:
i. Compile Time Initialization
ii. Run Time Initialization
Example:
intn[5]={10,20,30,40,50}; 10 20 30 40 50
n[0] n[1] n[2] n[3] n[4]
10 20 30 0 0
NOTE: If the number of values in the list is less than array size then the remaining elements are
assigned to 0 automatically.
25
Principles of Programming using C – BPOPS203 Module 3
32.5 -22.22 0 55 7
B E N G A L U R U \0
NOTE: When the user initializes the character array by giving each character then the \0 character
should also be specified. Also, one extra element space must be declared to store null character
(\0) in case of character arrays.
char city_name[10]= { ‘B’ , ‘E’ , ‘N’ , ‘G’ , ‘A’ , ‘L’ , ‘U’ , ‘R’ , ‘U’ , ‘\0’};
NOTE: If array size is not given then system automatically allocates the required memory space.
26
Principles of Programming using C – BPOPS203 Module 3
age[1]=4;
age[2]=34;
age[3]=3;
age[4]=4;
iii. Partial array initialization:
It is allowed in C language, if the number of values to be initialized is less than size of array,then the
remaining locations will be initialized to zero automatically by compiler.
Example: int age[5]={2,3}; 2 3 0 0 0
27
Principles of Programming using C – BPOPS203 Module 3
float avg;
clrscr();
printf(“Enter the value of n:\n”);
scanf(“%d”, &n);
printf(“ Enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
oddsum=0;
evensum=0;
for(i=0;i<n;i++)
{
if(a[i] % 2 == 0)
evensum=evensum+a[i];
else
oddsum=oddsum+a[i];
}
avg=(evensum+oddsum)/n;
printf(“The sum of EVEN number is:%d\n”,evensum);
printf(“The sum of ODD number is:%d\n”, oddsum);
printf(“The average of all number is:%f\n”, avg);
getch();
}
Output:
Enter the value of n:
5
Enter the array elements
1
2
3
4
5
The sum of EVEN number is: 6
The sum of ODD number is: 9
The average of all number is: 3
Example 3:
Write C Program to evaluate the polynomial f(x) = a4x4+a3x3+a2x2+a1x+a0, for a given value of x
and its coefficients using Horner’s method.
29
Principles of Programming using C – BPOPS203 Module 3
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float coeff[10], x, fx;
int i;
clrscr();
printf(" Enter the coefficients of a given polynomial (i.e.,a0,a1,a2,a3,a4 )\n");
for(i = 0 ; i<= 4 ; i++)
{
printf(“coeff [%d] = \n“,i);
scanf("%f", &coeff[ i] );
}
printf(" Enter the value of x \n");
scanf("%f",&x);
fx=0;
for( i = 4 ; i>= 0 ; i--)
fx = fx +pow(x,i) * coeff[ i];
printf("f(%f) = %.2f\n",x,fx);
getch();
}
Output
Enter the coefficients of a given polynomial (i.e., a0, a1, a2, a3 and a4)
coeff [0] = 1 coeff [1] = 2 coeff [2] = 3 coeff [3] = 4 coeff [4] = 5
Enter the value of x
2
f(2) = 129.00
Example 4:
Write a C program to generate Fibonacci numbers using arrays.
#include <stdio.h>
#include<conio.h>
void main()
{
int i,n,fib[10]={0,1,1};
clrscr();
printf(“Enter the number of terms to generate\n”);
scanf(“%d”, &n);
for(i=0;i<n;i++)
fib[i+3]=fib[i+2]+fib[i+1];
30
Principles of Programming using C – BPOPS203 Module 3
Example 5:
Write a C program to read N elements and find biggest element in the array.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],n,I,largest;
clrscr();
printf(“Enter the size of the array\n”);
scanf(“%d”, &size);
printf(“Enter the elements of the array\n”);
for (i=0;i<n; i++)
scanf(“%d”, &a[i]);
largest= a[0];
for(i=1;i<size;i++)
{
if(a[i]>largest)
31
Principles of Programming using C – BPOPS203 Module 3
largest=a[i];
}
printf(“The largest element in the array is %d\n”, largest);
getch();
}
Output:
Enter the size of the array
5
Enter the elements of the array
12
35
-10
-50
28
The largest element in the array is 35
Two-Dimensional Arrays
• The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.
• 2D arrays are created to implement a relational database(table) lookalike data structure.
• It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.
Initialization of 2D Arrays in C
The two-dimensional arrays can be initialized in the following way. In case of 2-D arrays the values
are initialized row wise. Assigning required values to a variable at the time of declaration before
processing is called initialization.
32
Principles of Programming using C – BPOPS203 Module 3
Example:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Col-0 Col-1 Col-2
int n[3][3]= {
{10, 10, 10}, Row-0 10 10 10
{20, 20, 20}, ----> Row-1 20 20 20
{30, 30, 30} Row-2 30 30 30
};
Limitations of Arrays:
Although arrays provide an easy way to store multiple values of the same type together, they have
certain limitations.
The size of an array that you specify at the time of creation cannot be altered later. In other words,
you cannot add more elements to an array than specified in its size.
It is very difficult to insert an element between two existing elements. If you want to insert a new
element between two existing elements, you first need to make space for the new element by
moving all the existing elements up by one index.
Shortage of Memory, if we don't know the size of memory in advance.
Wastage of Memory, if array of large size is defined.
33
Principles of Programming using C – BPOPS203 Module 3
Advantages of Array:
1. It is used to represent multiple data items of same type by using only single name.
2. It can be used to implement other data structures like linked lists, stacks, queues,trees, graphs
etc.
3. 2D arrays are used to represent matrices.
/*Write matrix */
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf(“%d”, a[i][j]);
Example 1:
34
Principles of Programming using C – BPOPS203 Module 3
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5], b[5][5], c[5][5], i,j,m,n,p,q;
clrscr();
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf(“\n Sum of Matrices\n:”);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
printf(“%d”, c[i][j]);
}
35
Example 2
Implement Matrix Multiplication and validate the rules of multiplication.
Program:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int a[5][5], b[5][5], c[5][5], m,n,p,q,i,j,k;
printf("Enter the order of matrix A(m and n):");
scanf("%d %d", &m,&n);
printf("Enter the order of matrix B(p and q):");
scanf("%d %d", &p,&q);
/* Check compatibility of two matrices*/
if(n!=p)
{
printf("Matrix multiplication is not possible…Try again");
exit(0);
}
else
/* Read matrix A*/
printf("\n Enter the elements of matrix A(m * n):\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
/* Read matrix B*/
printf("\n Enter elements of matrix B(p * q):\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d", &b[i][j]);
/* Matrix multiplication*/
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];
36
}
}
}
printf("The 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 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("The Resultant Matrix C is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t", c[i][j]);
printf("\n");
}
}
Output1:
Enter the order of matrix A(m and n): 2 4
Enter the order of matrix B(p and q): 2 2
Matrix multiplication is not possible…Try again
Output 2:
Enter the order of matrix A(m and n):2 3
Enter the order of matrix B(p and q):3 2
Enter the elements of matrix A(m * n):
1
2
3
4
5
6
37
Enter elements of matrix B(p * q):
1
2
3
4
5
6
The Matrix A is
1 2 3
4 5 6
The Matrix B is
1 2
3 4
5 6
The Resultant Matrix C is
22 28
49 64
Output 3:
Enter the order of matrix A(m and n):2 2
Enter the order of matrix B(p and q):2 2
Enter the elements of matrix A(m * n):
2
2
2
2
Enter elements of matrix B(p * q):
2
2
2
2
The Matrix A is
2 2
2 2
The Matrix B is
2 2
2 2
The Resultant Matrix C is
8 8
8 8
38
Principles of Programming using C – BPOPS203 MODULE 3
Example 3
Program to find transpose of matrix
#include<stdio.h>
void main()
{
int a [10] [10], t [10] [10];
int m,n,i,j;
printf("In Enter the order of matrix");
scanf ("'%d%d", &m, &n) ;
printf("In Enter the element of matrix one by one");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scant (“%d",&a[i][j]);
for(i=0;i‹m;i++)
for(j=0;j<n;j++)
t[[i][j]=a[j][i];
printf ("In Original Matrix In");
for(i=0;i<m;i++)
{
for (j=0; j<n; j++)
printf("%d\t", a[i][j]);
printf("\n");
printf("In Transpose Matrix In");
for(i=0:i<n:i++)
{
for(j=0;j<m;j++)
printf("%d\t",t[i][j]);
printtf ("\n");
}
}
Multi-Dimensional Arrays
C allows arrays of three or more dimensions. The exact limit is determined by compiler.
The general form of a muti-dimensional array is
data_typearray_name[s1][s2][s3]….[sm];
Where s, is the size of the ith dimension.
Some examples are: int survey[3][5][12]; float table[5][4][5][3];
Survey is a three-dimensional array declared to contain 180 integer type elements.
Table is a four-dimensional array containing 300 elements of floating-point type.
Operations on Arrays
1. Traversing an array
2. Inserting an element in an array
3. Deleting an element from 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.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, arr[20];
clrscr();
printf(“\n Enter the number of elements”);
scanf(“%d”, &n);
printf(“\n Enter the elements”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nThe array elements are”);
for(i=0;i<n;i++)
printf(“%d”,arr[i]);
}
2. Inserting an element in an array: Inserting an element in an array means adding a new data
element to an already existing array.
Program: Write a C program to insert a number at a given location in an array.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,pos,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
printf(“\nEnter the position at which the number has to be added”);
scanf(“%d”,&pos);
for(i=n-1;i>=pos;i--)
arr[i+1]=arr[i];
arr[pos]=num;
n++;
printf(“\nthe array after insertion of %d is”,num);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
Program: Write a C program to insert a number in an array that is already sorted in ascending
order.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,j,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
for(i=0;i<n;i++)
{
if(arr[i]>num)
{
for(j=n-1;j>=i;j++)
arr[j+1]=arr[j];
arr[i]=num;
break;
}
}
n++;
printf(“\nthe array after insertion of %d is”,num);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
3. Deleting an element from an array
Deleting an element from an array means removing a data element from an already existing array.
Program: Write a C program to delete a number from a given location in an array.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,pos,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nEnter the position at which the number has to be deleted”);
scanf(“%d”,&pos);
for(i=pos;i<n-1;i++)
arr[i]=arr[i+1];
n--;
printf(“\nthe array after deletion of is”);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
Program: Write a C program to delete a number from an array that is already sorted in ascending
order.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n,num,j,arr[10];
clrscr();
printf(“\n enter the number of elements in the array”);
scanf(“%d”,&n);
printf(“\nenter the values”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nenter the number to be inserted”);
scanf(“%d”,&num);
for(i=0;i<n;i++)
{
if(arr[i]==num)
{
for(j=i;j<n-1;j++)
arr[j]=arr[j+1];
}
}
n--;
printf(“\nthe array after deletion is”);
for(i=0;i<n;i++)
printf(“%d\t”,arr[i]);
getch();
}
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.
Program: Write a C program to merge two unsorted arrays.
#include <stdio.h>
#include <conio.h>
void main()
{
int i,n1,n2,m,arr1[10],arr2[10],arr3[10],index=0;
clrscr();
printf(“\n enter the number of elements in the first array”);
scanf(“%d”,&n1);
printf(“\nenter the values”);
for(i=0;i<n1;i++)
scanf(“%d”,&arr1[i]);
printf(“\n enter the number of elements in the second array”);
scanf(“%d”,&n2);
printf(“\nenter the values”);
for(i=0;i<n2;i++)
scanf(“%d”,&arr2[i]);
m=n1+n2;
for(i=0;i<n1;i++)
{
arr3[index]=arr1[i];
index++;
}
for(i=0;i<n2;i++)
{
{
arr3[index]=arr2[i];
index++;
}
printf(“\nthe array after merging is”);
for(i=0;i<m;i++)
printf(“%d\t”,arr3[i]);
getch();
}
5. SEARCHING
• 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 (sequential search)
2. Binary search
1. Linear search
• Linear search is also called sequential search and is a simple searching technique.
• In this technique the key item is searched in the 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.
Example 1:
Write C Program to implement Linear search
#include <stdio.h>
#include <conio.h>
void main()
{
int n,i,a[],key;
clrscr();
printf(“Enter the number of integers:\n”);
scanf(“%d”,&n);
printf(“Enter the %d items:\n”, n);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
printf(“Enter the key element to search:\n”);
scanf(“%d”, &key);
for(i=0;i<n;i++)
{
if(key == a[i])
{
printf(“\n Search Successful”);
exit(0);
}
}
printf(“\n Search Unsuccessful”);
getch();
}
Example 1:
/*Searching an element using Binary Search*/
#include <stdio.h>
#include<conio.h>
int main()
{
int i, n, begin, end, middle, key, pos=-1, found=0, a[20];
clrscr();
printf("Enter total number of elements in the array\n");
scanf("%d", &n);
printf("Enter elements in ascending order \n");
for (i = 0; i< n; i++)
scanf("%d", &a[i]);
printf("Enter the element to be searched\n");
scanf("%d", &key);
begin = 0;
end = n - 1;
while (begin <= end)
{
middle = (begin+end)/2;
if (a[middle] == key)
{
printf("The searched element %d is found at location %d\n", key, middle);
found=1;
break;
}
else if (a[middle] > key)
end = middle - 1;
else
}
begin = middle - 1;
if (begin > end && found==0)
printf("The searched element %d is not found in the array\n", key);
getch();
}
Output 1:
Enter total number of elements in the array
5
Enter elements in ascending order
10
20
30
40
50
Enter the element to be searched
10
The searched element 10 is found at location 1.
Output 2:
Enter total number of elements in the array
5
Enter elements in ascending order
10
20
30
40
50
Enter the element to be searched
55
The searched element 55 is not found in the array
i. Bubble Sort
• This is the simplest and easiest sorting technique.
• In this technique two successive elements of an array such as a[i] and a[i+1] are compared.
• If a[i]>=a [i+1] then 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: Write C program to input N integers in a single dimensional array and sort them in
ascending order using Bubble sort.
Program: Write C program to input N integers in a single dimensional array and sort them in
ascending order using Selection sort.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,j,t,n,min,loc;
clrscr();
printf(“Selection Sort\n”);
printf(“Enter total number of elements\n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for(i=0;i<n;i++)
scanf(“%d”, &a[i]);
for(i=0;i<=n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}
t=a[i];
a[i]=min;
a[loc]=t;
}
printf(“\n The sorted elements
are\n”); for(i=0;i<n;i++)
printf(“%d\n”, a[i]);
getch();
}
int main()
{
int ageArray[] = {2, 8, 4, 12};
b. Passing entire Array : To pass an entire array to a function, only the name of the array is passed
as an argument.