Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 185

ProgramingforProblemSolvingLab

B.Tech(CSE)1stYear2ndSemester

SubmittedTo
Mr. Piyush Kumar
Gupta(Assistant
Professor)

Submitted
By:Mohd Nazim
2020-310-157

(Signature)

JamiaHamdard
Department Of Computer Science &
EngineeringSchoolOfEngineeringSciences&Tec
hnology
1|Page
NewDelhi-110062

2|Page
INDEX

S.NO Programs Pag


. e
No.
1 WAPtoprint“HelloWorld”onmonitor. 9
2 WAPtocomputeandprinttheareaofcircle 10

itsradiusto beinputbytheuser.
3 WAPtoillustrate theuseof relationaloperatorsinC. 11
4 WAPtofind thelargerof5numbers (inputby 12
theuser)using
theconditionaloperator.
5 WAPtoillustrate theuseofbitwiseoperatorsinC. 13
6 WAPtofind thesumand averageof 14
10integernumbers.
7 Demonstratetheuseofprecisionfeaturesand 15
minimum field width specification with floating
pointnumbersinprintf()statement.
8 Writeaprogramthatprintsthevalue123.4567 16
infixed point
formatwiththe followingspecification
1) Minimumfieldwidthspecificationof8andupto2deci
malplaces
2) Leftjustifiedinminimumfieldwidthspecificationof8
andup to2decimalplaces
3) Minimumfieldwidthspecificationof8withtrai
ling
blanksandup to2decimalplaces
4) Inclusion of appropriate sign (+ or -) in
minimumfield
widthspecificationof8andupto2decimal places

9 WAPtoenter 17
theageofapersonandcheckifhe/sheiseligible to
castavote.
3|Page
10 WAPtoinputanintegernumberfromthekeyboardandc 18
heck ifitisdivisibleby3and 5.
11 WAPtofindthelargestof5integernumbersinputbytheus 19
erusing if-else.
12 WAPinCto 20
inputthedayoftheweekinnumericformanddisplayin
words using if-else.
Thegradingofstudentsisdoneaccordingtothefollo
wingrules
AverageMarksGrade8
0-100A
70-79B
60-69C
50-59D
40-49E
0-39F
13 WAPtoenterthe marksof 21
5subjectsforeach5studentsanddisplaythegradeof
students.
14 Given3points(x1,y1),(x2,y2)and(x3,y3)WAPto 25
checkifallthethreepointsareallon astraightline.
15 Givencoordinates(x,y)of 27
thecentreofacircleanditsradius,
WAP which will check whether a given point (p,
q)lieswithin
thecircle,onthecircleor outsidethecircle.
16 Givenapoint(x,y),WAPtofind outifit lieson thexaxis,y 29
axisoron theorigin
17 If the three sides of a triangle are entered through 30
thekeyboard,WAPtocheckwhetherthetriangleisvalido
rnot.Thetriangle isvalidifthesumof twosidesis
greaterthanthelargestofthethirdsides.
18 Ifthethreesidesofatriangleareenteredthrough 32
thekeyboard, WAP to check whether the triangle
isisosceles,equilateral,and
scaleneor rightangletriangle.

4|Page
19 WAPtocomputefactorialof agiven 33
positiveintegernumber
inputby theuser.Makeuseofwhile loop.

5|Page
20 WAPtoprintoutallArmstrongnumbersbetween1and1 34
0000.
21 WAPtoenterthe numberstilltheuserwants 35
andattheend itshoulddisplaythecountofpositive,
negativeandzeroesentered.(Makeuseofarray)
22 WAP to receive an integer and find its binary, 37
octalandhexa-decimalequivalent.
23 WAP in C to enter the age of 5 students and find 39
theaverageage.Thecontrolshouldskiptothebeginning
oftheloopwhentheageisenteredas0.
24 WAP menu driven program which has 40
followingoptions:
1) Computeab
2) Enterednumberprimeornot
3) Enterednumber oddoreven
4) exit
25 If two integers are entered through the 44
keyboard,WAPtoobtain
theprimefactorsofthisnumber.
(usingrecursivefunction)
26 Writeafunctionthatreceivesanintegerarrayand 45
returnsthesum,average,mean,mod
andstandarddeviationofit.
27 Writeafunctiontocomputethegreatestcommon 47
deviser (GCD) and least common deviser (LCD)
foranygiven twonumbers.
28 A6x6matrixis 49
enteredthroughthekeyboard,WAPtoobtain
thedeterminantvalueofthismatrix.
29 Enter 3 matrices of order p*q and multiply 51
them.Note:Everymatrixorderpandqshouldberandom.
30 Perform the appropriate operation of 53
addition,subtraction multiplication or division as
input by theuseron twointegernumbers.
Makeuseofswitch
statement.
31 Inputaparagraph 55
fromthekeyboardandprintnumberofvoweland
6|Page
consonantinit.
32 PrinttheFibonacci seriesuptofirstnterms,thevalueofn 56
tobe inputby theuser.(UseRecursion)

7|Page
33 .Printfollowing patternsusingloops: 57

34 WAP to copy the contents of one array into 66


anotherarrayinthereverseorder.
35 Findthesmallestnumberinanarrayusingpointers. 67
36 WAPtofindifann*nsquarematrixissymmetric. 68
37 Evaluatethegivenserieswithoutusinganylibraryfun 70
ctions,the
valuesofx andntobeinputby theuser.1)1
+x 2+ x3 +x 4+……+xn.
2)1/1!+1/2!+1/3!+................1/n!.
3)1/1!+x2/2!+x 3/3!+x4/4!+……+xn/n!.
38 WAPtofind 74
iftheyearenteredbytheuserisleapyearornot.
(Yearinbetween 1to9999).
39 WAP to input characters from the keyboard. Find 76
howmany of these characters are alphabets, how
many aredigitsand how
manyarespecialcharacters.
40 WAPtoprintall 77
theprimenumbersbetween1and10000.
41 Writeprogramsforfollowingsorting’s: 79
1) Bubblesortorexchangesort
2) Selectionsort
3) Insertionsort

8|Page
42 WAP to search an element in an unsorted list 83
ofelementsusing linearsearch.Andalsoapplyinsorted
listofelements. (Make useofswitchstatement)
43 WAPtosearchan elementinanunsortedlistof 85
elements using binary search. (Before applying
binarysearch, firstsortthe elements)
44 Printthetransposeofa matrixinputby theuser. 89
45 WAPtomerge2sorted1Darray. 91
46 WAPtoswapthe valuesusingcallbyvaluemethod. 93
47 WAPtoswapthe 94
valuesusingcallbyreferencemethod.
48 WAPtosolvetheAckermanfunctionusingrecursion. 95
49 WAPformergesort. 96
50 WAPforquicksort. 98
51 WAPthatconvertsastringlike“124”toaninteger124 100

52 WAPtosortaset 101
ofnamesstoredinanarrayinalphabetical
order.
53 WAPprogramtofindday ofagivendate. 102
54 WAPforstrcpy,strlen,strrev,strcmpwithoutusingpre 103
definedfunctions.
55 WAPtofind thenumberofwordsinalineoftext. 105
(Using
String)
56 WAPtocheckifastringisapalindrome. 106
57 WAP to sort a list of names in the ascending order 107
oflengthof thenames.
58 WAP to illustrate the scope of local and 108
globalvariablehavingthesame name.
59 WAPtoillustrate theuseofstaticvariables. 109
60 WAPforaccessingelementsthroughpointerina1Darra 110
y.
61 WAPforaccessingelementsthroughpointerina2Darra 111
y.
62 WAPtoshowthememoryallocationtothecharactersinast 112
ring.

9|Page
63 WAPtoillustratereturnofapointerfroma function. 113
64 WAP to read and display the elemnts of an array 114
ofintegers.Allocate
memorytothearraydynamicallyusingmalloc(),calloc
()andrealloc()functions.
65 WAPtocreatea structuretospecify 115
dataonstudentsgivenrollno,name,dept.,course,yearofj
oining.
Assumetherearenot
morethan450studentsinthecollege
a) Writeafunctiontoprintnames of
allstudentswhojoinedin aparticularyear.
b) Writeafunctiontoprintthedataof
allstudentswhoseroll numberisgiven
c) Writeafunctiontoprintnamesofallstudentswhoaread
mitted inaparticulardepartment.
66 Writeamenudrivenprogramthat 119
showstheworkingofalibrary,the menu optionshould
be:
a) Addbookinfo
b) Displaybookinfo
c) List allbooksofgivenauthor
d) Listthetitleof specifiedbook
e) List thecountof booksinthelibrary
f) Listthebooksintheorderof accessionnumber.
g) Exit
Createastructure
calledlibrarytoholdaccessionnumber,title
of the book, author name, price of the book and
flagindicating whetherbookisissuedornot.
67 Createastructuretospecifydataofcustomersinabank, 124
thedatastored is:
a) A/Cnumber
b) Name
c) Balance ina/c
Assumethenumbermax200customersinthebank
a)Write a functiontoprintthea/c
numberandnameofeachcustomerwithbalancebellowr
10|Page
upees100.

11|Page
b) Ifacustomerrequestsforwithdrawalordeposititis
given in the form a/c number, amount, code (1
fordepositand 0for
withdrawal)
c) Write a program to give a message that balance
isinsufficientforthespecifiedwithdrawal.
68 WAPtoopenafilereadit and write thecontentsin 128
anotherfileandalsocountthenumberofcharacterandw
ordsin thatfile.
69 WAPtodelete allvowelsfromasentence.UsingFile. 130
70 WAPtodeletealltheextraspaces 131
fromaparagraph.UsingFile.
71 WAPtoimplementsinglyconnectedlinkedlist. 132
72 Brieflyexplainanddifferentiatefollowingterms:pri 139
ntf,scanf,gets, puts,getchar,putchar,sprint,
sscanf,read,write,getc,putc.

12|Page
1. WAPtoprint“HelloWorld”onmonitor.In
put:
#include

<stdio.h>int

main()

