Model2 & 3 Notes
Model2 & 3 Notes
MODULE-2
MANAGING INPUT AND OUTPUT, BRANCHING AND
LOOPING
In programming input mean reading data from the input device or a file and Output means
displaying the results on the screen. C provides a number of input and output functions. These
functions are predefined in the respective header files. The input and output functions are
used in the program whose functionality are predefined in the header file
“#include<stdio.h>”
Example: if we want to store the values 50 and 31from the keyboard in variables num1 and
num2 then the input function is read as
scanf(“%d%d”,&num1,&num2);
the value 50 will be assigned to num1 and value 31 will be assigned to num2
printf( ): In C programming language, printf() function is used to print the “character, string,
float, integer, octal and hexadecimal values” onto the output screen. The features of printf()
can be effectively exploited to control the alignment and spacing of printouts on terminals.
Syntax:
printf(“Text Message”);
OR
printf(“format specifier”,variablelist);
where:
format specifier indicates the type of data to be displayed
variable list indicates the value present in the variable.
the number of format specifier must match the number of variables in the variablelist.
Example: if we want to display the values stored in variables num1 and num2 then the printf
statement can be written as
printf(“The Value of num1 = %d and The value of num2 = %d\n”,num1,num2);
This statement will display the values stored in the respective variables. The output will be
of the form:
The Value of num1 = 50 and The value of num2 = 31
#include<stdio.h>
void main()
{
int a,b,sum;
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
§
printf(“ Addition of two Numbers=%d\n”,sum);
}
getch(): is used to read a character from the keyboard, the character entered is not displayed
or echoed on the screen the functions don’t need a return key pressed to terminate the reading
of a character. A character entered will itself terminates reading
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getch();
printf(“The entered character is %c\n”,ch);
}
getche(): is used to read a character from the keyboard, the character entered is echoed or
displayed on the screen. the functions don’t need a return key pressed to terminate the
reading of a character. A character entered will itself terminates reading.
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getche();
printf(“The entered character is %c\n”,ch);
}
getchar(): will reads a character from the keyboard and copy it into memory area which is
identified by the variable ch. No arguments are required for this macro. Once the character is
entered from the keyboard, the user has to press Enter key.
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getchar();
printf(“The entered character is %c\n”,ch);
}
putch() and putchar(): This function outputs a character stored in the memory, on the
standard output device.. The variable should be passed as parameter to the functions
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getchar();
printf(“The entered character is \n”);
putchar(ch);
}
(i) simple if: This is a one way selection statement which helps the programmer to execute or
skip certain block of statements based on the particular condition.
Syntax:
if(conditional_expression)
{
True block statements;
}
Flowchart:
#include<stdio.h>
void main()
{
int age;
printf(“ Enter the age of the person\n”);
scanf(“%d”,&age);
if(age>=18)
{
printf(“The person is eligible to vote\n”);
}
if(age<18)
{
printf(“The person is not eligible to vote\n”);
}
}
(ii) if-else statement: This is a two way selection statement which executes true block or
false block of statements based on the given condition. The keyword “else” is used to shift
the control when the condition is evaluated to false.
Syntax:
if(conditional_expression)
{
True block statements;
}
else
{
False block statements;
}
#include<stdio.h>
void main()
{
int num;
printf(“Enter a number\n”);
scanf(“%d”,&num);
if(num%2==0)
{
printf(“%d is a even number\n”,num);
}
else
{
printf(“%d is a odd number\n”,num);
}
}
Flow chart:
Syntax:
if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition n)
statement n;
else
default statement;
statement X;
Flowchart:
Example: /* C program to display the grade of the student based on the average marks
obtained */
#include<stdio.h>
void main()
{
float avg;
printf(“Enter the Average marks\n”);
scanf(“%f”,&avg);
if(avg>=80)
printf(“Distinction\n”);
else if(avg>=60)
printf(“First Division\n”);
else if(avg>=50)
printf(“Second Division\n”);
else if(avg>=40)
printf(“Third Division\n”);
else
printf(“Fail\n”);
}
(v)Switch Statement: A switch statement tests the value of a variable and compares it with
multiple cases. Once the case match is found, a block of statements associated with that
particular case is executed. Each case in a block of a switch has a different name/number
which is referred to as an identifier. The value provided by the user is compared with all the
cases inside the switch block until the match is found. If a case match is not found, then the
default statement is executed, and the control goes out of the switch block. The break
statement is used at the end of each case to come out of the switch block.
Syntax:
switch( expression )
{
case value-1: Statement-1;
break;
case value-2: Statement-2;
break;
case value-3: Statement-3;
break;
Flowchart:
Flow chart:
(ii) do-while loop : A do-while loop is similar to the while loop except that the condition is
always executed after the body of a loop. It is also called an exit-controlled loop. The body is
executed if and only if the condition is true. In some cases, we have to execute a body of the
loop at least once even if the condition is false. This type of operation can be achieved by
using a do-while loop. In the do-while loop, the body of a loop is always executed at least
once. After
the body is executed, then it checks the condition. If the condition is true, then it will again
execute the body of a loop otherwise control is transferred out of the loop. Similar to the
while loop, once the control goes out of the loop the statements which are immediately after
the loop is executed.
Syntax:
initialization;
do
{
set of statements to be executed
including increment/decrement opetator
}while(test condition);
Flowchart:
(iii) for loop : A for loop is a more efficient loop structure in 'C' programming which is used
when the loop has to be traversed for a fixed number of times. The for loop basically works
on three major aspects (i) The initial value of the for loop is performed only once. (ii) The
condition is a Boolean expression that tests and compares the counter to a fixed value after
each iteration, stopping the for loop when false is returned. (iii) The incrementation
/decrementation increases (or decreases) the counter by a set value.
Syntax:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
Flowchart:
Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
statement of inner loop
}
statement of outer loop
}
Flowchart:
Example: C program to print the following pattern
*
* *
* * *
* * * *
#include <stdio.h>
void main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf(“ * ”);
}
printf("\n");
}
}
#include <stdio.h>
void main()
{
int i, j, n=1;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t",n);
n++;
}
printf("\n");
}
}
Programming examples on Looping constructs:
2. Write a C program to print even numbers in the range of 1 to10 using while loop.
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
if(i%2==0)
printf(“%d\t”,i);
i=i+1;
}
}
3. Write a C program to print sum of first n natural numbers using do-while loop
#include<stdio.h>
void main()
{
int n,i sum;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
sum=0;
do
{
sum=sum+i;
i++;
}while(i<=n);
printf(“Sum of natural numbers=%d\n”,sum);
}
5. Write a C program to print sum of first n natural numbers using for loop
#include<stdio.h>
void main()
{
int n,i sum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum of natural numbers=%d\n”,sum);
}
6. Write a C program to print sum of all odd numbers and even numbers up to a
given range n using for loop
#include<stdio.h>
void main()
{
int n,i,osum=0,esum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
esum=esum+i;
else
osum=osum+i;
}
printf(“The sum of even numbers=%d\n”,esum);
printf(“The sum of odd numbers=%d\n”,osum);
}
#include <stdio.h>
void main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf(“ %d ”,j);
}
printf("\n");
}
}
(i) break Statement: A break statement terminates the execution of the loop and the control
is transferred to the statement immediately following the loop. i.e., the break statement is
used to terminate loops or to exit from a switch.
Syntax :
Jump-statement;
break;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
i++;
if(i==3)
break;
printf(“%d\t”,i);
}
}
OUTPUT:
1 2
(ii) continue statement: The continue statement is used to bypass the remainder of the
current pass through a loop. The loop does not terminate when a continue statement is
encountered. Instead, the remaining loop statements are skipped and the computation
proceeds directly to
the next pass through the loop. It is simply written as “continue”. The continue statement tells
the compiler “Skip the following Statements and continue with the next Iteration”.
Syntax :
Jump-
statement;
Continue;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
i++;
if(i==3)
continue;
printf(“%d\t”,i);
}
}
OUTPUT:
1 2 4 5
(iii)goto statement : C supports the “goto” statement to branch unconditionally from one
point to another in the program. Although it may not be essential to use the “goto” statement
in a highly structured language like “C”, there may be occasions when the use of goto is
necessary. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid variable name and must be followed by a colon (: ). The label is
placed immediately before the statement where the control is to be transferred. The label can
be anywhere in the program either before or after the goto label statement.
Example:
Program without using goto Program using goto
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
printf(“MITE \t”); printf(“MITE \t”);
printf(“is \t in\t”); goto label1;
printf(“Moodbidri\n”); printf(“is \t in\t”);
} label1: printf(“Moodbidri\n”);
OUTPUT }
MITE is in Moodbidri OUTPUT
MITE Moodbidri
Write a C Program to check if the entered number is positive Negative or Zero using
goto statement.
#include<stdio.h>
#include<stdlib.h
> void main()
{
int num;
printf(“Enter the number\n”);
scanf(“%d”,&num);
if(num==0)
goto zero;
else if(num>0)
goto pos;
else
goto neg;
zero: printf(“The entered number is Zero\n”);
exit(0);
pos: printf(“The entered number is Positive\n”);
exit(0);
neg: printf(“The entered number is Negative\n”);
exit(0);
}
return statement: The return statement terminates the execution of a function and returns
control to the calling function. Execution resumes in the calling function at the point
immediately following the call. A return statement can also return a value to the calling
function.
Syntax :
Jump-statement:
return expression;
Given the equation ax2 + bx + c = 0, substitute the values of the coefficients a,b,c in the
discriminant b2-4ac
−𝑏
Outcome1: if the value of b2-4ac is equal to zero then we say the “Roots are Real and Equal”
The formula to calculate the real and equal root is 𝑥 =
2𝑎
Outcome2: if the value of b2-4ac is grater than zero i.e if the discriminant value is positive
we say the “Roots are real and distinct” the formula to calculate real and distinct roots are
𝑥 = 2−4𝑎𝑐
−𝑏±√𝑏 2
𝑎
Outcome3: if the value of b2-4ac is lesser than zero i.e if the discriminant value is negative
we say that the “ Roots are imaginary ” the formula to calculate imaginary roots are
𝑥 = 2−4𝑎𝑐
−𝑏±𝑖√𝑏 2
𝑎
Develop a program to compute the roots of a quadratic equation by accepting the
coefficients. Print appropriate messages
#include<stdio.h>
#include<stdlib.h
>
#include<math.h>
void main()
{
float a,b,c,x1,x2,disc;
printf("Enter the values of a,b,c\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("Invalid Input\n");
exit(0);
}
disc=b*b-4*a*c;
if(disc>0)
{
printf("Roots are Real and Distinct\
n"); x1=((-b)+sqrt(disc))/(2*a);
x2=((-b)-sqrt(disc))/(2*a);
printf("Root1= %f\n Root2= %f\n",x1,x2);
}
else if(disc==0)
{
printf("Roots are Real and Equal\n
"); x1=(-b)/(2*a);
printf("Root1=Root2=%f\n",x1);
}
else
{
printf("Roots are Imaginary\n");
x1=(-b)/(2*a);
x2=(sqrt(fabs(disc)))/(2*a);
printf("Root1= %f +i %f\
n",x1,x2); printf("Root2= %f -i
} %f\n",x1,x2);
}
Table of Binomial Coefficients:
Problem Statement :-The Binomial coefficients are used in the study of binomial
𝑚 𝑚!
distribution and reliability of multi component redundant system. It is given by
𝐵(𝑚, 𝑥) = ( ) = ,𝑚 ≥𝑥
𝑥 𝑥! ( 𝑚 − 𝑥 ) !
A binomial Coefficient table is required to determine the binomial coefficient of any set of m
and x
Analysis :- The binomial coefficient can be recursively calculated as follows
B(m,0) = 1
Further, B(0,0) = 1
i.e. The binomial coefficient is 1 when either x is 0 or m is 0
mx 0 1 2 3 4 5 6 7 8 9 10
0 1
1 1 1
2 1 2 1
3 1 3 3 1
4 1 4 6 4 1
5 1 5 10 10 5 1
6 1 6 15 20 15 6 1
7 1 7 21 35 35 21 7 1
8 1 8 28 56 70 56 28 8 1
9 1 9 36 84 126 126 84 36 9 1
10 1 10 45 120 210 252 210 120 45 10 1
DepartmentofComputerScience&Engineering 1
DepartmentofComputerScience&Engineering 2
MODULE-3
WhyArrays?
#include<stdio.h>vo
id main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
number1=10;
number2=20;
number3=30;
number4=40;
number5=50;
printf("number1:%d\n",number1);
printf("number2:%d\n",number2);
printf("number3:%d\n",number3);
printf("number4:%d\n",number4);
printf( "number5: %d ", number5);
}
It was simple, because we had to store just 5 integer numbers. Now let's assume we have to
store 5000 integer numbers, so what is next???
Tohandlesuchsituation,Clanguageprovidesaconcept calledtheARRAY
Exampleswherearrayscanbeusedare
DepartmentofComputerScience&Engineering 3
elements are stored sequentially one after the other in memory.
Anyelementcan beaccessedby using
DepartmentofComputerScience&Engineering 4
→nameofthe array
→positionofelementinthearray (index)
Typesofarray
SingleDimensionalArray:-AnArraywhichhasonlyonesubscriptisknownasSingle dimensional
array or One dimensional array
The individual array elements are processed by using a common array name withdifferent
index values that start with Zero and ends witharray_size-1
SyntaxofDeclaringSingleDimensional Arrays
data_typearray_name[array_size];
where
data_type:canbeint,floatorchar array_name:is
array_size:anintegerconstantindicatingthemaximumnumberofdataelementstobestored.
HereaisanIntegerArraythatcanholdupto5valuesinit. Array
Representation
DepartmentofComputerScience&Engineering 5
Here
a[0]holdsthefirstelementinthearray
and so on..
Memoryoccupiedby1Darray
Totalmemory=arraysize*sizeofdatatype For
example :int a[5];
Totalmemory=5*sizeof(int)
=5*2
=10bytes.
StoringValuesinArrays
Thevaluescanbestoredinarrayusingfollowingmethods:
Staticinitialization
Initializationof arrayelementsonebyone.
Partialinitialization ofarray
Arrayinitialization without specifyingthesize
RunTimearrayInitialization
1. Static initialization:- We can initialize the array in the same way as the ordinary
valueswhen they are declared.
Thegeneralsyntaxofinitialization ofarrayis
Example:
intb[4]={10,12,14,16};
DepartmentofComputerScience&Engineering 6
[Link] locationb[0]westorethe value10, in locationb[1] westorethevalue12and soon…
Supposeifwetrytoinsertmorevaluesthenthesizeofthearrayitwillgiveusanerror“Excess elements
in array initializer”
Example:
intb[4]={10,12,14,16,18};
2. Initialization of array elements one by one:- Here the user has the liberty to select
[Link]
Example
intb[4];
b[0]=10;
b[2]=14;
Onlythearraylocationsspecifiedbytheuserwillcontainthevalueswhichtheuserwantsthe other
locations of array will either be 0 or some garbage value.
DepartmentofComputerScience&Engineering 7
3. Partial initialization ofarray :- Ifthenumberof valuesinitialized in thearray is less than the
size of the array then it is called partial initialization. The remaining locations in the array
will be initialized to zero or NULL(‘\0’) value automatically
Example:
int b[4]={10,12};
4. Arrayinitializationwithoutspecifyingthesize:-Herethesizeorthearrayisnotspecified by the
user, the compiler will decide the size based on the number of values declared in the array.
Example:
intb[]={6,12,18};
Here the size of the array is specified and the compiler will set the array size as 3 for this
example
5. RunTimearrayInitialization:-Ifthevaluesarenotknownbytheprogrammerinadvance then
the user makes use of run time initialization. It helps the programmer to read unknown values
from the end users of the program from keyboard by using input function scanf().
Herewemakeuseofaloopingconstructtoreadtheinputvalues fromthekeyboard andstore them
sequentially in the array.
DepartmentofComputerScience&Engineering 8
Example:/*Cprogramtodemonstraterun timeinitialization*/
#include<stdio.h>vo
id main()
{
intb[5],i;
printf(“Enter5elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&b[i]);
}
}
Accessingarrayelements:
We can access the elements of array using index or subscript of element. An index gives the
portion of element in the array .To access an array element make use of array_name[index]
Toaccessvalue16wewriteb[2]=16similarlyifwewishtoprintthevalue18wewrite
printf(“%d”,b[3]);
Programmingexamplesononedimensional array:
#include<stdio.h>vo
id main()
{
int a[20],n,i;
printf(“Enterthearraysize”);
scanf(“%d”,&n);
Printf(“Enterthearrayelements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Theelementsenteredinthearrayare\n”);
for(i=0;i<n;i++)
DepartmentofComputerScience&Engineering 9
{
printf(“%d\t”,a[i]);
}
}
2. Writeacprogramtodisplayfirstnnaturalnumbersin an array.
#include<stdio.h>vo
id main()
{
int a[20],n,i;
printf(“Enterthenumberofelements\n”);
scanf(“%d”,&n);
printf(“Thefirst%dnaturalnumbersare:\n”,n);
for(i=0;i<n;i++)
{
a[i]=i+1; printf("a[%d]=%d\
n",i,a[i]);
}
}
include<stdio.h>voi
d main()
{
inta[20],b[20],c[20],n,i;
printf(“Enterthenumberofelements\n”);
scanf(“%d”,&n);
printf(“EntertheelementsofArrayA\n”); for(i=0;i<n;i+
+)
scanf(“%d”,&a[i]);
printf(“EntertheelementsofArrayB\n”); for(i=0;i<n;i+
+)
scanf(“%d”,&b[i]);
printf(“ArrayAddition\n”);
for(i=0;i<n;i++)
c[i]=a[i]+b[i];
printf(“Theresultantarrayis\n”);
for(i=0;i<n;i++)
printf(“%d\n”,c[i]);
}
DepartmentofComputerScience&Engineering 10
4. WriteCprogram tofindlargestandsmallestnumberinanarrayofn elements
include<stdio.h>voi
d main()
{
inta[10],n,i,max,min
printf(“Enterthenumberofelements\n”);
scanf(“%d”,&n);
printf(“Enterthevalues\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
max=min=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf(“Largest number=%d\n”,max);
printf(“Smallestnumber=%d\n”,min);
}
5. WriteaCprogramtoreadnintegerelementsinanarrayandprintthesamein reverse
order.
#include<stdio.h>vo
id main()
{
int a[20],n,i;
printf(“Enterthearraysize”);
scanf(“%d”,&n);
Printf(“Enterthearrayelements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Theelementsenteredinthearrayare\n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
printf(“Theelementsofthearrayinreverseorderare\n”);
for(i=n-1;i>=0;i--)
printf(“%d\t”,a[i]);
}
DepartmentofComputerScience&Engineering 11
6. Write a C Program to find the sum of odd, even, all and average of n numbers using
arrays
#include<stdio.h>vo
id main()
{
inta[20],sum=0,esum=0,osum=0,n,i;
float avg;
printf(“Enterthearraysize”);
scanf(“%d”,&n);
printf(“Enterthearrayelements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
if((a[i]%2)==0)
esum=esum+a[i];
else
osum=osum+a[i];
}
avg=sum/n;
printf(“The sum of all numbers is %d”,sum);
printf(“Thesumofevennumbersis%d”,esum);
printf(“The sum of odd numbers is %d”,osum);
printf(“The average of all numbers is %f”,avg);
}
#include<stdio.h>
#include<conio.h>
void main()
{
intfib[20],n,i;
printf(“[Link]\n”); scanf("%d",&n);
fib[0]=0;
fib[1]=1;
if(n==1)
printf(“fibonacciseriesis%d”,fib[0]);
else if(n==2)
printf(“fibonacciseriesis%d\t%d”,fib[0],fib[1]);
else
for(i=2;i<n;i++)
DepartmentofComputerScience&Engineering 12
{
fib[i]=fib[i-1]+fib[i-2];
}
printf(“Thefibonacciseriesare:\n");
for(i=0;i<n;i++)
{
printf("%d\t",fib[i]);
}
}
SortingTechniques:-
Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large datasets as its average and worst case time complexity are
of O(n2). where n is the number of items.
#include<stdio.h>vo
idmain()
{
int a[50],n,i,j,temp;
printf("Enterthenumberofelements\n");
scanf("%d",&n);
printf("Enter%delements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Theenteredelementsare\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n*****SORTING******\n"); 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("Thesortedelementsare\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
#include<stdio.h>vo
idmain()
{
int a[20],n,i,j,temp;
printf("Entertotalelements\n");
scanf("%d",&n);
printf("Enter%delements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Thesortedelementsare\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
SearchingTechniques:
Linearsearch:-[Link] for a
given specific element called as key element in the large list of data in sequential order.
Ifthekeyelementispresentinthelistofdatathen thesearchissuccessfulotherwisesearchis
unsuccessful.
Benefits:
• Simpleapproach
• Workswell forsmallarrays
• Usedtosearchwhentheelementsarenotsorted
Disadvantages:
• Lessefficientifthearrayislarge
• Iftheelementsarealready sorted, linearsearchisnot efficient.
#include<stdio.h>vo
idmain()
{
int a[100],n,i,key,flag=0;
printf("Enterthenoofelements\n");
scanf("%d",&n);
printf("Enter%delements",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Entertheelementtobesearched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag==1)
printf("Elementfoundatposition%d\n", i+1);
else
printf("Elementnotfound\n");
}
1. Dividesthearrayintothreesections:
– middleelement
2. Ifthemiddleelementisthecorrectvalue,[Link],[Link] half of
the array that may contain the correct value.
3. [Link] examine
Advantages:
• Veryefficicentsearchingtechnique.
Disadvantages:
CprogramtosearchanelementinanarrayusingBinarysearch
#include<stdio.h>vo
idmain()
{
inta[100],n,i,low,high,mid,key,flag=0;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter%delementsinascendingorder\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Entertheelementtobesearched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
flag=1;
break;
}
else
if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(flag==1)
printf("Elementfoundat position%d\n", mid+1);
else
printf("Elementnotfound\n");
}
Twodimensional array
The simplest form of multidimensional array is two dimensional array. Arrays with two or
moredimensions arecalledmulti-dimensionalarrays.(interms ofrowsandcolumns)ofsame
[Link]
subscript represents rows and the second subscript represent column.
Syntax:
data_typearray_name[size1][size2];
where,
data_type:isthetypeofdatatobestoredandprocessedinthecomputer’smemory array_name:
array[size2]:indicatesthenumberofcolumnsinthearray
. Example:
int a[2][3];
Representsaisatwodimensionalintegerarraythatholdstworowsandthree columns.
Initializationoftwodimensionalarray:
1)Initializingallelementsrowwise:-Amultidimensionalarraycanbeinitializedbyspecifying
bracketed values for each row.
Example:
int[2][3]={{5,3,4}{6,1,2}};
Printing2Darray
wherem-rowsize,n-columnsize,i-rowindexandj-columnindex for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d",a[i][j]);
}
printf(“\n”)
}
ProgrammingexamplesonTwodimensional array:
#include<stdio.h>vo
id main()
{
inta[20][20]m,n,i,j;
printf(“entertherowandcolumnsize\n”); scanf(“%d
%d”,&m,&n);
printf(“Entertheelementsofmatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf(“Theelementsofmatrixare\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf(“\n”);
}
}
Output
Entertherowandcolumnsize 2
3
Entertheelementsofmatrix 3
45 9 10 12
Theelementsofmatrixare
3 4 5
9 10 12
include<stdio.h>voi
d main()
{
inta[20][20],b[20][20],c[20][20],m,n,i,j;
printf(“entertherowsandcolumnofmatrix\n”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrixA\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“EntertheelementsofMatrixB\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“MatrixAddition\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“Theresultantmatrixis\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\n”,c[i]);
}
printf(“\n”);
}
}
3. WriteaCProgram tofindTransposeofmatrix
include<stdio.h>voi
d main()
{
inta[20][20],b[20][20],m,n,i,j;
printf(“entertherowsandcolumnofmatrix\n”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“EntertheelementsofMatrixare\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“MatrixTranspose\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[j][i]=a[i][j];
}
}
printf(“TheTransposeofthematrixis\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}
4. WriteaCProgramtoprintDiagonal elementsofthematrix
include<stdio.h>voi
d main()
{
inta[20][20],m,n,i,j;
printf(“enterthenorowsandcolumnofmatrix\n”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“MatrixAis\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“ThediagonalElementsare\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
if(i==j)
{
printf(“%d”,a[i][j]);
}
}
printf(“\n”);
}
}
#include<stdio.h>vo
id main()
{
int a[20][20],m,n,i,j,sum;
printf(“enterthenorowsandcolumnofmatrix\n”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“MartixAisDisplayedas\n”); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[i][j];
}
printf(“sumoftheelementsofrow%dinmatrix=%d”,i,sum);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[j][i];
}
printf(“sumoftheelements ofcolumn %din matrix=%d”,i,sum);
}
6. WriteaCProgramtofind sumoftheDiagonalelementsofthematrix
#include<stdio.h>vo
id main()
{
int a[20 ][20], m,n, i,j,sum=0;
printf(“entertheorderofmatrix”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“MartixAisDisplayedas\n”); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=sum+a[i][i];
}
printf(“Thesum ofthediagonalelementsof matrix=%d\n”,sum);
}
7. WriteaCProgramtofindthelargestelementin givenmatrix
#include<stdio.h>vo
id main()
{
int a[20 ][20], m,n, i,j,large;
printf(“entertheorderofmatrix\n”);
scanf(“%d%d”,&m,&n);
printf(“EntertheelementsofMatrix\n”); for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“MartixAisDisplayedas\n”); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
large=0; for(i=0;i<m;i+
+)
{
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
}
printf(“Thelargestelement in thematrix =%d\n”,large);
}
Multidimensionalarray
Anarrayhaving3ormoresubscriptordimensionsisknownasmultidimensionalarray. It is
also known as arrays of arrays or matrix.
The general form of multidimensional array is
data_typearray_name[s1][s2][s3]….[sn];
Wheres1 is the sizeof ith dimension.
RepresentationofMultidimensionalArray
Strings:-
Definition:- A string constant or a string literal can be defined as a sequence of characters
enclosed in double quotes that will be treated as a single data element followed by a null
character ‘\0’
Syntax:
charstring_name[size];
Where,
charisthedatatype ofstrings
string_nameisavalididentifierwhichisthenameforthestringvariable size
indicates the length of the string which is to be stored
Initializationofstrings:
charstr1[10]=“peter”;
or
charstr1[10]={‘p’,‘e’,‘t’,‘e’,‘r’};
Boththeinitializations mentionedaresame
ifwedirectly specifythe entirestringat atimeweuse“ ”
ifwespecifythecharactersseparatelyweshoulduse‘’,foreachcharacterandfinally enclosing all
thecharacters within { }
Thestringinitialized previouslywillbestoredinmemoryas
Formattedinputandoutput:-
scanf() and printf():-
Thescanf()andprintf()statementsareusedwhen wearereadingor displayingasinglestring (without
space).
Wedo not use “&”symbol in scanfbecause string name itself represent the address whereit is
to be stored.
%sistheformatspecifierusedforstring.
/*Cprogram toread anddisplaystringusingformatted I/Ofunction*/
#include<stdio.h>vo
id main()
{
charstr[20];
printf(“Enterastring\n”);
scanf(“%s”,str);
printf(“Theenteredstringis =%s\n”,str);
}
Unformattedinputandoutput:-
gets() and puts():
ifwewanttoreadordisplaythesetofstrings(sentenceorwordswithspace)wemakeuseof gets() and
puts() function for single display at once
/*Cprogram toread anddisplaystringusingformatted I/Ofunction*/
#include<stdio.h>vo
id main()
{
charstr[20];
printf(“Enterastring\n”);
gets(str);
printf(“Theenteredstringis\n”);
puts(str);
}
ArrayofStrings/MultidimensionalStrings:-
The twodimensionalarrayofstringsisanarrayofonedimensionalcharacterarraywhich consist of
strings as its individual elements.
Syntax:
charstring_name[size1][size2];
where,
charisadatatypeof strings
string_nameisavalididentifierwhich isthenameofthestringvariable size1
indicates thenumber of strings in the array
size2indicatesthemaximumlengthofeachstring. Static
Initialization of strings:-
charstr1[3][10]={“Thomas”,“Bob”,“Alice”};
DynamicInitializationofArrayof strings:-
/*Cprogram forreadinganddisplayingArrayofstrings */
#include<stdio.h>vo
id main()
{
charstr[50][50];
int n,i;
printf(“Enterthenumberofnames\n”);
scanf(“%d”,&n);
printf(“Enter%dnames\n”,n);
for(i=0;i<n;i++)
{
scanf(“%s”,str[i]
}
printf(“Enterednamesare\n”);
for(i=0;i<n;i++)
{
printf(“%s\n”,str[i]
}
}
String Manipulating Functions:- C supports different string handling functions to perform
[Link]
“#include<string.h>”.
Someofthemostcommonusedbuilt-instringmanipulation functionsare
• strlen():Returns thenumberof characterin thegiven string
• strcmp():Compares two stringfortheirsimilarity
• strcpy():Copiessource stringintodestinationstringvariable
• strcat():Concatenates (joins)twostringintosinglestring
• strrev():Reversesagiven string
• strupr():Convertscharacterstouppercase
• strlwr():Convertscharacterstolowercase
StringLength:-Thefunctionstrlen()isusedtofindthelengthofthestringintermsofnumber of
characters in it.
SYNTAX:
strlen(string_data);
/*Cprogram tofindlengthofthestring usingstrlen()function */
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[50];
int len;
printf("Enterastring\n");
scanf("%s",str1);
len=strlen(str1);
printf("LengthoftheString=%d\n",len);
}
*****OUTPUT*****
Enter a string
mangalore
LengthoftheString=9
/*Cprogram tofindlength ofthestringwithoutusingstrlenfunction*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[50];
int i,count;
printf("Enterastring\n");
scanf("%s",str1);
count=0; for(i=0;str1[i]!
='\0';i++)
{
count=count+1;
}
printf("LengthoftheString=%d\n",count);
}
String Compare:- The function strcmp() is used to compare the string data every character
of one string is compared with the corresponding position character ofsecond string.
SYNTAX
strcmp(str1,str2)
• Thefunctionreturns0if thereiscompletematch(str1==str2)
• Returnspositivevalueifstr1>str2
• Returnsnegativevalueif str1<str2
/*Cprogram tocomparetwostringsusingstrcmp()function*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[20],str2[20];
int k;
printf("Enterstring1\n");
scanf("%s",str1);
printf("Enterstring2\n");
scanf("%s",str2);
k=strcmp(str1,str2);
if(k==0)
printf("Stringsaresame\n");
else
printf("Stringsaredifferent\n");
}
*****OUTPUT*****
Enter string 1
mite
Enterstring2
mite
Stringsare same
/*Cprogramtocomparetwostringswithoutusingstrcmp()function*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
charstr1[20],str2[20];
int len1,len2,i;
printf("Enterstring1\n");
scanf("%s",str1);
printf("Enterstring2\n");
scanf("%s",str2);
len1=strlen(str1);
len2=strlen(str2); if(len1!
=len2)
printf("Stringsaredifferent\n");
else
{
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
printf("Stringsaredifferent\n");
exit(0);
}
}
printf("Stringsaresame\n");
}
}
StringCopy:-Thefunctionstrcpy()copiesthecontentfromonestringto anotherstring SYNTAX
strcpy(str2,str1);
/*Cprogram tocopythestringusingstrcpyfunction */
#include<stdio.h>
#include<string.h>v
oid main()
{
char str1[30],str2[30];
printf("Enterstring1\n");
scanf("%s",str1);
strcpy(str2,str1);
printf("Thecopied stringis =%s\n",str2);
}
*****OUTPUT*****
Enter string1
mitemangalore
Thecopied string is = mite
/*Cprogram tocopythestringwithoutusingstrcpy()function*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[30],str2[30];
int i=0;
printf("Enterstring1\n");
scanf("%s",str1);
while(str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}
str2[i]='\0';
printf("TheOriginalString=%s\n",str1);
printf("The Copied String=%s\n",str2);
}
*****OUTPUT*****
Enter string1
Mangalapuram
TheOriginalString=Mangalapuram
The Copied String=Mangalapuram
StringnCopy:-Thestrncpy()funtioncopiesthencharactersofonestringtoanotherstring SYNTAX
strncpy(dest_string,source_string,n);
Wherenisanintegervaluewhichspecifiesthenumberofcharacterstobecopied
/*Cprogram toillustratestrncpy()function*/
#include<stdio.h>
#include<string.h>v
oid main()
{
char str1[30],str2[30];
printf("EnterString1\n");
gets(str1);
printf("String1=%s\n",str1);
strncpy(str2,str1,10);
printf("String2=%s\n",str2);
}
*****OUTPUT*****
Enter String1
MANGALORE_INSTITUTE_OF_TECHNOLOGY
String1=MANGALORE_INSTITUTE_OF_TECHNOLOGY
String 2=MANGALORE_
StringConcatenate:-Thefunctionstrcat()isusedtoconcatenate(attach)twostrings. SYNTAX
strcat(str1,str2);
/*Cprogram toconcatenatetwostringsusingstrcatfunction*/
#include<stdio.h>
#include<string.h>v
oid main()
{
char str1[30],str2[30];
printf("EnterString1\n");
scanf("%s",str1);
printf("EnterString2\n");
scanf("%s",str2);
strcat(str1,str2);
printf("Theconcatenated stringis=%s\n",str1);
}
*****OUTPUT*****
Harry
EnterString2
Potter
Theconcatenatedstring is=HarryPotter
/*Cprogramtoconcatenatetwostringswithoutusingstrcat()function*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[20],str2[20],str3[50];
int i,k;
printf("EnterString1\n");
scanf("%s",str1);
printf("EnterString2\n");
scanf("%s",str2);
k=0;
for(i=0;str1[i]!='\0';i++)
{
str3[i]=str1[i];
k=k+1;
}
for(i=0;str2[i]!='\0';i++)
{
str3[k]=str2[i];
k=k+1;
}
str3[k]='\0';
printf("Theconcatenated stringis=%s\n",str3);
}
*****OUTPUT*****
Enter String1
Ronald
EnterString2
Weasley
Theconcatenated string is=RonaldWeasley
String n Concatenate: - The function strncat() is used to concatenate the specified number
of characters only
SYNTAX
strncat(string1,string2,n);
Wherenisaninteger valuewhichconcatenatesonly n charactersofstring2tostring1
/*Cprogram toillustratestrncat()function*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[30],str2[30];
printf("EnterString1andString2\n");
scanf("%s%s",str1,str2);
strncat(str1,str2,5);
printf("Theconcatenated stringis=%s\n",str1);
}
*****OUTPUT*****
EnterString1andString2
Hermoine
Granger
Theconcatenated string is=HermoineGrang
Thecharactersfromlefttorightintheoriginalstringareplacedinthereverseorder SYNTAX
strrev(str1)
#include<stdio.h>
#include<string.h>v
oid main()
{
char str1[30];
printf("EnterString1\n");
gets(str1);
strrev(str1);
printf("TheReversed string=%s\n",str1);
}
*****OUTPUT*****
Enter String1
wingardiamleviosa
TheReversedstring =asoivelmaidragniw
*****OUTPUT*****
Enter String1
Expectopetronum
Thereversedstring=munortepotcepxE
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[50],str2[50];
int i,j,len,x;
printf("EnterString1\n");
gets(str1);
j=0;
len=strlen(str1);
for(i=len-1;i>=0;i--)
{
str2[j]=str1[i];
j++;
}
str2[j]='\0';
printf("The original String =%s\n",str1);
printf("ThereversedString=%s\n",str2);
x=strcmp(str1,str2);
if(x==0)
printf("%sisapalindrome\n",str1);
else
printf("%sis notapalindrome\n",str1);
}
*****OUTPUT*****
malayalam
The original String =malayalam
ThereversedString=malayalam
malayalam is a palindrome
StringLower:-Thefunctionstrlwr()convertseachcharacterofthestringtolowercase.
SYNTAX
strlwr(string_data);
StringUpper:-Thefunctionstrupr()convertseachcharacterofthestringtouppercase. SYNTAX
strupr(string_data);
/*Cprogramtoconvertstringstouppercaseandlowercaseusingstrupr()andstrlwr()
functions*/
#include<stdio.h>
#include<string.h>v
oid main()
{
charstr1[50],str2[50];
printf("Enterthestringinlowercaseletters\n");
scanf("%s",str1);
printf("ThestringinUppercaseletteris=%s\n",strupr(str1));
printf("Enter the string in Upper case letters\n");
scanf("%s",str2);
printf("Thestring inLowercaseletteris=%s\n", strlwr(str2));
}
*****OUTPUT*****
Enterthestringinlowercaseletters dumbledore
ThestringinUppercaseletteris=DUMBLEDORE
Enter the string in Upper case letters
HAGRID
Thestringin Lowercaseletteris=hagrid
OtherApplications ofstrings. :-
TheString functions are also used to count thenumberofvowels and consonants in thegiven
string. And also gives the frequency of occurrence of each vowel in the given string.
Thisprogrammakesuseoftheheaderfile“#include<ctype.h>”which isusefulfortestingand
[Link]“isalpha()”whichisusedtocheckifthe parsed
character is an alphabet ornot.
/*CprogramtocountthenumberofVowelsand ConsonantsinagivenSentence*/
#include<stdio.h>
#include<string.h>
#include<ctype.h>
main()
{
charstr1[50],ch;
inti,vc=0,cc=0,ac=0,ec=0,ic=0,oc=0,uc=0;
printf("\n Enter a sentence\n");
gets(str1);
printf("Theenteredsentenceis\n");
puts(str1);
for(i=0;i<strlen(str1);i++)
{
if(isalpha(str1[i]))
{
ch=str1[i]; if(ch=='a'||
ch=='A')
ac++;
elseif(ch=='e'||ch=='E')
ec++;
elseif(ch=='i'||ch=='I') ic+
+;
elseif(ch=='o'||ch=='O')
oc++;
elseif(ch=='u'||ch=='U')
uc++;
else
cc++;
}
}
vc=ac+ec+ic+oc+uc;
printf("\nThetotal numberofvowels =%d\n",vc);
printf("\nThefrequencyofvowelais=%d\n",ac);
printf("\nThefrequencyofvoweleis=%d\n",ec);
printf("\n The frequency of vowel i is =%d\n",ic);
printf("\nThefrequencyofvowelois=%d\n",oc);
printf("\nThefrequencyofvoweluis=%d\n",uc);
printf("\nTotalnumberofconsonants=%d\n",cc);
}
#include<stdio.h>vo
id main()
{
chatstr[100];
int i=0,vc=0,cc=0;
printf(“Enteranystring\n”);
gets(str);
while(str[i]!=‘\0’)
{
if(str[i]==‘a’||str[i]==‘e’||str[i]==‘i’||str[i]==‘o’||str[i]==‘u’||str[i]==
‘A’||str[i]==‘E’||str[i]==‘I’||str[i]==‘O’||str[i]==‘U’)
{
vc++;
}
else
{
cc++;
} i+
+;
}
printf(“Number of Vowels in the string = %d\n”,vc);
printf(“Numberofconsonantsinthestring=%d\n”,cc);
}