Cs3271programming in C Lab Part 1
Cs3271programming in C Lab Part 1
5. Strings: operations
7. Recursion
Pointers
and Unions.
10. Files: reading and writing, File pointers, file operations, random
access, processordirectives.
1. I/O statements, operators, expressions
EX. 1A
C PROGRAM USING INPUT STATEMENTS
DATE:
AIM:
Procedure:
The scanf() function works in much the same way as the printf(). It has the
general form
scanf(“control_string”,variable1_address, variable2_address,...);
Where the control string, also known as format string is a list of format specifiers
indicating the format and type of data to be read from the standard input device,
which is the keyboard, and stored in the corresponding address of variables.
There must be the same number of format specifiers and addresses as there are
input fields. scanf() returns the number of input fields successfully scanned,
converted, and stored.
The most obvious is that scanf() has to change the values stored in parts of the
computer‟s memory associated with variables. Store values in memory locations
associated with variables, the scanf() function should have the addresses of the
variables rather than just their values. This means that simple variables have to
be passed with a proceeding &.
There is no need to use „&‟ for strings stored in arrays because the array name
is already a pointer. This issue will be dealt with in the chapter on arrays and
strings.
Format specifiers in scanf ( )
The format string in scanf() has the following general form:
“< character string >< % conversion specifier field >”
Here character string is optional and has to be used with care. Each „conversion
specifier field‟ is coded as follows:
%[*]<width><size><conversion-code>
Each conversion (or format) specifier begins with the percent character, %, after
which come the following, in the given order.
1. An optional assignment-suppression character, *, which states that the value
being read will not be assigned to an argument, but will be dropped.
2. An optional width specifier, <width>, which designates the maximum number
of characters to be read that compose the value for the associated argument.
Encountering white space, before the entire width is scanned, terminates the
input of this value and moves to the next.
3. An optional conversion-code modifier, <size>, which modifies the conversion
code to accept format for a type of:
h = short int, l = long int, if the format specifiers provide for an integer
conversion,
l = double, if the format specifiers provide for a floating-point conversion, and
L = long double, which is valid only with floating-point conversions.
The format specifiers in scanf()
Formatted input in scanf ()
Typically, the format string for a scanf() will not contain constant text. If it does,
that means the input must contain
#include <stdio.h>
int main(void)
int a, b, c;
int num;
return 0;
Input1:
10 20 30
Output1:
I have read 3 values.
Input2:
10 20 hello
Output2:
I have read 2 values.
Input3:
hello 10 20 30
Output3:
I have read 0 values.
Add two integer numbers and print the input numbers and result.
#include <stdio.h>
int main()
{
int a,b,c;
printf(“\nThe fi rst number is ”);
scanf(“%d”,&a);
printf(“\nThe second number is ”);
scanf(“%d”,&b);
c=a+b;
printf(“The answer is %d \n”,c);
return 0;
}
Input:
The first number is 99
The second number is 100
Output:
The answer is 199
EX. 1B
C PROGRAM USING OUTPUT STATEMENTS
DATE:
AIM:
Procedure:
Formatted Output Function printf ( )
The format string in printf(), enclosed in quotation marks, has three types of
objects:
Ordinary characters: these are copied to output Conversion specifier field:
denoted by % containing the codes listed in Table and by optional modifiers such
as width, precision, flag, and size Control code: optional control characters such
as \n, \b, and \t
Aim:
#include <stdio.h>
void main()
{
int m = 12345;
long n = 987654;
printf("%d\n",m);
printf("%10d\n",m);
printf("%010d\n",m);
printf("%-10d\n",m);
printf("%10ld\n",n);
printf("%10ld\n",-n);
}
Output:
Formatted output of real numbers
Aim:
#include <stdio.h>
void main()
{
float y = 12.3456;
printf("%7.4f\n", y);
printf("%f\n", y);
printf("%7.2f\n", y);
printf("%-7.2f\n", y);
printf("%07.2f\n", y);
printf("%*.*f", 7, 2, y);
printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n", y);
printf("%e\n", y);
}
Output:
Formatted output of string
Aim:
#include <stdio.h>
void main()
{
char x = 'K';
static char name[20] = "ARAVINDA NARAYANAN";
printf("OUTPUT OF CHARACTERS\n\n");
printf("%c\n%3c\n%5c\n", x,x,x);
printf("%3c\n%c\n", x,x);
printf("\n");
printf("OUTPUT OF STRINGS\n\n");
printf("%s\n", name);
printf("%20s\n", name);
printf("%20.10s\n", name);
printf("%.5s\n", name);
printf("%-20.10s\n", name);
printf("%5s\n", name);
}
EX1C
C PROGRAM USING ARITHMETIC OPERATORS
DATE:
AIM: To Write a C program to read name and marks of Programming in C (First &
Second Internal) subject and calculate the Sum (total), Average (percentage) and
ALG ORITHM:
Step 3: Read the appropriate values (name, mark1 & mark2) using scanf.
#include <stdio.h>
void main()
{
int a,b,sum;
float avg, im;
char name[15];
printf("Enter Ur name: ");
scanf("%s",name);
printf("Enter Programming in C Unit Test 1 and 2 Marks: ");
scanf("%d\t%d",&a,&b);
sum=a+b;
avg=(float)(a+b)/2;
im = (float)(avg/100)*40; // convert from 100% to 40%
printf("\n\nName is = %s",name);
printf("\nTotal of Unit Test 1 & 2 Mark is = %d",sum);
printf("\nAverage Result is = %.2f",avg);
printf("\nConvert Average from 100%% to 40%%");
printf("\nFinal internal mark is = %.2f",im);
}
Input:
Enter Ur name: KarthkeyanP
Enter Programming in C Unit Test 1 and 2 Marks: 95 97
Output:
Name is = KarthkeyanP
Total of Unit Test 1 & 2 Mark is = 192
Average Result is = 96.00
Convert Average from 100% to 40%
Final internal mark is = 38.40
RESULT:
Thus a C Program using I/O statements and expressions was executed and
the output was obtained.
2. Decision-making constructs: if-else, goto, switch-
case, break-continue
EX 2A
LEAP YEAR CHECKING
DATE:
AIM
To write a C Program to find whether the given year is leap year or Not.
ALGORITHM
Step 1. Start the process.
Step 2. Declare the integer variables
Step 3. Read the input.
Step 4. Take a year as input and store it in the variable year.
Step 5. Using if, else statements to,
a) Check whether a given year is divisible by 400.
b) Check whether a given year is divisible by 100.
c) Check whether a given year is divisible by 4.
Step 6. If the condition at step 5.a becomes true, then print the output as “It is
a leap year”.
Step 7. If the condition at step 5.b becomes true, “It is not a leap year”.
Step 8. If the condition at step 5.c becomes true, “It is a leap year”.
Step 9. If neither of the condition becomes true, then the year is not a leap year
and prints the same.
Step 10. Display the output of the calculations.
Step 11. Stop the process.
#include <stdio.h>
void main()
int year;
scanf("%d",&year);
else
}
Input1:
Enter the Year (YYYY) : 2060
Output1:
The Given year 2060 is a Leap Year
Input2:
Enter the Year (YYYY) : 2099
Output2:
The Given year 2099 is Not a Leap Year
RESULT
Thus a C Program for Leap year checking was executed and the output was
obtained.
EX 2B
DESIGN A SIMPLE CALCULATOR
DATE:
AIM
To write a C Program to Design a calculator to perform the operations, namely,
addition, subtraction, multiplication and division.
ALGORITHM
Step 1. Start the process.
Step 2. Declare the variables
Step 3. Read the option.
Step 4.Using Decision making and branching statement (switch)
Step 5. Calculate Arithmetic operations (+,-,*,/) for the input of two numbers.
Step 6. Display the output of the calculations.
Step 7. Stop the process.
#include <stdio.h>
int main()
{
char opt;
int n1, n2;
float res;
printf (" Choose an operator(+, -, *, /) \n ");
scanf ("%c", &opt);
if (opt == '/' )
{
printf (" You have selected: Division");
}
else if (opt == '*')
{
printf (" You have selected: Multiplication");
}
switch(opt)
{
case '+':
res = n1 + n2;
printf (" Addition of %d and %d is: %.2f", n1, n2, res);
break;
case '-':
res = n1 - n2;
printf (" Subtraction of %d and %d is: %.2f", n1, n2, res);
break;
case '*':
res = n1 * n2;
printf (" Multiplication of %d and %d is: %.2f", n1, n2, res);
break;
case '/':
if (n2 == 0) // if n2 == 0, take another number
{
printf (" \n Divisor cannot be zero.Enter another value ");
scanf ("%d", &n2);
}
res = n1 / n2;
printf (" Division of %d and %d is: %.2f", n1, n2, res);
break;
default:
printf (" Something is wrong!! Please check the options ");
}
return 0;
}
Input1:
Choose an operator(+, -, *, /)
+
Output1:
Input2:
Choose an operator(+, -, *, /)
-
Output2:
You have selected: Subtraction
Enter the first number: 10
Enter the second number: 5
Subtraction of 10 and 5 is: 5.00
Input3:
Choose an operator(+, -, *, /)
*
Output3:
You have selected: Multiplication
Enter the first number: 10
Enter the second number: 10
Multiplication of 10 and 10 is: 100.00
Input4:
Choose an operator(+, -, *, /)
/
Output4:
You have selected: Division
Enter the first number: 10
Enter the second number: 10
Division of 10 and 10 is: 1.00
RESULT
Thus the C Program to perform the Calculator operations, namely, addition,
subtraction, multiplication and division has been executed and results are
verified.
EX 2C
C PROGRAM TO FIND THE ROOTS OF A QUADRATIC
EQUATION.
DATE:
AIM:
To find the roots of a quadratic equation.
ALGORITHM:
Step 1: Start the process
Step 2: Read a,b,c
Step 3: calculate disc = b*b-4*a*c //disc=discriminant
The term b2 - 4ac is known as the discriminant of a quadratic equation. It tells
the nature of the roots.
Step 4: if(disc>0)
Begin
Step 5: root1=(-b+sqrt(disc))/(2*a)
Step 6: root2=(-b-sqrt(disc))/(2*a)
Step 7: Print “Root1” , “Root2”
End
If the discriminant is greater than 0, the roots are real and different.
discriminant = b * b - 4 * a * c;
return 0;
}
Inpu1t:
Enter coefficients a, b and c: 1 4 4
Output1:
root1 = root2 = -2.00;
Input2:
Enter coefficients a, b and c: 1 2 3
Output2:
root1 = -1.00+1.41i and root2 = -1.00-1.41i
RESULT:
Thus the C Program to find the roots of a quadratic equation has been executed and the result was
verified.
EX 2D
MULTIPLICATION TABLE USING goto STATEMENT
DATE:
Aim:
To write a C Program for Multiplication Table using goto Statement.
ALGORITHM
Step 1. Start the process.
Step 2. Declare the variables.
Step 3. Read the number whose table you want to print?
Step 4.Using goto statement and go to the label name is table
Step 5. Calculate num*I and print the result.
Step 6. Then „i‟ value Increment by 1
Step 7. Check the test condition(i<=10), if it is true goto table otherwise exit.
Step 8. Stop the process.
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
Input:
Enter the number whose table you want to print? 5
Output:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
RESULT:
Thus the C Program for Multiplication Table using goto Statement using goto
statement has been verified and executed successfully.
3. Loops: for, while, do-while
EX 3A
CHECK WHETHER A GIVEN NUMBER IS ARMSTRONG
DATE: NUMBER OR NOT
AIM
To write a C Program to Check whether a given number is Armstrong number
or not.
ALGORITHM
#include <stdio.h>
#include <math.h>
void main()
{
int n, sum = 0, rem = 0, cube = 0, temp;
Output1:
The given number is an Armstrong number
Input2:
Enter a number: 123
Output2:
The given number is not an Armstrong number
RESULT:
Thus a C Program for Armstrong number checking was executed
and the output was obtained
EX 3B
AVERAGE HEIGHTS OF PERSONS
DATE:
AIM
To write a C Program to populate an array with height of persons and find how
many persons are above the average height.
ALGORITHM
Step 1. Start the process.
Step 2. Declare the variables.
Step 3. Read the total number of persons and their height.
Step 4. Calculate avg=sum/n and find number of persons their h>avg.
Step 5. Display the output of the calculations.
Step 6. Stop the process.
#include <stdio.h>
void main()
{
int i, n, sum=0,count=0,height[100];
float avg;
printf("Enter the Number of Persons : ");
scanf("%d", &n);
printf("\n Enter the Height of each person in centimetre\n");
for(i=0;i<n;i++)
{
scanf("%d", &height[i]);
sum = sum + height[i];
}
avg = (float)sum/n;
for(i=0;i<n;i++)
if(height[i]>avg)
count++;
printf("\n Average Height of %d persons is : %.2f\n", n, avg);
printf("\n The number of persons above average : %d ",count);
}
Input:
Enter the Number of Persons : 5
Enter the Height of each person in centimeter
159
169
179
166
177
Output:
Average Height of 5 persons is : 170.00
The number of persons above average : 2
RESULT
Thus a C Program average height of persons was executed and the output was
obtained.
EX 3C
C PROGRAM TO PRINT THE FACTORIAL OF A GIVEN
NUMBER.
DATE:
AIM
To write a C Program to print the factorial of a given number.
ALGORITHM
Step 1: Start the process.
Step 2: Declare the variables and its resultant values.
Step 3: Read the number.
Step 4: Using do … while() loop and find factorial of given number.
Step 5: fact = fact * i and increment „i‟ value.
Step 6: Continue step 5 until while condition false.
Step 7: Finally print the result.
Step 8: Stop the process.
#include<stdio.h>
void main()
{
int n,i=1,f=1;
printf("\n Enter The Number:");
scanf("%d",&n);
do
{
f=f*i;
i++;
}while(i<=n);
printf("\n The Factorial of %d is %d",n,f);
}
Input:
Enter The Number:5
Output:
The Factorial of 5 is 120
RESULT:
Thus a C Program for find the factorial of a given number was
executed and the output was obtained
4. Arrays: 1D and 2D, Multi-dimensional arrays, traversal
EX 4A
C program to accept N numbers and arrange them in an
ascending order
DATE:
Aim:
To write a C program to accept N numbers and arrange them in an ascending
order
Algorithm:
Step 1: Start the process
Step 2: Declare an array of some fixed capacity, ex. 30.
Step 3: From users, take a number N as input, which will indicate the number of
elements in the array (N <= maximum capacity)
Step 4: Iterating through for loops (from [0 to N) ), take integers as input from
user and print them. These inputs are the elements of the array.
Step 5: Now, create a nested for loop with i and j as iterators.
Step 6: Start the sorting in ascending order by extracting each element at
position i of outer loop.
Step 7: This element is being compared to every element from position i+1 to
size-1 (means all elements present below this extracted element)
Step 8: In case any of the extracted element is greater than the element below
it, then these two interchange their position, else the loop continues.
Step 9: After this nested loop gets executed, we get all the elements of the
array sorted in ascending order.
Step 10: Stop the process
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
a = number[i];
number[i] = number[j];
number[j] = a;
}
Input:
Enter the value of N
6
Output:
The numbers arranged in ascending order are given below
3
78
90
200
456
780
Result:
Aim:
To write a C program to Count and display of positive, negative, odd and even
numbers in an array
Algorithm:
Step 1: Start the process
Step 2: Declare and read variables n, i
Step 3: Read elements into an array
Step 4: If(a[i] > 0) then display number is positive
Step 5: If(a[i]%2==0) then display number is even
Step 6: If(a[i] < 0) then display number is negative
Step 7: If(a[i]%2!=0) then display number is odd
Step 8: Stop the process
#include<stdio.h>
void main()
{
int a[10],i,o=0,p=0,e=0,n=0;
printf(" enter 10 nos\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
if(a[i]%2==0)
{
e++;
}
else
{
o++;
}
if(a[i]>=0)
{
p++;
}
else
{
n++;
}
}
printf("\n Even nos.=%d",e);
printf("\n Odd nos.=%d",o);
printf("\n +ve nos.=%d",p);
printf("\n -ve nos.=%d",n);
}
Input:
enter 10 nos
10
-10
9
-9
7
-7
3
-3
20
-20
Output:
Even nos.=4
Odd nos.=6
+ve nos.=5
-ve nos.=5
Result:
The C program is successfully compiled and executed successfully.
EX 4C
MULTIPLICATION OF TWO MATRICS
DATE:
Aim:
To write a C program to Multiplication of two matrices.
Algorithm:
Step 1: Start the process
Step 2: Read the no. of rows (r1) and cols (c1) of a matrix a[3][3].
Step 3: Read the no. of rows (r2) and cols. (c2) of matrix b[3][3].
Step 4: If c1=r2 then display matrix multiplication is possible otherwise display
impossible
Step 5: If c1=r2 then read the elements into both the matrices a and b.
Step 6: Initialize a resultant matrix c[3][3] with 0.
Step 7: Calculate c[i][j] = c[i][j] + a[i][k] * b[k][j].
Step 8: Display the resultant matrix
Step 9: Stop the process
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf(" enter row & column of Mat1\n");
scanf("%d%d",&m,&n);
printf(" enter row & column of Mat2\n");
scanf("%d%d",&p,&q);
if(n==p)
{
printf(" enter Mat1\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf(" enter Mat2\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
printf(" \n multiplied matrix\n");
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("%8d",c[i][j]);
} printf("\n");
}
}
else
printf(" \n multiplication is not possible...");
}
Input:
enter row & column of Mat1
3 3
enter row & column of Mat2
3 3
enter Mat1
1 2 3 4 5 6 7 8 9
enter Mat2
1 2 3 4 5 6 7 8 9
Output:
multiplied matrix
30 36 42
66 81 96
102 126 150
Result:
The C program is successfully compiled and executed successfully.
5. Strings: operations
EX 5A
Reverse of a given string
DATE:
AIM
To write a C Program to perform reverse without changing the position of special
characters for the given string.
ALGORITHM
Step 1. Start the process.
Step 2. Declare the variables.
Step 3. Read a String.
Step 4. Check each character of string for alphabets or a special character by
using is Alpha ().
Step 5. Change the position of a character vice versa if it is alphabet otherwise
remains same.
Step 6. Repeat step 4 until reach to the mid of the position of a string.
Step 7. Display the output of the reverse string without changing the position of
special characters.
Step 8. Stop the process.
Given a string a@cd%ef#;ghi&j*k; find its reverse without changing the
position of special characters. (Example input:a@gh%;j and output:j@hg%;a)
PROGRAM
#include <stdio.h>
#include <string.h>
#include <conio.h>
void swap(char *a, char *b)
{
char t; t = *a;
*a = *b;
*b = t;
}
void main()
{
char str[100];
void reverse(char *);
int isAlpha(char);
void swap(char *a ,char *b);
clrscr();
printf("Enter the Given String : ");
gets(str);
reverse(str);
printf("Reverse String : %s",str);
getch();
}
void reverse(char str[100])
{
// Initialize left and right pointers
int r = strlen(str) - 1, l = 0;
while (l < r)
{
// Ignore special characters
if (!isAlpha(str[l]))
l++;
else if(!isAlpha(str[r])) r--;
else
{
swap(&str[l], &str[r]); l++;
r--;
}
}
}
int isAlpha(char x)
{
return ( (x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z') );
}
Input:
Output:
RESULT
Thus a C Program for reverse of a given String was executed and the output was
obtained.
EX 5B
Count of each character in the string
DATE:
Aim:
To Count of each character in the given string
Algorithm:
Step 1: Start the process
Step 2: Take a string and a character as input.
Step 3: Using for loop search for the input character.
Step 4: When the character is found, then print its corresponding position.
Step 5: Again keep on searching for the input character. Now keep on
incrementing a variable whenever the input character encounters.
Step 6: Do step-5 until the end of string. when it is done, print the value
of the variable.
Step 7: Stop the process
Count of each character in the string
#include<stdio.h>
#include<string.h>
Output:
The count of each character in the string Aravindanarayanan is
A 1
r 2
a 6
v 1
i 1
n 4
d 1
y 1
Result:
Thus the C Program to find the frequency of a character in a string has been
executed and verified.
EX 5C
Check given string is palindrome or not
DATE:
Aim:
Algorithm
Output1:
liril - PALINDROME
Input21:
Enter a string :Karthi
Output2:
Karthi - NOT PALINDROME
Result:
Aim:
To write a c program to swap two numbers using call by value
Algorithm:
Step 1: Start the process
Step 2: Take two numbers as input and store it in the variables num1 and num2
respectively.
Step 3: Call the function swap and pass the variables num1 and num2 as
parameters to the function swap.
Step 4: In function swap, recieve the parameters through variables a and b
respectively.
Step 5: Copy the value of variable a to the variable temp. Copy the value of
variable b to the variable a and copy the value of variable temp to the
variable. This will do the swapping ONLY in the swap() function, but it
will NOT change the value of variables in the main() function.
Step 6: Print the variables num1 and num2 in the main function as output and
exit.
Step 7: Stop the process
#include <stdio.h>
int main()
{
int num1, num2;
Printf(“Enter any two integer numbers : “);
scanf(“%d%d”, num1,num2);
Output:
Before swapping num1 =10 num2 = 20
Result:
Thus the above program is successfully compiled and tested using Turbo C
compiler.
EX 6B
Simple C program illustrates pass by reference
DATE:
Aim:
To write a C program illustrates pass by reference.
Algorithm:
int main()
{
int num;
Printf(“Enter any integer number : “);
scanf(“%d”, num);
cube(&num);
printf("The cube of the given number is %d", num);
return 0;
}
Output:
The cube of the given number is 1000
Result:
Thus the above program is successfully compiled and tested using Turbo C
compiler.
EX 6c
Square of Array Elements by passing arrays to function
DATE:
Aim:
To write a C Program to Print the Square of Array Elements by passing arrays to
function
Algorithm:
void print_square(int [ ] );
void main (void)
{
int i;
int num [MAX_ROWS][MAX_COLS] = { {1, 2, 3}, {4, 5, 6} };
for (i = 0; i < MAX_ROWS; i++)
print_square(num[i]);
}
void print_square(int x[ ])
{
int j;
for (j = 0; j < MAX_COLS; j++)
printf ("%d\t", x[j] * x[j]);
printf("\n");
}
Input:
Define all its elements at the time of declaration. {1, 2, 3}, {4, 5, 6}
Output:
1 4 9
16 25 36
Result:
Thus the above program is successfully compiled and tested using Turbo C
compiler in windows environment.
7. Recursion
EX 7A
Find the factorial of a given number using recursion
DATE:
Aim:
To write a C Program to find the factorial of a given number using
recursion
Algorithm:
Step 1: Start the process
Step 2: Read number n
Step 3: Call factorial(n) function
Step 4: If n==1 then return 1
Step 5: Else f=n*factorial(n-1)
calling the same function itself until a base condition is satisfied
Step 6: finally return f
Step 7: Print the factorial f
Step 8: Stop the process
#include<stdio.h>
void main( )
{
int factorial(int);
int n,f;
printf("Enter the number: ");
scanf("%d",&n);
f=factorial(n);
printf("Factorial of the number is %d",f);
}
int factorial(int n)
{
int f;
if(n==1)
return 1;
else
f=n*factorial(n-1);
return f;
}
Input:
Enter the number: 5
Output:
Factorial of the number is 120
Result:
Thus the above program is successfully compiled and tested using Turbo C
compiler in windows environment.
EX 7B
Binary Search using Recursion
DATE:
Aim:
To write a C Program to Perform Binary Search using Recursion
Procedure :
Step 1: Start the process
Step 2: A Binary Search is a quick and efficient method of finding a specific
target value from a set of ordered items. A Binary Search, also known
as a half-interval search.
The basic idea behind Binary Search is that the array in which it is
applied upon should be sorted. It divides the whole array into two
halves and proceeds to look for the key in suitable part of divided
array.
Step 3: In Binary Search the key value which is to be searched is compared to
the middle element of the array. If the key value is less than or greater
than this middle element, the algorithm knows which half of the array
to continue searching in because the array is sorted.
Step 4: This process is repeated until we discover the element. In each step this
algorithm divides the array size by half and the Binary search will be
successful if it is able to locate the element in array, but if it cannot find
the element in array it simply returns -1 or prints “Key not Found”.
Step 6: Stop the process
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int key, size, i;
int list[25];
Output1:
Key found
Input2:
Output2:
Key not found
Result:
The program is successfully compiled and tested using Turbo C compiler on Windows
10.