printf("Hello

World!");return0;

Output:
HelloWorld

13|Page
2. WAPtocomputeandprinttheareaofcircle,itsradiustobeinputb
ytheuser.
Input:
#include<stdio.h>

int main()

floatradius,area;

printf("\n Enter the radius of Circle :

");scanf("%d",& radius);

area =3.14 * radius* radius;printf("\n

Area of Circle : %f", area);return0;

Output:
Enter radius of a circle:

1Area of circle:

3.14Circumference:6.28

14|Page
3. WAPtoillustratetheuse
ofrelationaloperatorsinC.Input:
#include
<stdio.h>int
main()
{
int m=40,
n=20;if(m ==n)
{

printf("mandnareequal");
}
Else
{
printf("mandnarenot equal");
}
return0;
}

Output:
mand n arenot equal

15|Page
4. WAPtofindthelargerof5numbers(inputbythe
user)usingtheconditionaloperator.
Input:#include<s
tdio.h>intmain ()
{
inta, b, c, d,e, f, x,y,z, large;
printf(" Enter any five integer numbers :
") ;scanf("%d %d %d %d %d", &a, &b, &c, &d,
&e) ;x = (a>b?a:b);
y =(c >d? c :d);
z= (e > f? e:f);
large =x>y?(x>z?x: z): (y>z?y :z);printf("\n\n The
largest of Five numbers is : %d", large) ;return0;
}

Output:
Enteranyfiveintegernumbers:455421-8990

Thelargestoffivenumbersusing Conditionalternary Operatoris:90

16|Page
5. WAPtoillustratetheuse of
bitwiseoperatorsinC.Input:
#include<stdio.h>int
main()
{
unsignedchara=5,b=9;printf("a=
%d,b=%d\n",a,b);printf("a&b=%d\
n",a&b);printf("a|b=%d\n",a|
b);printf("a^b=%d\
n",a^b);printf("~a=%d\
n",a=~a);printf("b<<1=%d\
n",b<<1);printf("b>>1=%d\
n",b>>1);

return0;
}

Output:
a=5,b=9
a&b=1
a|b=13
a^b=12
~a=250
b<<1=18
b>>1=4

17|Page
6. WAPtofindthesumandaverageof10integernumbers.Input:
#include
<stdio.h>int
main()
{
inti,n,sum=0;
floatavg;
printf("Input the 10 numbers : \
n");for(i=1;i<=10;i++)
{
printf("Number-%d:",i);
scanf("%d",&n);
sum+=n;
}
avg=sum/10.0;
printf("Thesumof10nois:%d\nTheAverageis:%f\n",sum,avg);
return0;
}

Output:
Inputthe10numbers:N
umber-1:1
Number-2:2
Number-3:3
Number-4:4
Number-5:5
Number-6:6
Number-7:7
Number-8:8
Number-9:9
Number-10:10
Thesumof10nois:55TheAve
rageis:5.500000

18|Page
7. Demonstratetheuseofprecisionfeaturesandminimumfieldwidt

h specification with floating point number in printf()statement.


Output:
#include<stdio.h>
int main()
{

int i =

1234;float x=

348.45;chara[];

printf("%3d%5d%8d",i,i,i);

printf("%7f %7.1f %7.3f ",

x,x,x);printf("%10s %13s

%10.5s",a,a,a);return0;
}

Output:

1234 1234 _ _ _ _ 1234

348.450000 _ _ 348.5 348.450

_precision _ _ _ _precision________precision

19|Page
8. Writeaprogramthatprints thevalue123.4567infixed

pointformatwiththefollowing specification
1) Minimum field width specification of 8 and up to

2decimalplaces
2) Left justified in minimum field width specification of

8andup to 2decimal places


3) Minimum field width specification of 8 with

trailingblanksandup to 2decimal places


4) Inclusion of appropriate sign (+ or -) in minimum

fieldwidthspecificationof 8and upto 2decimal places

Input:
#include<stdio.h>i
nt main()
{
floatNum=123.4567;
printf("fixed-point format (correct to two decimal places):-- %.2f\
n",Num);printf("fixed-point format (correct to five decimal places):-- %.5f\
n",Num);printf("fixed-pointformat(correcttozerodecimalplaces):--%f\
n",Num);
printf("fixed-point format (correct to negative to positive decimal places):-- -+%f\
n",Num);return0;
}

Output:
fixed-point format (correct to two decimal places):--

123.45fixed-point format (correct to five decimal places):--

123.45670fixed-pointformat(correcttozerodecimal places):--

123.456703

fixed-point format(correct tonegativetopositivedecimalplaces):---+123.456703


20|Page
9. WAPtoentertheageofapersonandcheckifhe/

sheiseligibletocastavote.
Input:
#include<stdio.h>
int main()
{
int age;
printf("Enter Age of Person :
");scanf("%d",&age);
if(age>17)
printf("\nPerson is Eligible for
Voting");else
printf("\nPerson is NOT Eligible for
Voting");return0;
}

Output:
EnterAgeofPerson :17

Person is NOT Eligible for

VotingEnterAgeof Person : 24

Personis EligibleforVoting

21|Page
10. WAPtoinputanintegernumberfrom

thekeyboardandcheckifitisdivisibleby3 and5.

Input:
#include<stdio.h>
int main()
{

intnum;
printf("Enter an integer:
");scanf("%d",&num);
if(num%3 ==0 && num %5 ==0)
{
printf("Numberisdivisibleby3 and5");
}
else
{
printf("Numberis notdivisible by3 and5");
}
return0;
}

Output:
Enteraninteger:10
Number is not divisible by 3 and
5Enteran integer: 15
Numberis divisibleby3 and 5

22|Page
11. WAP to find the largest of 5 integer numbers input by the

userusing if-else.

Input:
#include<stdio.h>
int main()
{
inta,b,c,d,e;
printf("ENTERTHEFIVENUMBERS");
scanf("%d %d %d %d %d", &a, &b, &c, &d,
&e);if(a>b&& a>c&&a>d &&a>e)
printf("%dislargest",a);else
if(b>c && b>d &&
b>e)printf("%dislargest",b);e
lse if(c>d &&
c>e)printf("%dislargest",c);e
lseif(d>e)
printf("%dis largest",
d);else
printf("%d is largest",
e);return0;
}

Output:
ENTERTHEFIVENUMBERS1 53 7 2
7islargest

23|Page
12. WAPin Ctoinputthedayoftheweek

innumericformanddisplayinwordsusingif-else.

Input:
#include
<stdio.h>int
main()
{
intweek;
printf("Enter week number (1-7):
");scanf("%d",&week);
if(week ==1)
{
printf("Monday");
}
elseif(week==2)
{
printf("Tuesday");
}
elseif(week==3)
{
printf("Wednesday");
}
elseif(week==4)
{
printf("Thursday");
}
elseif(week==5)
{
printf("Friday");
24|Page
}
elseif(week==6)
{
printf("Saturday");
}
elseif(week==7)
{
printf("Sunday");
}
else
{
printf("Invalid Input!Pleaseenterweeknumberbetween1-7.");
}
return0;
}

Output:
Enter week number (1-7):
5Friday

25|Page
13. Thegradingofstudentsis
doneaccordingtothefollowingrules
Average Marks
Grade80-100 A
70-79 B
60-69 C
50-59 D
40-49 E
0-39 F
WAPtoenterthemarksof5subjectsfor
each5studentsanddisplaythe gradeof students.

Input:
#include
<stdio.h>int
main()
{
float marks1, marks2, marks3, marks4, marks5,
average;printf("Entermarksobtainedinsubject1:");scanf("
%f",&marks1);
printf("Enter marks obtained in subject
2 :");scanf("%f",&marks2);
printf("Enter marks obtained in subject
3 :");scanf("%f",&marks3);
printf("Enter marks obtained in subject
4 :");scanf("%f",&marks4);
printf("Enter marks obtained in subject
5 :");scanf("%f",&marks5);
average = (marks1 + marks2 + marks3 + marks4 + marks5) /
5;printf("Average: %0.2f\n", average);

26|Page
if(average >=80)
{
printf("GradeA");
}
elseif(average>=70)
{
printf("GradeB");
}
elseif(average>=60)
{
printf("GradeC");
}
elseif(average>=50)
{
printf("GradeD");
}
elseif(average>=40)
{
printf("GradeE");
}
else
{
printf("GradeF");
}
return0;
}

27|Page
Output:
Enter marks obtained in subject 1 :
82Enter marks obtained in subject 2 :
75Enter marks obtained in subject 3 :
66Enter marks obtained in subject 4 :
56Enter marks obtained in subject 5 :
45Average: 64.80
GradeC

28|Page
14. Given3points (x1,y1),
(x2,y2)and(x3,y3)WAPtocheckifallthethreepointsareallonastrai
ghtline.
Input:
#include<stdio.h>
int main()
{
float x1, y1, x2, y2, x3, y3, m,
n;printf("Enter points (x1, y1)\
n");scanf("%f%f", &x1,
&y1);printf("Enter points (x2,
y2)\n");scanf("%f%f", &x2,
&y2);printf("Enter points (x3,
y3)\n");scanf("%f%f",&x3,
&y3);
m=(y2 -y1) / (x2-x1);

n = (y3 - y2) / (x3 -


x2);if(m==n)
{
printf("All3points lieonthe sameline\n");
}
else
{
printf("All3points donot lieon thesame line\n");
}
return0;
}

Output:

29|Page
Output1:
Enterpoints(x1,y1)

30|Page
-2
2

Enterpoints(x2,y2)2
5

Enterpoints(x3,y3)6
8

All3pointslieonthesamestraightline.

Output2:
Enterpoints(x1,y1)1
2

Enterpoints(x2,y2)3
4

Enterpoints(x3,y3)
-10
15
All3pointsdonotlie onthesamestraight line.

31|Page
15.Givencoordinates(x,y)ofthecenterofacircleanditsradius,WAP
which will check whether a given point (p, q) lies within
thecircle,onthecircleoroutsidethecircle.
Input:
#include<stdio.h>
int main()
{

int x1, y1, x2, y2,


radius;floatpc;
printf("Enter the center co-ordinates of the circle:
");scanf("%d %d", &x1, &y1);
printf("Enter the radius of the circle:
");scanf("%d",&radius);
printf("Enter the point co-ordinates:
");scanf("%d %d", &x2, &y2);
//check for distance between point and center point of
circlepc=sqrt(pow(x2-x1, 2)+pow(y2-y1,2));
if(pc>radius)
printf("Point (%d,%d) lies outside the circle.", x2,
y2);elseif(pc<radius)
printf("Point (%d,%d) lies inside the circle.", x2,
y2);elseif(pc==radius)
printf("Point (%d,%d) lies on the boundary of circle.", x2,
y2);else
printf("Wrong
Entry");return0;
}

Output:

32|Page
Enter the center co-ordinates of the circle: 0
0Entertheradius of thecircle: 6
Enter the point co-ordinates: 0
7Point(0,7)liesoutsidethecircle.

33|Page
16. Givenapoint(x, y),WAPto findoutifit
liesonthexaxis,yaxisorontheorigin
Input:
#include<stdio.h>
int main()
{
int x1, y1;
printf("Enter the co-ordinates of point:
");scanf("%d %d", &x1, &y1);
if(x1==0&& y1!=0)
printf("Point (%d, %d) lies on y-axis", x1,
y1);elseif(x1 !=0 && y1 ==0)
printf("Point (%d, %d) lies on x-axis", x1,
y1);elseif(x1 ==0 && y1 ==0)
printf("Point (%d, %d) lies on the origin", x1,
y1);else
printf("Point(%d,%d) neitherlieonx-axisnor ony-axis",x1, y1);

return0;
}

Output:
Enter the co-ordinates of point: 0
5Point(0, 5) lies ony-axis

34|Page
17.If the three sides of a triangle are entered through
thekeyboard,WAPtocheckwhetherthetriangleisvalidornot.Thetri
angle is valid if the sum of two sides is greater than the
largestofthe thirdsides.
Input:
#include<stdio.h>
int main()
{
//we are assuming only integer values for triangle
sidesint x, y, z;
int max,valid;
//x forAB y forBC zfor AC
//nowcalculatemaxside value amongallthesides
//Takeinput
printf("Enter the first side of triangle:
");scanf("%d",&x);
printf("Enter the second side of triangle:
");scanf("%d",&y);
printf("Enter the third side of triangle:
");scanf("%d",&z);

max =
x;if(max<
y)max=y;
if(max<z)
max=z;

//if largest side is lower than the sum of two remaining


sidesif(max==x && x <(y+z))
valid=1;

if(max == y && y <


(x+z))valid=1;

if(max == z && z <


(x+y))valid=1;

if
(valid==1)printf("Triangl
e is valid");else
printf("Triangleisnotvalid");

35|Page
return0;
}

Output:
Enter the first side of triangle:
2Enter the second side of triangle:
3Enter the third side of triangle:
4Triangle is valid
Enter the first side of triangle:
4Enter the second side of triangle:
2Enter the third side of triangle:
1Triangleis not valid

36|Page
18. If the three sides of a triangle are entered through
thekeyboard, WAP to check whether the triangle is
isosceles,equilateral,andscaleneorright angletriangle.
Input:
#include<stdio.h>
int main()
{

int side1, side2,


side3;printf("Entersidesoftriangl
e:");
scanf("%d%d
%d",&side1,&side2,&side3);if(side1 == side2
&& side2 ==
side3)printf("TheGivenTriangleisequilateral\
n");
else if(side1 == side2 || side2 == side3 || side3 ==
side1)printf("Thegiven Triangle isisosceles\n");
else
printf("The given Triangle is scalene\
n");return0;
}

Output:
Run1:
Enter sides of triangle:3 4
6The given Triangle is
scaleneRun2 :
Entersides oftriangle:22 5The
given Triangle is isoscelesRun

37|Page
3:
Entersides oftriangle:555
TheGivenTriangleisequilateral

38|Page
19.WAPtocomputefactorialofa
givenpositiveintegernumberinputbytheuser.Makeuseofwhileloo
p.
Input:
#include
<stdio.h>int
main()
{
int
n,i,f;f=i
=1;
printf("Enter a Number to Find Factorial:
");scanf("%d",&n);
while(i<=n)
{
f*=i;
i++;
}
printf("The Factorial of %d is :
%d",n,f);return0;
}

Output:
Enter a Number to Find Factorial:
5TheFactorial of 5 is : 120

39|Page
20.WAP to print out all Armstrong numbers between 1
and10000.
Input:
#include
<stdio.h>int
main()
{
int a,b =0, s, n;
printf("The armstrong numbers
are-");for(n=1; n<=10000;n++)
{
s=n;
while(n >0)
{
a=n%10;
b=b+a*a*
a;n =n/ 10;
}
if (b ==
s)printf("%d",s);
}
return0;
}

Output:
TheArmstrongnumbersbetween 1and 1000are:

123 4 5 6 7 8 9 153 370 371 407

40|Page
21. WAP to enter the numbers till the user wants and at the end
itshould display the count of positive, negative and zeroes
entered.(Makeuseofarray)
Input:
#include<stdio.h>
ntmain()
{
int i, num, count_p=0, count_n=0,
count_z=0;int arr[100];
//sizeofarray
Printf("Enter Numbers:
");scanf("%d",&num);

//takeinputfromuserfor "num"numbers

for(i=0;i<num;i++)
{
scanf("%d",&arr[i]);
}

//count the
numbersfor(i=0;i<
num;i++)
{
//check for positive
numbersif(arr[i]>0)
{
count_p++;
}
elseif(arr[i]<0)
{
count_n++;
}
elseif(arr[i]==0)
{
count_z++;
}
else
{
printf("Wrong
Entry");break;
}
41|Page
}
printf("Positive Numbers: %d\n",
count_p);printf("Negative Numbers: %d\n",
count_n);printf("ZeroNumbers:%d\
n",count_z);

return0;
}

Output:
EnterNumbers:5
-12-4-50
PositiveNumbers:1
NegativeNumbers:3
ZeroNumbers:1

42|Page
22.WAP to receive an integer and find its binary, octal and hexa-
decimalequivalent.
Input:
#include<stdio.h>voi
d convert(int, int);int
main()
{
intnum;

printf("Enter a positive decimal number :


");scanf("%d",&num);
printf("\nBinary number ::
");convert(num,2);
printf("\n");

printf("\nOctal number ::
");convert(num, 8);printf("\
n");
printf("\nHexadecimal number ::
");convert(num,16);
printf("\
n");return0;
}

voidconvert(int num, intbase)


{
int rem = num
%base;if(num==0)
return;convert(num/
base,base);

43|Page
if(rem <
10)printf("%d",
rem);else
printf("%c",rem-10+'A' );
}

Output:
FIRSTRUN

Enterapositivedecimalnumber:15

Binarynumber::1111

Octalnumber::17

Hexadecimalnumber::F

SECONDRUN

Enterapositivedecimalnumber:157

Binarynumber::10011101

Octalnumber::235

Hexadecimalnumber::9D

44|Page
22. WAP in C to enter the age of 5 students and find the
averageage.Thecontrolshouldskiptothebeginningoftheloopwhenthe
ageisenteredas0.
Input:
#include<stdio.h>
int main()
{

int
s1,s2,s3,s4,s5,sum;flo
atavg;
printf("\n Enter age of student 1 :
");scanf("%d",&s1);
printf("\n Enter age of student 2 :
");scanf("%d",&s2);
printf("\n Enter age of student 3 :
");scanf("%d",&s3);
printf("\n Enter age of student 4 :
");scanf("%d",&s4);
printf("\n Enter age of student 5 :
");scanf("%d",&s5);
avg=sum/5;
printf("\n\n THE AVERAGE IS
%.2f",avg);return0;
}

Output:
Enterageofstudent 1 :5
Enterageofstudent 2 :2
Enterageofstudent 3 :1
Enterageofstudent 4 :6
Enter age of student
5 :8THEAVERAGEIS3.

45|Page
00

46|Page
24.WAPmenudrivenprogramwhichhasfollowingoptions:
1) Computea b
2) Enterednumberprimeornot
3) Enterednumberoddoreven
4) exit

Input:
#include<stdio.h>
int main()
{
int c=0, num, res, n, flag=0,
i;while(c!=4)
{
//displaymenu
printf("\n1.a^b\n2.Primeornot\n3. Oddoreven\n4.Exit\n");
//display choice option to the
userprintf("\nEnter your
choice:");scanf("%d",&c);
//write case statement for Four
optionsswitch(c)
{

//For
a^bcas
e1:

printf("Entera:");
scanf("%d",&a);

printf("Enterb:");
scanf("%d",

&b);res=power(a,

b);

printf("Result:%d",res);
}

int power(int a,int b)


{
int x;
47|Page
x = pow(a,
b);break;

48|Page
//For prime
blockcase2:
//functionalityofPrimeornot

printf("Enter an integer:
");scanf("%d",
&num);n=num;

for(i=2;i<=n/2;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}
//for number "1" it's neither prime nor
compositeif(num==1)
printf("\n1 is neither prime nor
composite");else
{
if(flag==0)
printf("\n%d is Prime Number.\n\n",
n);else
printf("\n%disnotaPrimeNumber.\n\n",n);
}
break;

//For Odd-even
blockcase3:

printf("Enter an integer:
");scanf("%d",
&num);n=num;

if(num%2==0)
printf("\n%d is Even Number.\n\
n",n);else
printf("\n%d is Odd Number.\n\
n",n);break;

//For Exit
blockcase
4:printf("\
nExit");
49|Page
break;
}
}
return0;
}

Output:
1. a^b
2. Primeornot
3. Oddoreven
4. Exit
Enter your
choice:1Entera:2
Enter
b:3a^b:8
1. a^b
2. Primeornot
3. Oddoreven
4. Exit
Enter your
choice:2Enter an
integer: 55is
PrimeNumber.
1. a^b

2. Primeornot
3. Oddoreven
4. Exit
Enter your
choice:3Enter an
integer: 55is Odd
Number.
1. a^b
50|Page
2. Primeor not

51|Page
3. Oddoreven
4. Exit
Enter your
choice:4Exit

52|Page
25. Iftwointegersareenteredthroughthekeyboard,WAPtoobtai
nthe primefactorsof thisnumber. (usingrecursivefunction)
Input:
#include<stdio.h>
int prime(int
num);int main()
{
intnum;

printf("Enter an integer:
");scanf("%d",&num);
printf("The Prime Factors of %d are:
",num);prime(num);
}
intprime(intnum)
{
intx;for(x=2;x<=num;
x++)
{
if(num%x==0)
{
printf("%d,
",x);prime(num/
x);break;
}
}
return0;
}

Output:
Enteraninteger:12
ThePrimeFactors of12are:2, 2,3,

53|Page
26. Writeafunctionthatreceivesanintegerarrayandreturns
thesum,average,mean,modand standarddeviationof it.
Input:
#include<stdio.h>
void stand_devi(float, float, float, float, float, float*, float*, float*,
float*);intmain()
{
floata,b,c,d, e;
floatsum =0, avg =0,sd =0, vari=0;
printf("Enter 5 numbers\n");scanf("%f%f%f%f
%f", &a, &b, &c, &d, &e);stand_devi(a, b, c, d, e,
&sum, &avg, &vari, &sd);printf("\nSum= %0.2f\
n", sum);
printf("Mean / Average = %0.2f\n",
avg);printf("Variance = %0.2f\n",
vari);printf("StandardDeviation=%0.2f\
n",sd);

return0;
}
void stand_devi(float a, float b, float c, float d, float
e,float*sum,float*avg,float*v,float*sd)
{
*sum=a+b +c+d+e;

*avg=*sum / 5.0;
*v+=pow((a-*avg),2 );
*v+=pow( (b -*avg),2 );
*v+=pow((c-*avg),2 );
*v+=pow( (d -*avg),2 );

54|Page
*v+=pow((e-*avg),2 );

55|Page
*v =*v / 5.0;
*sd=
sqrt(*v);return0;
}

Output:
Enter5numbers
50
-5
14
122
41
Sum=222.00
Mean/
Average=44.40Variance
=1885.84StandardDeviation
=43.43

56|Page
27. Writeafunctiontocomputethegreatestcommon
deviser(GCD) and least common deviser (LCD) for any
given twonumbers.
Input:
#include<stdio.h>
int main()
{

int num1, num2, gcd, lcd, remainder, numerator,


denominator;printf("Entertwo numbers\n");
scanf("%d %d", &num1,
&num2);if(num1 >num2)
{
numerator =
num1;denominator=nu
m2;
}
else
{
numerator =
num2;denominator=nu
m1;
}
remainder = numerator %
denominator;while(remainder!=0)
{
numerator=
denominator;denominator=remainder
;
remainder=numerator%denominator;
}
57|Page
gcd=denominator;
lcd=num1 * num2 / gcd;

58|Page
printf("GCD of %d and %d = %d\n", num1, num2,
gcd);printf("LCD of %d and %d = %d\n", num1, num2,
lcd);retuen0;
}

Output:
Enter two
numbers30
40
GCDof30 and 40 =10
LCDof30 and 40 =120

59|Page
28. A6x6matrixisenteredthroughthekeyboard,WAPtoobtainthede
terminantvalueofthismatrix.
Input:
#include<stdio.h>
int main()
{
int a[6][6], i,
j;longdeterminant;
printf("Enter the elements of matrix:
");for(i=0;i <6;i++)
for(j = 0;j < 6;j+
+)scanf("%d", &a[i]
[j]);printf("\nThe matrix is\
n");for(i=0;i <6; i++)
{

printf("\n");
for(j = 0;j < 6; j+
+)printf("%d\t",a[i]
[j]);
}
determinant=a[0][0]* ((a[1][1]*a[2][2])- (a[2][1]*a[1][2]))-a[0][1]*(a[1][0]*a[2][2]-
a[2][0]*a[1][2])+a[0][2]*(a[1][0]* a[2][1]- a[2][0]* a[1][1]);
printf("\nDeterminant of 6X6 matrix: %ld",
determinant);return0;
}

Output:
Entertheelements of matrix:6 6 2 8 4 01 7 3 9 5 1 2 8 4 0 6 2 3 9 5 1 7 3 4 0 6 2 8 4
517395
Thematrix is
60|Page
6 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
8 9 0 1 2 3
4 5 6 7 8 9
0 1 2 3 4 5

Determinantof6X6matrix:24

61|Page
29. Enter 3 matrices of order p*q and multiply
them.Note: Every matrix order p and q should be
random.Input:
#include
<stdio.h>int
main()
{
int m, n, p, q, c, d, k, sum=0;
intfirst[10][10],second[10][10],multiply[10][10];
printf("Enter the number of rows and columns of first matrix\
n");scanf("%d%d",&m, &n);
printf("Entertheelementsoffirstmatrix\n");

for (c = 0 ; c < m ; c+
+ )for ( d = 0 ; d < n ; d+
+ )scanf("%d",&first[c]
[d]);
printf("Enter the number of rows and columns of second matrix\
n");scanf("%d%d",&p, &q);
if(n!=p )
printf("Matrices with entered orders can't be multiplied with each other.\
n");else
{
printf("Enter the elements of second matrix\
n");for(c=0 ; c<p ; c++ )
for ( d = 0 ; d < q ; d+
+ )scanf("%d", &second[c]
[d]);for(c=0 ; c<m ; c++)
{

62|Page
for(d =0 ; d<q ; d++ )

63|Page
{
for(k =0 ; k<p ; k++)
{
sum=sum+first[c][k]*second[k][d];
}
multiply[c][d] =
sum;sum =0;
}

}
printf("Product of entered matrices:-\
n");for(c=0 ; c<m ;c++)
{
for ( d = 0 ; d < q ; d+
+ )printf("%d\t", multiply[c]
[d]);printf("\n");
}
}
return0;
}

Output:
Enter the number of rows and columns of first matrix 3
3Entertheelements of first matrix
120
011
201
Enter the number of rows and columns of second matrix 3
3Entertheelements of second matrix
112
211
121
Productofenteredmatrices:-
5 3 4
3 3 2
3 4 5

64|Page
30. Perform the appropriate operation of addition,
subtractionmultiplication or division as input by the user on
two integernumbers.Makeuseofswitchstatement.
Input:
#include<stdio.h>
int main()
{

int
a,b;int
op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\
n");printf("Enterthe valuesof a& b: ");
scanf("%d
%d",&a,&b);printf("Enter
your Choice :
");scanf("%d",&op);
switch(op)
{
case1:
printf("Sum of %d and %d is :
%d",a,b,a+b);break;
case2:
printf("Difference of %d and %d is : %d",a,b,a-
b);break;
case3:
printf("Multiplication of %d and %d is :
%d",a,b,a*b);break;
case4:
printf("Division of Two Numbers is %d :
",a/b);break;
65|Page
default :

66|Page
printf(" Enter Your Correct
Choice.");break;
}
return0;
}

Output:
1.Addition2.Su
btraction3.Multi
plication4.Divis
ion
Enter the values of a & b:20
15Enteryour Choice: 1
Sumof 20 and 15is : 35

67|Page
31. Inputaparagraphfromthekeyboardandprintnumberofvowe
land consonantinit.
Input:
#include
<stdio.h>int
main()
{
chars[1000];
int
i,vowels=0,consonants=0;pri
ntf("Enterthe string :
");gets(s);
for(i=0;s[i];i++)
{
if((s[i]>=65&&s[i]<=90)||(s[i]>=97&&s[i]<=122))
{
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'
||
s[i]=='U')vow
els+
+;elseconsona
nts++;
}
}
printf("vowels = %d\
n",vowels);printf("consonants = %d\
n",consonants);return0;
}

Output:
Enter the string : hello
68|Page
worldvowels= 3
consonants=7

69|Page
32. Printthe Fibonacciseriesupto firstn
terms,thevalueofntobeinputbytheuser.(UseRecursion)
Input:
#include<stdio.h>
int main()
{
int n,i =0, c;
printf(" Enter Fibonacci series\
n :");scanf("%d",&n);
for(c=1 ; c<=n ; c++)
{
printf("%d\n",
Fibonacci(i));i++;
}
return0;
}
intFibonacci(intn)
{
if ( n == 0
)return0;
else if ( n == 1
)return1;
else
return(Fibonacci(n-1)+Fibonacci(n-2));
}

Output:
Enter Fibonacci series :
50
1
1
2
3

70|Page
33. Printfollowingpatternsusingloops:

Input:
(1)
#include
<stdio.h>int
main()
{

int i,j,rows;
printf("Enter the number of rows:
");scanf("%d",&rows);
for (i = 1; i <= rows; ++i)
{for (j = 1; j <= i; ++j)
{printf("*");
}
printf("\n");
}
return0;
}

Output:
Enternumberofraw:3
*

71|Page
**

72|Page
** *

(2)
#include<stdio.h>
int main()
{
int n,r, c,s;
printf("Enter number of rows:
");scanf("%d",&n);for(r=1;r<=n;
r++)
{

for(s=1;s<=n-r;s+
+)printf("*");for(c=
1;c<=r;c+
+)printf("*");
printf("\n");
}
return0;
}

Output:
Enternumberofraw:3
*
**
***

(3)
#include<stdio.h>
int main()
{
int i,j,n,a;
printf("progran to print the patten\n enter the no of
rows :");scanf("%d",&n);
a=1;

73|Page
for(i=1;i<=n;i++)
{
for(j=n;j>=i;j--)
{
printf(" %c
",a+64);a++;
}
printf("\n");
}
return0;
}

Output:
Program to print the
patternEnterno of raw : 3
AB
CD E
F

(4)
#include
<stdio.h>int
main()
{
inti, space,rows,k= 0;printf("Enter
the number of rows:
");scanf("%d",&rows);
for(i =1; i <=rows; ++i, k =0)

{
for(space=1; space <=rows -i; ++space)
{
printf("*");
}
while(k !=2 * i -1)
{
printf("*");

74|Page
++k;
}
printf("\n");
}
return0;
}

Output:
Enter thenumberof raw:3
*
***
*****

(5)
#include
<stdio.h>int
main()
{
int n,c, k;
printf("Enter number of rows\
n");scanf("%d",&n);
for(k=1; k<=n; k++)
{
for (c = 1; c <= n-k; c+
+)printf("");

for (c = 1; c <= 2*k-1; c+


+)printf("*");
printf("\n");
}
for(k=1; k<=n -1; k++)
{
for (c = 1; c <= k; c+
+)printf("");

for (c = 1 ; c <= 2*(n-k)-1; c+


+)printf("*");
printf("\n");
}

75|Page
return0;
}
Output:
Enterthenumberofraw:5
*
***
*****
***
*

(6)
#include<stdio.h>
int main()
{
int i,j,n,a;
printf("program to print the patten\n enter the no of
rows :");scanf("%d",&n);
a=1;
for(i=1;i<=n;i++)
{
for(j=i;j>=1;j--)
{
printf(" %d
",a);a++;
}

printf("\n");

}
for(i=1;i<=n-1;i++)
{
for(j=n-1;j>=i;j--)
{
printf(" %d
",a);a++;

76|Page
}
printf("\n");
}
return0;
}

Output:
Program to print the
patternEnterno of raw: 3
1
23
456
78
9

(7)
#include
<stdio.h>int
main()
{
int rows, coef = 1, space, i,
j;printf("Enter the number of rows:
");scanf("%d",&rows);
for(i =0; i<rows; i++)
{
for (space = 1; space <= rows - i; space+
+)printf("");
for(j =0; j<=i; j++)
{
if (j == 0 || i ==
0)coef=1;
else
coef = coef * (i - j + 1) /
j;printf("%4d",coef);
}
printf("\n");
}

77|Page
return0;

78|Page
}
Output:

1
1 1
12 1
1 3 3 1
1 4 64 1
15 10 105 1

(8)
#include<stdio.h>
int main()
{
inti,j,k,n,a=1;
printf("\n program to print pattern\
n");printf("enter the number of rows u want\
n");scanf("%d",&n);
for(i=0;i<n;i++)
{
for(k=n;k>i;k--)
{
printf("");
}
for(j=0;j<=i;j++)
{
printf("
%d",a);a
++;
}
printf("\n");
}
for(i=1;i<n;i++)
{
for(j=0;j<=i;j++)
{
printf("");
}
for(k=n;k>i;k--)
{

79|Page
printf("
%d",a);a++;
}

printf("\n");
}
return0;
}

Output:
Program to print the
patternEnterno of raw: 3
1
23
45 6
78
9

(9)
#include<stdio.h>
int main()
{
int i,j,k,n,a=0;
printf("\n program to print pattern\
n");printf("enter the number of rows u want\
n");scanf("%d",&n);
for(i=1;i<=n;i++)

{
for(j=i;j<=n-1;j++)
{
printf("");
}
for(k=0;k<2*i-1;k++)
{
printf("
%c",a+65);a+
+;
}
printf("\n");
}

80|Page
for(i=n-1;i>=1;i--)
{
for(j=i;j<=n-1;j++)
{
printf("");
}
for(k=0;k<2*i-1;k++)
{
printf("%c",a+65);
a++;
}
printf("\n");
}
return0;
}

Output:
Program to print the
patternEnternoof rawu
want:3
AB
CD
EFGH
IJ K
LM

81|Page
34. WAP to copy the contents of one array into another array
inthereverseorder.
Input:
#include<stdio.h>
int main()
{
int ar1[5]={10,20,30,40,50 },ar2[5],i;
//copying
elementsfor(i=4;i>=0
;i--)
ar2[i]=ar1[4 -i];
//displayingarrayfor
(i = 0; i < 5; i+
+)printf("%d ",
ar2[i]);return0;
}

Output:
50 40 30 20 10

82|Page
35. Findthesmallestnumberinanarrayusingpointers.Inp
ut:
#include<stdio.h>
#defineN 5
intmain()
{
int a[N],i,*small;
printf("Enter %d integer numbers\n",
N);for(i=0; i <N; i++)
scanf("%d",
&a[i]);small=&a[0]
;
for(i=1;i <N;i++)
{
if(*(a+i) <*small)
*small=*(a+i);
}
printf("Smallest Element In The Array: %d\n",
*small);return0;
}

Output:
Enter5integernumbers5
2
6
4
3
SmallestElementInTheArray:2

83|Page
36. WAPto findif
ann*nsquarematrixissymmetric.Input:
#include<stdio.h>
int main()
{
int a[10][10],i,j,n;
printf("Enter order of square matrix:
");scanf("%d",&n);
for(i =1;i <=n;i++)
{
for(j =1;j <=n;j++)
{
printf("Entervalueof a[%d][%d]:", i,j);
scanf("%d\t",&a[i][j]);
}
}
for(i =1;i <=n;i++)
{
for(j =1;j <=n;j++)
{
if(a[i][j]!= a[j][i])
{
printf("\n\nMatrixisnotsymmetric");
}
}
}
printf("\n\nMatrix is
symmetric");return0;
}

84|Page
Output:
Enter order of square matrix:
2Enter value of a[1][1] :
34Enter value of a[1][2] :
34Enter value of a[2][1] :
34Entervalue of a[2][2]: 34

85|Page
37. Evaluatethegivenserieswithoutusing
anylibraryfunctions,thevaluesof xandntobeinput bytheuser.
1) 1 +x 2 +x 3+x 4 +……+x n .
2) 1/1!+1/2! +1/3!+...............1/n!.
3)1/1!+x 2 /2! +x 3 /3! +x 4 /4! +……+x n /n!.

Input:
//1 + x 2 + x 3 + x 4 +……+ x
n .#include<stdio.h>
// Function to print the sum of the
seriesdoublesum(intx, intn)
{
doublei, total =1.0, multi=x;
// First Term of
seriesprintf("1");

// Loop to find the N terms of the


seriesfor(i =1; i <n; i++)
{
total = total +
multi;printf("%.1f ",
multi);multi= multi *
x;
}
printf("\
n");returnto
tal;
}
// Driver
Codeint

86|Page
main()
{
intx =2;

87|Page
intn =5;
printf("%.2f", sum(x,
n));return0;
}

Output:
1 2.0 4.0 8.0 16.0
31.00

Input:
//1/1!+1/2! +1/3!+...............1/n!.
#include<stdio.h>
int main()
{
int j,i,n,f;
double
sum=0.0;printf("Enter last
element:\
n");scanf("%d",&n);for(i=1;i<
=n;i++)
//loopforadding elementsofseries
{
if(i!
=n)printf("1/%d!
+",i);elseprintf("1/
%d!=",i);f=1;
for(j=1;j<=i;j++)
//loopforfindingfactorial
{

88|Page
f=f*j;
}
sum=sum+(1.0)/f;
}
printf("%lg",sum);
return0;
}

Output:
Enter last element : 51/1!+1/2!
+1/3!+1/4!+1/5!=1.71667

Input:
//1/1! + x 2 /2! + x 3 /3! + x 4 /4! +……+ x n
/n!.#include<stdio.h>
// C code to print the sum of the
seriesdoublesum(intx, intn)
{
double i, total = 1.0, multi =
x;for(i =1; i <=n; i++)
{

total = total + multi /


i;multi= multi * x;
}
returntotal;
}
// Driver
codeint
main()
{

89|Page
int x =
2;intn=5;
printf("%.2f", sum(x,
n));return0;
}

Output:
18.07

90|Page
38. WAP to find if the year entered by the user is leap year
ornot.(Yearinbetween1to9999).
Input:
#include
<stdio.h>int
main()
{
intyear;
printf("Enter a year:
");scanf("%d",&year);
// leap year if perfectly divisible by
400if(year%400 ==0)
{
printf("%disaleapyear.",year);
}
//not a leapyear if divisibleby 100
// but not divisible by
400elseif(year%100==0)
{
printf("%disnotaleap year.",year);
}
//leap yearifnotdivisible by100
//butdivisible by4
else if (year % 4 == 0)
{printf("%disaleapyear.",year);
}
// all other years are not leap
yearsElse
{

91|Page
printf("%disnotaleap year.",year);

92|Page
}
return0;
}

Output:
Output1:
Enter a year:
99999999isnotaleapye
ar.

Output2:
Enter a year:
20242024isaleapyear.

93|Page
39.WAPtoinputcharactersfromthekeyboard.Findhowmanyof
these characters are alphabets, how many are digits and
howmanyarespecialcharacters.
Input:
#include
<stdio.h>int
main()
{

chars[1000];
int i,alphabets=0,digits=0,special
characters=0;printf("Enterthe string :");
gets(s);for(i=0;s
[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 &&
s[i]<=122) )alphabets++;
else if(s[i]>=48 &&
s[i]<=57)digits++;
else
specialcharacters++;

}
printf("Alphabets = %d\
n",alphabets);printf("Digits= %d\
n",digits);
printf("Special characters = %d", special
characters);return0;
}

Output:
Enter the string:
rukhsana2502@Alphabets=8
94|Page
Digits=4
Specialcharacters=1

95|Page
40. WAP to print all the prime numbers between 1 and
10000.Input:
#include
<stdio.h>int
main()
{
int i,Number,count;
printf(" Prime Number from 1 to 1000 are: \
n");for(Number=1;Number<=1000;Number++)
{
count=0;
for(i =2; i<=Number/2;i++)
{
if(Number%i ==0)
{
count+
+;break;
}
}
if(count==0&& Number!=1)
{
printf("%d",Number);
}
}
return0;
}

Input:
Primefrom 1to 1000are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,

96|Page
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,

97|Page
197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,
523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757,
761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881,
883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997.

98|Page
41.Writeprogramsforfollowingsorting’s:
1) Bubblesort or exchangesort
2) Selectionsort
3) Insertionsort

Input:
(1) // Bubble sort or exchange
sort#include<stdio.h>
intmain()
{
int array[100], n, i, j,
swap;printf("Enter number of
elements n:");scanf("%d",&n);
printf("Enter %d Numbers n:",
n);for(i=0; i <n; i++)
scanf("%d",
&array[i]);for(i=0;i<n-
1;i++)
{
for(j=0; j<n-i-1;j++)
{
if(array[j]>array[j+1])
{
swap=array[j];array[j]=a
rray[j+1];array[j+1]=sw
ap;
}
}
}
printf("SortedArray:n");

99|Page
for(i = 0; i < n; i+
+)printf("%dn",
array[i]);return0;
}

Output:
Enter number of elements n:
2Enter2 numbern: 0
1

SortedArray:n0n1 n

Input:
(2) // Selection
sort#include
<stdio.h>int
main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
inti,j,position,swap;for(i
=0;i<(n -1);i++)
{
position=i;
for(j =i +1; j <n; j++)
{
if (arr[position] >
arr[j])position =j;
}
if(position !=i)
{

100|Page
swap=arr[i];

101|Page
arr[i] =
arr[position];arr[posi
tion]=swap;
}
}
for (i = 0; i < n; i+
+)printf("%d\t",
arr[i]);return0;
}

Output:
0 2 6 11 12 18 34 45 55 99

Input:
(3) // Insertion
sort#include
<stdio.h>int
main()
{
int n, array[1000], c, d, t, flag =
0;printf("Enter number of elements\
n");scanf("%d",&n);
printf("Enter %d integers\n",
n);for (c = 0; c < n; c+
+)scanf("%d",&array[c]);
for(c=1; c<=n -1; c++)
{
t=array[c];
for(d=c-1 ; d >=0; d--)
{

102|Page
if(array[d] >t)
{

103|Page
array[d+1] =
array[d];flag=1;
}
elsebr
eak;
}
if
(flag)array[d+1]
=t;
}
printf("Sorted list in insertion order:\
n");for(c=0; c<=n -1; c++)
{
printf("%d\n",array[c]);
}
return0;
}

Output:
Enter number of
elements3
Enter3integers
1
0
4
Sorted list in insertion
order0
1
4

104|Page
42. WAP to search an element in an unsorted list of
elementsusing linear search. And also apply in sorted list of
elements(Makeuseofswitchstatement).
Input:
#include
<stdio.h>int
main()
{

intarray[100],search,c,n;
printf("Enter number of elements in array\
n");scanf("%d",&n);
printf("Enter %d integer(s)\n",
n);for (c=0;c<n;c+
+)scanf("%d",&array[c]);
printf("Enter a number to search\
n");scanf("%d",&search);
for(c=0;c<n; c++)
{
if(array[c]==search)
/*If requiredelementisfound */
{

printf("%d is present at location %d.\n", search,


c+1);break;
}
}
if(c==n)
printf("%d isn't present in the array.\n",
search);return0;
}

105|Page
Output:
Enter number of element in
array2
Enter2integer(s)
2
4
Enter number to
search4
4ispresentatlocation 2.

106|Page
43. WAP to search an element in an unsorted list of
elementsusingbinarysearch.
(Beforeapplyingbinarysearch,firstsortthe
elements).
Input:
#include
<stdio.h>int
main()
{
intarray[10];
int i, j, num, temp, key
num;int low, mid, high;
printf("Enter the value of num \
n");scanf("%d",&num);
printf("Enter the elements one by one \
n");for(i =0; i <num; i++)
{
scanf("%d",&array[i]);
}
printf("Input array elements \
n");for (i = 0; i < num; i+
+)printf("%d\n",array[i]);
}
/* Bubble sorting begins
*/for(i =0; i <num; i++)
{

for(j =0; j<(num -i- 1);j++)


{
if(array[j] >array[j+1])

107|Page
{
temp=array[j];

108|Page
array[j] = array[j +
1];array[j+1] =temp;
}
}
}
printf("Sorted array is...\
n");for(i =0; i <num; i++)
{
printf("%d\n",array[i]);
}
printf("Enter the element to be searched \
n");scanf("%d",&keynum);
/* Binary searching begins
*/low=1;
high =
num;do
{

mid=(low+high) /2;
if (keynum <
array[mid])high =mid -1;
else if (keynum >
array[mid])low=mid +1;
}
while (keynum != array[mid] && low <=
high);if(keynum ==array[mid])
{
printf("SEARCHSUCCESSFUL\n");
}
Else

109|Page
{
printf("SEARCHFAILED\n");
}
}

Output:
1. Enter the value of
num6
Enter the elements one by
one1
2
3
4
5
6
Input array
elements1
2

3
4
5
6
Sortedarrayis...
1
2
3
4
5
6

110|Page
Enter the element to be
searched6
SEARCHSUCCESSFUL

2. Enter the value of


num5
Enter the elements one by
one1
3
6
8
9
Input array
elements1
3
6
8
9
Sortedarrayis...
1
3
6
8
9
Enter the element to be
searched4
SEARCHFAILED

111|Page
44. Printthe transposeofamatrixinputbythe

user.Input:
#include<stdio.h>
int main()
{
int a[10][10], transpose[10][10], r,
c;printf("Enter rows and columns:
");scanf("%d %d", &r, &c);
// asssigning elements to the
matrixprintf("\nEnter matrix
elements:\n");for(int i =0; i <r; ++i)
for(int j =0; j <c;++j)
{
printf("Enter element a%d%d: ", i + 1, j +
1);scanf("%d",&a[i][j]);
}
// printing the matrix a[]
[]printf("\nEntered matrix: \
n");for(int i =0; i <r; ++i)
for(int j =0; j <c;++j)

{
printf("%d", a[i]
[j]);if (j == c -
1)printf("\n");

}
// computing the
transposefor (int i = 0; i <
r; ++i)for(int j =0; j <c; +
+j)

112|Page
{

113|Page
transpose[j][i]=a[i][j];
}

// printing the transposeprintf("\


nTranspose of the matrix:\n");for(int i
=0; i <c; ++i)
for(int j =0; j <r;++j)
{
printf("%d", transpose[i]
[j]);if(j ==r-1)
printf("\n");
}
return0;
}

Output:
Enter rows and columns:
23

Enter matrix
elements:Enter
element a11: 1Enter
element a12: 4Enter
element a13: 0Enter
element a21: -5Enter
element a22:
2Enterelementa23: 7

Enteredmatrix:
140
-527

Transposeofthematrix:
1 -5
4 2
0 7

114|Page
45.WAP to merge 2 sorted 1D
array.Input:
#include
<stdio.h>voidsort(intc
[],intn3)
//Functiontosorttheelementsofthearray
{
for(inti=0;i<n3;i++)
{
int temp;
for(intj=i+1;j<n3;j++)
{
if(c[i]>c[j])
{
temp=c[i];
c[i]=c[j];c
[j]=temp;
}
}
}
}
intmain()
{
int n1,n2,n3;
//Arraysizedeclaration
printf("\nEnter the size of first array
");scanf("%d",&n1);
printf("\nEnter the size of second array
");scanf("%d",&n2);

n3=n1+n2;
printf("\nEnter the array
elements");int a[n1],b[n2],c[n3];
//Array
Declarationfor(inti=0;i
<n1;i++)
//ArrayInitialization
{
scanf("%d",&a[i]);
}
sort(a,n1);
//Function call to sort the
arrayint k=n1;
printf("\nEnter the array
115|Page
elements");for(inti=0;i<n2;i++)

116|Page
//ArrayInitialization
{
scanf("%d",&b[i]);
}
sort(b,n2);
//
Functioncalltosortthearrayfor(int
i=0;i<n1;i++)
//Mergetwoarrays
{
c[i]=a[i];
}
for(intj=0;j<n2;j++)
{
c[k]=b[j];
k++;
}
printf("\nAfter sorting...\
n");sort(c,n3);
//
Functioncalltosortthearrayfor(int
i=0 ;i<n3 ;i++)
//Printtheresultantsortedarray
{
printf("%d",c[i]);
}
return0;
}

Output:
Enter the size of first array
5Enterthesizeofsecondarray5
Enterthesortedarray elements 54 32 1
Enter the sorted array elements 9 8 7 6
5Themergedarray..
1234598765
Aftersorting...
9876554321

117|Page
46. WAPtoswapthevaluesusingcallbyvaluemethod.Inpu
t:
#include<stdio.h>
voidchange(int num)
{
printf("Before addingvalueinsidefunctionnum=%d\n",num);
num=num+100;
printf("Afteradding valueinsidefunctionnum=%d\n",num);
}
intmain()
{
int x=100;
printf("Beforefunction callx=%d \n",x);
change(x);
//passingvalueinfunction
printf("Afterfunctioncallx=%d \n",x);
return0;
}

Output:
Beforefunctioncallx=100
Before adding value inside function
num=100After adding value inside function
num=200Afterfunction call x=100

118|Page
47.WAP to swap the values using call by reference
method.Input:
#include<stdio.h>void
change(int*num)
{
printf("Before adding value inside function num=%d \n",*num);
(*num)+=100;
printf("Afteraddingvalue insidefunction num=%d \n",*num);
}
intmain()
{
int x=100;
printf("Before function call x=%d \n",
x);change(&x);
//
passingreferenceinfunctionprintf("After
function call x=%d \n", x);return0;
}

Output:
Beforefunctioncallx=100
Before adding value inside function
num=100After adding value inside function
num=200Afterfunction call x=200

119|Page
48.WAPtosolvetheAckerman
functionusingrecursion.Input:
#include
<stdio.h>intack(int
m,intn)
{
if(m==0)
{
returnn+1;
}
elseif((m >0) &&(n ==0))
{
returnack(m-1,1);
}
elseif((m>0) &&(n>0)){
returnack(m-1,ack(m, n-1));
}
}
intmain()
{
int A;
A=ack(1,2);
printf("%d",
A);return0;
}

Output:
4

120|Page
49.WAP for merge
sort.Input:
#include<stdio.h>
voidmerge(int arr[],intstart,int mid,int end)
{
int len1 = mid - start +
1;int len2 =end -mid;

intleftArr[len1],rightArr[len2];

for (int i = 0; i < len1; i+


+)leftArr[i] = arr[start +
i];for(intj=0;j<len2;j++)
rightArr[j] =arr[mid+ 1+j];

int i, j,
k;i=0;
j=0;
k=start;

while(i <len1 && j<len2)


{
if(leftArr[i]<=rightArr[j])
{
arr[k] =
leftArr[i];i++;
}
else
{
arr[k] =
rightArr[j];j++;
}
k++;
}

while(i <len1)
{
arr[k] =
leftArr[i];i++;
k++;
}

while(j <len2)

121|Page
{
arr[k] =
rightArr[j];j++;
k++;
}
}

voidmergeSort(int arr[],int start,intend)


{
if(start <end)
{

int mid = start + (end - start) /


2;mergeSort(arr, start,
mid);mergeSort(arr, mid + 1,
end);merge(arr,start,mid, end);
}
}
voiddisplay(int arr[],intsize)
{
for (int i = 0; i < size; i+
+)printf("%d ",
arr[i]);printf("\n");
}
intmain()
{
int arr[] ={6,5, 12, 10,9, 1};
intsize=sizeof(arr)/sizeof(arr[0]);

printf("Original array\
n");display(arr,size);

mergeSort(arr,0,size - 1);

printf("Sorted array\
n");display(arr,size);
}

Output:
Original
array6 5 12
10 9 1
Sorted
array156910

122|Page
12

123|Page
50.WAP for quick
sort.Input:
#include<stdio.h>
void
quick_sort(int[],int,int);intpa
rtition(int[],int,int);
intmain()
{
inta[50],n,i;
printf("How many
elements?");scanf("%d",&n);
printf("\nEnter array
elements:");for(i=0;i<n;i+
+)scanf("%d",&a[i]);quick_sort(
a,0,n-1);printf("\nArray after
sorting:");for(i=0;i<n;i++)
printf("%d
",a[i]);return0;
}

voidquick_sort(int a[],int l,int u)


{
intj;if(
l<u)
{
j=partition(a,l,u);qu
ick_sort(a,l,j-
1);quick_sort(a,j+1,
u);
}
}

int partition(int a[],int l,int u)


{
int
v,i,j,temp;v=
a[l];
i=l;j=u
+1;do
{
doi
++;
while(a[i]<v&&i<=u);
do
124|Page
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];a
[j]=temp;
}
}
while(i<j);
a[l]=a[j];a
[j]=v;retur
n(j);
}

Output:
Howmanyelements6?
Enterarray elements:12 711 9 315
Arrayaftersorting=357 91112

125|Page
51.WAP that converts a string like “124” to an integer
124Input:
#include
<stdio.h>int
main()
{
charstr[100];
inti, num, fin=0;
printf("Enter a string of numbers :
");getchar();
for(i =0;str[i]!='\0'; i++)
{
num=str[i]-48;
fin=fin*10 +num;
}
printf("\nNumber : %d",
fin);return0;
}

Output:
Enter a string of numbers :
4Number:4369

126|Page
52.WAPtosortasetof namesstoredinanarrayinalphabeticalorder.
Input:
#include<stdio.h>
int main()
{
inti,j,n;
char str[100]
[100],s[100];printf("Enter number
of names :\n");scanf("%d",&n);
printf("Enter names in any order:\
n");for(i=0;i<n;i++)
{
scanf("%s",str[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(s,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],s);
}
}
}
printf("\nThe sorted order of names are:\
n");for(i=0;i<n;i++)
{
printf("%s\n",str[i]);
}
}
Output:
Enter number of
names:2
Enter names in any
order:Nazim
Haroon
The sorted order of names
is:Haroon
Nazim

127|Page
53.WAPprogramtofindday
ofagivendate.Input:
#include<stdio.h>
int main()
{
int month[12] ={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
charweek[7][10];
int date,mon, year,i, r,s=0;

strcpy(week[0],"Sunday");
strcpy(week[1],"Monday");

strcpy(week[2],
"Tuesday") ;strcpy(week[3],
"Wednesday") ;strcpy(week[4],
"Thursday") ;strcpy(week[5],
"Friday") ;strcpy(week[6],"Satu
rday") ;
printf("Enter a valid date (dd/mm/yyyy) :
") ;scanf("%d/%d/%d",&date,&mon,&year);
if( (year % 400 == 0) || ((year % 4 == 0) && (year % 100 !=
0)) )month[1]=29 ;
for(i = 0 ; i < mon - 1 ; i+
+)s=s +month[i] ;
s = s + (date + year + (year / 4) -
2) ;s =s %7 ;
printf("\nThe day is : %s",
week[s]) ;return0;
}

Output:
Enter a valid date (dd/mm/yyyy):
25/02/2002Theday is : Monday

128|Page
54. WAPforstrcpy,strlen,strrev,strcmpwithoutusingpre
defined functions.
Input:
(Strcpy)#include<
stdio.h>int main()
{

char source[] = "C

Program";char

destination[50];strcpy(destin

ation,source);

printf("Source string: %s\n",

source);printf("Destinationstring:%s\

n",destination);

return0;
}
Output:
Source string: C
ProgramDestinationstring:CProgr
am

(Strlen)#include<
stdio.h>int main()
{

char arr[] = "Manish"

;int len1;

len1=strlen(arr) ;

printf("Length ofstring=%d",len1) ;

return0;
}
Output:
Lengthof string= 6

(Strrev)
129|Page
#include
<stdio.h>int
main()

130|Page
{

chars[100];

printf("Enter a string to reverse\

n");gets(s);

strrev(s);

printf("Reverseof thestring: %s\n", s);

return0;
}

Output:
Enter a string to
reverse24
Reverseofthestring:
42

(Strcmp)#include
<stdio.h>int
main()
{

char string1[ ] = "Jerry"

;char string2[ ] = "Ferry"

;int i,j,k;

i = strcmp ( string1, "Jerry"

) ;j =strcmp ( string1, string2

);

k=strcmp ( string1, "Jerry boy");

printf("%d %d %d",i, j,k ) ;


}

Output:
01 -1

131|Page
55.WAPtofind the numberof wordsinalineof text.
(UsingString)
Input:
#include
<stdio.h>int
main()
{
chars[200];
int count = 0,
i;printf("Enter the string:\
n");scanf("%[^\n]s",s);
for(i =0;s[i] !='\0';i++)

{
if (s[i] == ' ' && s[i+1] != '
')count++;
}
printf("Number of words in given string are: %d\n", count +
1);return0;
}

Output:
Enter thestring:12
Numberofwords ingiven string are:1

132|Page
56. WAP to check if a string is a
palindrome.Input:
#include
<stdio.h>int
main()
{

chara[100],b[100];
printf("Enter a string to check if it's a palindrome\
n");gets(a);
strcpy(b,
a);strrev(b);
if(strcmp(a, b)==0)
printf("The string is a palindrome.\
n");else
printf("The string isn't a palindrome.\
n");return0;
}

Output:
Enter a string to check if it's a
palindromeWow
Thestringis apalindrome.

Enter a string to check if it's a


palindrome12
Thestringisn'tapalindrome.

133|Page
57. WAP to sort a list of names in the ascending order of length
ofthenames.
Input:
#include<stdio.h>
int main()
{
int i,j,count;
charstr[25][25],temp[25];
puts("How many strings u are going to enter?:
");scanf("%d",&count);
puts("Enter Strings one by one:
");for(i=0;i<=count;i++)
gets(str[i]);for(i=0;i<=c
ount;i+
+)for(j=i+1;j<=count;j+
+)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted
Strings:");for(i=0;i<=count;i++)
puts(str[i]);
return0;
}

Output:
How many strings u are going to enters?
3
Enter string one by
one:manno
NazimHa
roon
Order of Sorted
Strings:Haroon
NazimMa
nno

134|Page
58.WAP to illustrate the scope of local and global variable
havingthesamename.
input:
#include<stdio.h>
/* global variable declaration
*/intg =20;

intmain()
{

/* local variable declaration


*/intg=10;

printf("valueof g=%d\n", g);

return0;
}

Output:
valueofg =10

135|Page
59. WAPtoillustratetheuseofstaticvariables.Inp
ut:
#include<stdio.h>
int fun()
{
static int count =
0;count++;
returncount;
}

intmain()
{
printf("%d",fun());
printf("%d ",
fun());return0;
}

Output:
12

136|Page
60.WAP for accessing elements through pointer in a 1D
array.Input:
#include<stdio.h>
int main()
{
int my_arr[5] ={1, 2,3,4, 5},i;

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


{
printf("Value of a[%d] = %d\t", i,
my_arr[i]);printf("Addressof a[%d]=%u\
n",i,&my_arr[i]);
}

return0;
}

Output:
Value of a[0] = 1 Address of a[0] =
2293312Value of a[1] = 2 Address of a[1] =
2293316Value of a[2] = 3 Address of a[2] =
2293320Value of a[3] = 4 Address of a[3] =
2293324Valueofa[4]=5Addressofa[4]=2293
328

137|Page
61.WAP for accessing elements through pointer in a 2D
array.Input:
#include<stdio.h>
//accessing elements of 2D array using
pointersint main()
{

intarr[4][4]={{1,2,3,4},{5,6,7,8},{9,0,1,2}};
int *ptr=&arr;

//accessing the elements of 2D array using


ptrfor(inti=0;i<3;i++)
{
for(int j=0;j<4;j+
+)printf("%d",*((ptr+i*4)+j
));
//4is thenumberof columns
//*((ptr+i*4)+j) is similar to arr[i]
[j]printf("\n");
}
return0;
}

Output:
1234
5678
9012

138|Page
62. WAP to show the memory allocation to the characters in
astring.
Input:
#include<stdio.h>

void *malloc(size_t

size);voidexemple(void)
{
char*string;

string = malloc(sizeof(char) *
5);if(string ==NULL)
return;string[0
]='H';
string[1]='e';
string[2]='y';
string[3]='!';
string[4] = '\
0';printf("%s\n",
string);free(string);
}

Output:
“Hey!”

139|Page
63.WAP to illustrate return of a pointer from a
function.Input:
#include<stdio.h>

// Function returning
pointerint*fun()
{
int A =
10;return(&A
);
}

// Driver
Codeint
main()
{
// Declare a
pointerint* p;

// Function
callp=fun();

printf("%p\n",p);
printf("%d\n",
*p);return0;
}

Output:
000000000000000

140|Page
64. WAP to read and display the elemnts of an array of
integers.Allocate memory to the array dynamically using
malloc(), calloc()andrealloc()functions.
Input:
#include
<stdio.h>int
main()
{
char
name[20];char
*address;

strcpy(name,"HarryLee");
address= (char*)malloc(50*sizeof(char));
/*allocatingmemorydynamically*/
strcpy(address,"Lee Fort,11-BSansStreet");

printf("Name = %s\n", name


);printf("Address: %s\n", address
);return0;
}
Output:
Name=Herry Lee
AddressLeeFort,11-BSansStreet

141|Page
65.WAP to create a structure to specify data on students
givenRollno,name,dept.,course,yearofjoining.Assumetherearenot
morethan450studentsinthecollege
a) Write a function to print names of all students who
joinedina particularyear.
b) Write a function to print the data of all students whose
rollnumberis given
c) Write a function to print names of all students who
areadmittedin a particulardepartment.
Input:
#include<stdio.h>
#defineN450

structstudents
{
intrlnm;
char
name[25];char
dept[25];
/* structure defined outside of main();
*/charcourse[25];
intyear;
};

intmain()
{
/*main()*/

struct students
s[N];int i,ch;

/* taking input of 450 students in an array of structure

*/for(i=0;i<N;i++)
{

printf("Enter data of student %d\t\t\t\ttotal students: %d\


n",i+1,N);printf("****************************\n\n");

printf("enter
rollnumber:");scanf("%d",&s[i].rlnm);

printf("\n\nenter
name:");scanf("%s",&s[i].n
ame);

printf("\n\nenter
department:");scanf("%s",&s[i].dept);
142|Page
printf("\n\nenter
course:");scanf("%s",&s[i].course);

printf("\n\nenter year of
joining:");scanf("%d",&s[i].year);
}

/* displaying a menu */printf("\n\

tenteryourchoice:\n");
printf("\t**********************\n\n");

printf("1: enter year to search all students who took admission in that:\n\
n");printf("2:enterroll number to seedetailsof that student\n\n\n");

printf("yourchoice:");
/* taking input of your choice
*/scanf("%d",&ch);

switch(ch)
{

case1:

dispyr(&s);
/* function call to display names of students who joined in\ a particular year
*/break;

case2:

disprl(&s); /* function call to display information of a student \


whoserollnumberis given */

break;d

efault:

printf("\n\nerror!wrongchoice");

return0;

}
/*******************main() ends **************/

dispyr(structstudents*a)
{
/* function for displaying names of students\
whotookadmissioninaparticularyear*/

143|Page
int j,yr;

printf("\nenter
year:");scanf("%d",&yr)
;

printf("\n\nthese students joined in %d\n\

n",yr);for(j=0;j<N;j++)
{

if(a[j].year==yr)
{

printf("\n%s\n",a[j].name);
}

}
return0;
}

disprl(structstudents *a) { /* function to print information of a\


studentwhoseroll number has been\
given.

*/int k,rl;

printf("\nenter roll number:


");scanf("%d",&rl);

for(k=0;k<N;k++)
{
if(a[k].rlnm==rl)
{

printf("\n\n\t Details of roll number: %d\


n",a[k].rlnm);printf("\
t***************************\n\
n");printf("Name:%s\n",a[k].name);
printf("Department: %s\
n",a[k].dept);printf("Course: %s\
n",a[k].course);printf("Yearofjoining:
%d",a[k].year);

break;
}

else
{
144|Page
printf("\nRollnumberyouentered doesnotexist\n\n");

145|Page
break;
}

return0;
}

Output:

Enterdata ofstudent1 total students: 450


*********************
Enterroll number:157
Enter name: Mohd
NazimEnter department:
EngineeringEntercourse: CSE
Enteryear ofjoining: 2020
.
.
.

Enterdata ofstudent450 total students: 450


*********************
Enterroll number:157
Enter name: Mohd
NazimEnter department:
EngineeringEntercourse: CSE
Enteryear ofjoining: 2020

Enteryourchoice:
******************
1: enter year to search all students who took admission in
that:2:enter roll numberto seedetails of that student\n\n\n"

Yourchoice:
error!Wrong choice

146|Page
66. Writeamenu
drivenprogramthatshowstheworkingofalibrary,themenuopti
onshouldbe:
a) Add book info
b) Displaybook info
c) Listall booksof givenauthor
d) Listthe titleofspecifiedbook
e) Listthe countof books inthelibrary
f) Listthe books in theorder ofaccession number.
g) Exit
Create a structure called library to hold accession number,
titleof the book, author name, price of the book and flag
indicatingwhetherbook is issued ornot.
Input:
#include<stdio.h#i
nclude<string.h>v
oidadd();
void
display();void
author();void
title();void
count();void
access();struct
book
{
int a;
//a=accessionnumber
char
name[30],title[30],flag[6];float
price;
}
b[100];
intd;
voidmain()
{
int i,n,c;
printf("Enter number of book\
n");scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter information of book no. %d\
n",i+1);printf("Accession number
");scanf("%d",&b[i].a);
147|Page
printf(" Name of author
");scanf("%s",b[i].name);p
rintf("Titleofbook");

148|Page
scanf("%s",b[i].title);printf("
Price
");scanf("%f",&b[i].price);pri
ntf("Issue status yes/no:
");scanf("%s",b[i].flag);
}
d=i;printf("****menu***
**");

printf("\n1. Add book information\n2. Display book information\n3. List all books of
givenauthor\n4. list the title of specified book\n5. List the count of books in the library\n6.
List thebooksin the order of accession number\n 7.Exit\n");
printf("Choose an option\
n");scanf("%d",&c);
while(c!=7)
{
if(c==1)a
dd();if(c
==2)disp
lay();
if(c==3)
author();if(c==4)t
itle();
if(c==5)
count();if(c==6)a
ccess();
if(c!=1 && c!=2 && c!=3 && c!=4 && c!=5 && c!
=6)printf("InvalidInput\nPleaseentervalidinput\n");
printf("1. Add book information\n2. Display book information\n3. List all books of
givenauthor\n4. list the title of specified book\n5. List the count of books in the library\n6.
List thebooksin the order of accession number\n 7.Exit\n");
printf("Choose an option\
n");scanf("%d",&c);
}
}
voidadd()
{
int i,n;
printf("Enter number of book added\
n");scanf("%d",&n);
for(i=d;i<n+d;i++)
{
printf("Enter information of additional book no. %d\n",i-
d+1);printf("Accessionnumber ");

149|Page
scanf("%d",&b[i].a);printf(
"Nameofauthor");

150|Page
scanf("%s",b[i].name);printf(
"Title of book
");scanf("%s",b[i].title);printf
("Price
");scanf("%f",&b[i].price);pri
ntf("Issue status yes/no:
");scanf("%s",b[i].flag);
}
d=d+n;
}
voiddisplay()
{
printf("Accession number Name title price issue status\
n");for(intj=0;j<d;j++)
printf("%d%s%s%f%s\n",b[j].a,b[j].name,b[j].title,b[j].price,b[j].flag);
}
voidauthor()
{
charA[30],j,c;
printf("Enter author name
");scanf("%s",A);
printf("Accession number Name title price issue status\
n");for(intj=0;j<d;j++)
{
c=strcmp(A,b[j].name);
if(c==0)
printf("%d%s%s%f%s\n",b[j].a,b[j].name,b[j].title,b[j].price,b[j].flag);
}
}
voidtitle()
{
char
t[30];int
c,i,j;
printf("Enter Title of a book
");scanf("%s",t);
for(i=0;i<d;i++)
{
c=strcmp(t,b[i].title);if(c
==0)
{
printf("AccessionnumberName titlepriceissuestatus\n");
printf("%d%s%s%f%s\n",b[i].a,b[i].name,b[i].title,b[i].price,b[i].flag);
}

151|Page
}

152|Page
}
voidcount()
{
printf("no.ofbooksinlibararyis%d\n",d);
}
voidaccess()
{
int
i,j,E[100],c[100],a;for
(i=0;i<d;i++)
{
E[i]=b[i].a;
c[i]=i;
}
for(i=0;i<d;i+
+)for(j=i;j<d;j+
+)if(E[i]>E[j])
{a=E[i
];
E[i]=E[j];
E[j]=a;
a=c[i];c[
i]=c[j];c[
j]=a;
}
printf("Accession number Name title price issue status\
n");for(j=0;j<d;j++)
printf("%d%s%s%f%s\n",b[c[j]].a,b[c[j]].name,b[c[j]].title,b[c[j]].price,b[c[j]].flag);
}
return0;
}

Output:
Enter numer of
book1
Enter information of book no.
1Accession number
234xxxxNameofauthor
Nazimnama
TitleofbookThe
nazimgreat
Issuestatusyes/no :yes

153|Page
****menu*****

154|Page
1. Addbookinformation
2. Displaybookinformation
3. Listallbooks ofgivenauthor
4. listthetitleofspecifiedbook
5. Listthe countof booksin thelibrary
6. List the books in the order of accession
number7.Exit

Choose an
option2
Accession number name title price issue
status234xxxxx.000000 23
234xxxxRukhsar50.000000yes
1. Addbookinformation
2. Displaybookinformation
3. Listallbooks ofgivenauthor
4. listthetitleofspecifiedbook
5. Listthe countof booksin thelibrary
6. List the books in the order of accession
number7.Exit

155|Page
67.Create a structure to specify data of customers in a bank,
thedatastoredis:
a) A/C number
b) Name
c) Balancein a/c
Assumethenumbermax200customers in the bank
a) Write a function to print the a/c number and name of
eachcustomerwith balancebellow rupees100.
b) If a customer requests for withdrawal or deposit it is given
inthe form a/c number, amount, code (1 for deposit and 0
forwithdrawal)
c) Write a program to give a message that balance is
insufficientforthe specified withdrawal
input:
#include<stdio.h>
#define N
200structbank
{
intacn;
char
name[20];int
bal;
/*defined outofmain() */
};

intmain()
{
structbankb[N];
inti,ch,lw=100,ch2,ac,am;

for(i=0;i<N;i++)
{
/*inputtingcustomerdata */
printf("\tEnter information of customers \
n");printf("\t******************************\n\
n");

printf("enter account no.:


");scanf("%d",&b[i].acn);

printf("\n\nenter customer name:


");scanf("%s",&b[i].name);

156|Page
printf("\n\nenter balance:
");scanf("%d",&b[i].bal);

157|Page
}
printf("\tEnteryourchoice\n");
/* further processing of transaction
*/printf("\t*****************\n\
n");

printf("1: to know whose balance is below 100.\n\


n");printf("2:toprocessrequest orwithdrawl.\n\n\n");

scanf("%d",&ch);
switch(ch)
{

case1:

disp(&b);
/* displaying whose balance is below 100

*/break;

case2:

printf("enter your account number:


");scanf("%d",&ac);

for(i=0;i<N;i++)
{
if((b[i].acn)==ac)
{

printf("\tHello %s\
n",b[i].name);printf("\n\n");

printf("\n\nenter your choice\


n");printf("\n1: deposite:\
n");printf("\n0: withdrawl:\n\
n");scanf("%d",&ch2);

switch(ch2)
{

case0:

if(b[i].bal<lw)

158|Page
{

159|Page
printf("\n\nsorry!accountbalanceistoolowfor withdrawl.\n");

break;
}
else
{
printf("\n\nenter amount for withdrawl:
");scanf("%d",&am);
}
if(b[i].bal<am)
{
printf("\n\nyoudon'thaveenoughbalanceforwithdrawl.\n");
}
else
{
b[i].bal=b[i].bal+am;printf("\n\
nwithdrawlwassuccessful.\n");
}
break;

case1:

printf("\n\nenter amount to deposite:


");scanf("%d",&am);

b[i].bal=b[i].bal+am;
printf("\n\ncashdepositedsuccessfully.\n\n");

break;
}
}
}
}
getch();
}
disp(structbank*a)
{
intk;

printf("\tCustomers whose balance is below 100:\n");printf("\


t*************************************\n\n");

for(k=0;k<N;k++)
{

160|Page
if((a[k].bal)<100)
{

printf("%2d\t%s\n",a[k].acn,a[k].name);
}
}
return0;
}

Output:

Enterinformationofcustomers
***************************
Enteraccount no. :3710xxxxxxxxx

Enter customer name : Mohd

NazimEnterbalance: 250

Enterinformationofcustomers
***************************
Enteraccount no. :3710xxxxxxxxx

Entercustomername:MohdNazim

Enterbalance:500
Enterinformationofcustomers
***************************
.
.
.
.
.

1:to know whosebalanceis below 100


2:topressrequestorwithdrawl.

161|Page
68.WAP to open a file read it and write the contents in
anotherfileandalsocountthe numberof
characterandwordsinthatfile.Input:
#include
<stdio.h>int
main()
{
FILE *fptr1,
*fptr2;charfilename[10
0],c;
printf("Enter the filename to open for reading \
n");scanf("%s",filename);

// Open one file for


readingfptr1 =
fopen(filename, "r");if(fptr1
==NULL)
{
printf("Cannot open file %s \n",
filename);exit(0);
}

printf("Enter the filename to open for writing \


n");scanf("%s",filename);

// Open another file for


writingfptr2 =
fopen(filename, "w");if(fptr2
==NULL)
{
printf("Cannot open file %s \n",
filename);exit(0);
}
// Read contents from
filec=fgetc(fptr1);
while(c!=EOF)
{
fputc(c,fptr2);c
=fgetc(fptr1);
}
printf("\nContentscopiedto%s",filename);

fclose(fptr1)

162|Page
;fclose(fptr2
);return0;
}

163|Page
Output:
Enterthefilenametoopenforreadinga.txt
Enterthefilenametoopenforwritingb.txt
Contentscopiedtob.txt

164|Page
69. WAPtodeleteallvowelsfromasentence.UsingFile.Input
:
#include<stdio.h>i
ntmain()
{
inti,j,len;
char
sent[100];printf("Enterasent
ence\n");gets(sent);
for(len=0;sent[len]!='\0';len+
+);for(i=0;i<len;i++)
{
if(sent[i]=='a'||sent[i]=='e'||sent[i]=='i'||sent[i]=='o'||sent[i]=='u'||sent[i]=='A'||sent[i]=='E'||
sent[i]=='I'||sent[i]=='O'||sent[i]=='U')
{
for(j=i;j<len;j++)
{
sent[j]=sent[j+1];
}
i--;
}
}
printf("\n\nThesentencewithnovowelsinitisas\n");puts(sent);
return0;
}

Output:
EnterasentenceHo
wareyou
ThesentencewithnovowelsinitisasHwry

165|Page
70. WAPtodeletealltheextraspacesfromaparagraph.UsingFile.
Input:
#include<stdio.h>in
tmain()
{
charinputString[100],outputArray[100];in
treadIndex=0,writeIndex;printf("EnteraSe
ntences\n");gets(inputString);
/*Skipsallspacesbeforefirstcharacters*/
while(inputString[readIndex]=='')
{
readIndex++;
}
for(writeIndex=0;inputString[readIndex]!='\0';readIndex++)
{
if(inputString[readIndex]==''&&inputString[readIndex-1]=='')
{
continue;
}
outputArray[writeIndex]=inputString[readIndex];writeInde
x++;
}
outputArray[writeIndex]='\0';
printf("Sentenceswithoutextraspaces\n
%s",outputArray);return0;
}

Output:
EnteraSentences
Hey Mohd NazimSentences
without extra
spacesHeyMohdNazim

166|Page
71. WAP to implement singly connected linked
list.Input:
#include<stdio.h>
structnode
{
int
data;int
key;
structnode*next;
};
struct node *head =
NULL;structnode*current=NUL
L;
//display the
listvoidprintLi
st()
{
struct node *ptr =
head;printf("\n[");

//start from the


beginningwhile(ptr!=
NULL)
{
printf("(%d,%d) ",ptr->key,ptr-
>data);ptr=ptr->next;
}
printf("]");
}

//insert link at the first


locationvoidinsertFirst(intkey,int
data)
{
//createalink
structnode*link=(structnode*)malloc(sizeof(structnode));

link->key =
key;link-
>data=data;
//point it to old first
nodelink->next=head;
//point first to new first
nodehead=link;
167|Page
}
//deletefirstitem
structnode*deleteFirst()
{
//savereferencetofirst link

168|Page
structnode*tempLink =head;
//mark next to first link as
firsthead=head->next;
//return the deleted
linkreturntempLink;
}
//is list
emptyboolisE
mpty()
{
returnhead== NULL;
}

intlength()
{
intlength=0;
structnode*current;

for(current= head;current !=NULL;current=current->next)


{
length++;
}
returnlength;
}
//find a link with given
keystructnode*find(int
key)
{
//start from the first
linkstructnode*current=hea
d;
//if list is
emptyif(head==NU
LL)
{
returnNULL;
}
//navigate through
listwhile(current->key!
=key)
{
//ifit is last node
if(current->next==NULL)
{

169|Page
returnNULL;
}
else
{
//go to next link

170|Page
current=current->next;
}
}
//if data found, return the current
Linkreturncurrent;
}
//delete a link with given
keystructnode*delete(intke
y)
{
//start from the first
linkstructnode*current=hea
d;
structnode*previous=NULL;
//if list is
emptyif(head==NU
LL)
{
returnNULL;
}
//navigate through
listwhile(current->key!
=key)
{
//ifit is last node
if(current->next==NULL)
{
returnNULL;
}
else
{
//store reference to current
linkprevious=current;
//move to next
linkcurrent=current-
>next;
}
}
//found a match, update the
linkif(current==head)
{
//change first to point to next
linkhead=head->next;
}

171|Page
else
{
//bypassthecurrentlink
previous->next=current->next;
}

172|Page
returncurrent;
}
voidsort()
{
int i, j, k, tempKey,
tempData;structnode*current;
structnode*next;

int size =
length();k =size;

for(i =0 ; i <size-1 ;i++, k--)


{
current =
head;next=head-
>next;

for(j =1 ; j <k ; j++)


{
if(current->data>next->data)
{
tempData = current-
>data;current->data = next-
>data;next-
>data=tempData;

tempKey = current-
>key;current->key = next-
>key;next-
>key=tempKey;
}
current = current-
>next;next=next->next;
}
}
voidreverse(structnode**head_ref)
{
struct node* prev= NULL;struct
node* current =
*head_ref;structnode* next;

while(current!= NULL)
{
next= current-

173|Page
>next;current->next
= prev;prev =
current;current=next;

174|Page
}
*head_ref=prev;
}
intmain()
{
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);i
nsertFirst(5,40);i
nsertFirst(6,56);

printf("OriginalList:");
//print
listprintLis
t();

while(!isEmpty())
{
struct node *temp = deleteFirst();printf("\
nDeletedvalue:");printf("(%d,%d)",temp-
>key,temp->data);
}

printf("\nList after deleting all items:


");printList();
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);i
nsertFirst(5,40);i
nsertFirst(6,56);

printf("\nRestored List:
");printList();
printf("\n");

structnode*foundLink=find(4);

if(foundLink!=NULL)
{
printf("Elementfound:");
printf("(%d,%d) ",foundLink->key,foundLink-
>data);printf("\n");

175|Page
}

176|Page
else
{
printf("Elementnotfound.");
}
delete(4);
printf("List after deleting an item:
");printList();
printf("\
n");foundLink=find(
4);

if(foundLink!=NULL)
{
printf("Elementfound:");
printf("(%d,%d) ",foundLink->key,foundLink-
>data);printf("\n");
}
else
{
printf("Elementnotfound.");
}
printf("\
n");sort();

printf("List after sorting the data:


");printList();

reverse(&head);
printf("\nList after reversing the data:
");printList();
}

Output:
OriginalList:
[(6,56)(5,40)(4,1) (3,30)(2,20)(1,10)]
Deleted value:
(6,56)Deleted value:
(5,40)Deleted value:
(4,1)Deleted value:
(3,30)Deleted value:
(2,20)Deletedvalue:
(1,10)
List after deleting all items:
[]
177|Page
RestoredList:

178|Page
[(6,56)(5,40)(4,1) (3,30)(2,20)(1,10)]
Elementfound:(4,1)
Listafterdeletinganitem:
[(6,56)(5,40) (3,30)(2,20) (1,10)]
Elementnot found.
Listaftersortingthedata:
[(1,10)(2,20) (3,30)(5,40) (6,56)]
Listafterreversingthedata:
[(6,56)(5,40) (3,30)(2,20) (1,10)]

179|Page
72. Brieflyexplainanddifferentiatefollowingterms:printf,scanf,gets
, puts, getchar, putchar, sprint, sscanf, read, write, getc,
putc.Input:
Printf()AndScanf():
The standard input-output header file, named stdio.h contains the definition of
thefunctions printf() and scanf(), which are used to display output on screen and to take
inputfromuser respectively.

Example:#include
<stdio.h>int
main()
{
inti;
printf("Please enter a
value...");scanf("%d",&i);
printf("\nYou entered: %d",
i);return0;
}

Output:
Please enter a value...
24Youentered:
24

Gets()AndPuts():
he gets() function reads a line from stdin(standard input) into the buffer pointed
tobystrpointer,untileitheraterminating newlineor EOF(end offile) occurs.
Theputs()function writesthe stringstrand atrailingnewline tostdout.

str → This is the pointer to an array of chars where the C string is

stored.Example:
#include<stdio.h>
intmain()
{
char
str[100];printf("Enter a
string");gets(str);
puts(str );
return0;

180|Page
}

Output:
Enter a string
1010

Getschar()Andputschar():
The getchar() function reads a character from the terminal and returns it as an integer.
Thisfunction reads only single character at a time. You can use this method in a loop in case
youwant to read more than one character. The putchar() function displays the character
passed toit on the screen and returns the same character. This function too displays only a
singlecharacter at a time. In case you want to display more than one characters, use
putchar()method in a loop.

Example:#include
<stdio.h>int
main()
{
int c;
printf("Enter a
character");c=getchar();
putchar(c);
}

Output:
Enter a character
RR

Sscanf():
function reads the values from a char[] array and store each value into variables of
matchingdatatypeby specifying the matching format specifier.

Example:#include
<stdio.h>int
main()
{
char ar[20] = "User M 19
1.85";charstr[10];
char
ch;inti;

181|Page
floatf;
/* Calling sscanf() to read multiple values from a char[] array and store each value
inmatchingvariable*/
sscanf(ar,"%s%c%d",&str,&ch,&i,&f);

printf("The value in string is : %s ",


str);printf("\n");

printf("The value in char is : %c ",


ch);printf("\n");

printf("The value in int is : %d ",


i);printf("\n");

printf("Thevaluein floatis :%f",f);

sscanf(ar,"%s%c%d",&str,&ch,&i);

return0;
}

Output:
The value in string is :
UserThevalueincharis:MTh
evalue in int is : 19
Thevaluein float is : 1.850000

Sprint()
The sprintf() function reads the one or multiple values specified with their matching
formatspecifiers and storethese values in a char[]array.

Example:#include
<stdio.h>int
main()
{
chartarget[20];
char name[10] =
"Nazim";chargender='M';
int age=18;
floatheight =1.80;

printf("Thenameis:%s",name);

182|Page
printf("\n");
printf("The gender is : %c",
gender);printf("\n");
printf("The age is : %d",
age);printf("\n");
printf("Theheightis:%f",height);

/*Callingsprintf()functiontoreadmultiplevariablesandstoretheirvaluesinachar[]array
i.e. string.*/
sprintf(target, "%s %c %d %f", name, gender, age,
height);printf("\n");
printf("Thevalueinthe targetstringis:%s", target);

return0;
}

Output:
The name is :
NazimThegender is: M
Theageis :18
Theheight is : 1.800000
Thevalue in the targetstring is :AndreaF 18 1.650000

Cread:
Fromthefileindicatedbythefiledescriptorfd,theread()functionreadscntbytesofinputintothememor
yareaindicatedbybuf.Asuccessfulread()updatestheaccesstimeforthefile.
SyntaxinClanguage
size_tread(intfd,void*buf,size_tcnt);

Example:
// read system
Call#include<stdio
.h>#include
<fcntl.h>intmain()
{
intfd,sz;
char*c=(char*)calloc(100,sizeof(char));

fd=open("foo.txt",O_RDONLY);if(
fd<0)
{
perror("r1");exit(
1);
}

183|Page
sz=read(fd,c,10);
printf("calledread(%d,c,10).returnedthat""%d
byteswereread.\n",fd,sz);
c[sz]='\0';
printf("Thosebytesareasfollows:%s\n",c);
}

Output:
calledread(3,c,10).returnedthat10byteswereread.Thosebytes
areasfollows:000foo.

Cwrite:
Writescntbytesfrombuftothefileorsocketassociatedwithfd.cntshouldnotbegreaterthanINT_MA
X(definedinthelimits.hheaderfile).Ifcntiszero,write()simplyreturns0withoutattemptinganyother
action.
#include<fcntl.h>

SyntaxinClanguage
size_twrite(intfd,void*buf,size_tcnt);
Example:
//
writesystemCall#in
clude<stdio.h>#inc
lude<fcntl.h>intma
in()
{
intsz;

intfd=open("foo.txt",O_WRONLY|O_CREAT|
O_TRUNC,0644);if(fd<0)
{
perror("r1");exit(
1);
}
sz=write(fd,"hellogeeks\n",strlen("hellogeeks\n"));

printf("calledwrite(%d,\"hellogeeks\\n\",%d").
"Itreturned%d\n",fd,strlen("hellogeeks\n"),sz);

close(fd);
}
Output:
calledwrite(3,"hellogeeks\n",12).itreturned11

184|Page
Getc()AndPutc():
Getc functions is used to read a character from a file. In a C program, we read a character
asbelow.
getc(fp);

Putcfunctionisusedtodisplayacharacteronstandardoutputorisusedtowriteintoafile.InaC
program, wecan useputc as below.
putc(char,stdout);
putc(char,fp);

Example:
#include<stdio.h>
int main()
{
char
ch;FILE*
fp;
fp=fopen("std1.txt","w");
//openingfileinwritemodeprintf("enter
the text.press cntrl Z:\
n");while((ch=getchar())!=EOF)
{
putc(ch,fp);
//writingeachcharacter intothefile
}
fclose(fp);fp=fopen("std1.t
xt","r");printf("text on the
file:\
n");while((ch=getc(fp))!
=EOF)
{
// reading each character from
fileputchar(ch);
//displayingeachcharacterontothescreen
}
fclose(fp);
return0;
}
Output:
enterthetext.press cntrlZ:
^Z

185|Page

You might also like