C Programming Lab
C Programming Lab
ProgramOutcomes
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5 Moderntoolusage:Create,select,andapplyappropriatetechniques,resources,andmodern engineering and
IT tools including prediction and modeling to complex engineering activities with an understanding of
the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principlesandapplythesetoone’s ownwork, as a member andleader in ateam, to manage
projects and in multidisciplinary environments.
PO12 Life-longlearning:Recognizetheneedfor,andhavethepreparationandabilitytoengagein independent and
life-long learning in the broadest context of technological change.
1
121
112
123
121
ProgramSpecificOutcomes
PSO1 Professional Skills: The ability to research, understand and implement computer programs in the areas
related to algorithms, system software, multimedia, web design, big data analytics, and networking for
efficient analysis and design of computer-based systems of varying complexity.
PSO2 Problem-Solving Skills: The ability to apply standard practices and strategies in software project
development using open-ended programming environments to deliver a quality product for business
success.
PSO3 Successful Career and Entrepreneurship: The ability to employ modern computer languages,
environments, and platforms in creating innovative career paths, to be an entrepreneur, and a zest for
higher studies.
COMPUTERPROGRAMMINGLABSYLLABUS
SOFTWAREANDHARDWAREREQUIREMENTSFORABATCHOF60STUDENTS: HARDWARE:
Desktopsystems:30nos
Printers: 02
SOFTWARE:
System Software: Windows 7.
Application Software: MS Office.
ProgrammingLanguages:DevC++
COMPUTERPROGRAMMINGLABORATORY
(CommonforCSE/ ECE/ME/ CE)
Semester:2
CI
L T P C SEE Total
Category Foundation E
- - 4 2 30 70 100
Goal:This course helps the students in understanding a powerful, portable and flexible structured programming language
which is suitablefor both systems and applications programming. It is a robust language which contains a rich set
of built-in functions and operators to write any complex program.
2
Objectives:
Thecourseshouldenablethestudentsto:
I. Developmodular,efficientandreadableCprogramsbyhands-onexperience.
II. Interpret good profound knowledge in C programming language and enable them to build programs using operators,
control structures, arrays, strings, functions, pointers and structures to solve the real world problems.
III. Illustratememoryallocationtovariablesdynamicallyandperformoperationsontextandbinaryfiles.
IV. DevelopinterestandlayfoundationtolearndatastructuresandJavaprogramminglanguagesandexcelasaprofessional
programmer.
LISTOF EXPERIMENTS
Week-1 OPERATORSANDEVALUATIONOFEXPRESSIONS
a. WriteaCprogramtocheckwhetheranumberisevenor oddusingternaryoperator.
b. WriteaCprogramtoperformtheadditionoftwonumberswithoutusing+ operator.
c. WriteaCprogramtoevaluatethearithmeticexpression((a+b/ c*d -e) *(f -g)).Readthevaluesa,b,c,d,e,f,g from the
standard input device.
d. WriteaCprogramtofindthesumofindividualdigitsofa3digitnumber.
e. WriteaCprogramtoreadthevaluesofxandyandprinttheresultsofthefollowingexpressionsinoneline:
i. (x+y) /(x-y)
ii. (x+y)(x-y)
Week-2 CONTROLSTRUCTURES
a. Writea Cprogram, whichtakes twointeger operandsand oneoperator fromtheuser, performs the operationand then
prints the result. (Consider the operators +, -, *, /, % and use switch statement).
b. WriteaCprogramtocalculatethefollowingsum:
sum= 1 – x2 /2! + x4 /4! – x6 /6! +x8 /8! – x10/10!
c. WriteaCprogramtofindtherootsofaquadraticequation.
d. WriteaCprogramtocheckwhetheragiven3digitnumberisArmstrongnumberornot.
e. WriteaCprogramtoprintthenumbersintriangularform
1
12
123
123 4
Week-3 ARRAYS
3
121
112
123
121
a. WriteaCprogramtofindthesecondlargestintegerinalistofintegers.
b. WriteaCprogramtoperformthefollowing:
i. Additionoftwomatrices
ii. Multiplicationoftwomatrices
c. WriteaCprogramtocountanddisplaypositive,negative,oddandevennumbersinanarray.
d. WriteaCprogramtomergetwosortedarraysintoanotherarrayinasortedorder.
e. WriteaCprogramtofindthefrequencyofaparticularnumber inalistofintegers.
Week-4 STRINGS
a. WriteaCprogramthatusesfunctionstoperformthefollowingoperations:
i. Toinsertasubstringintoagivenmainstringfromagiven position.
ii. Todeletencharactersfromagivenpositioninagivenstring.
b. WriteaCprogramtodetermineifthegivenstringisapalindromeornot.
c. WriteaCprogramtofindastringwithinasentenceandreplaceitwithanotherstring.
d. WriteaCprogramthatreadsalineoftextandcountsalloccurrenceofaparticularword.
e. WriteaCprogramthatdisplaysthepositionorindexinthestringSwherethestringTbegins,or1ifS
doesn’tcontainT.
Week-5 FUNCTIONS
a. WriteCprogramsthatusebothrecursiveandnon-recursivefunctions
i. Tofindthefactorialofagiven integer.
ii. Tofindthegreatestcommondivisoroftwogivenintegers.
b. WriteCprogramsthatusebothrecursiveandnon-recursivefunctions
i. ToprintFibonacciseries.
ii. TosolvetowersofHanoi problem.
c. WriteaCprogramtoprintthetransposeofagivenmatrixusingfunction.
d. WriteaCprogramthatusesafunctiontoreverseagiven string.
Week-6 POINTERS
a. WriteaCprogramtoconcatenatetwostringsusingpointers.
b. WriteaCprogramtofindthelengthofstringusingpointers.
c. WriteaCprogramtocomparetwostringsusingpointers.
d. WriteaCprogramtocopyastringfromsourcetodestinationusingpointers.
e. WriteaCprogramtoreverseastringusingpointers.
Week-7 STRUCTURESANDUNIONS
4
121
112
123
121
a. WriteaCprogramthatusesfunctionstoperformthefollowingoperations:
i. Readingacomplexnumber
ii. Writingacomplex number
iii. Additionandsubtractionoftwocomplexnumbers
iv. Multiplicationoftwocomplexnumbers.Note:representcomplexnumberusingastructure.
b. Write a C programto compute the monthly pay of 100employees using each employee’s name, basic pay. The DAis
computed as 52% of the basic pay. Gross-salary (basic pay + DA). Print the employees name and gross salary.
c. Create a Book structure containing book_id, title, author name and price. Write a C programto pass a structure as a
function argument and print the book details.
d. Create a union containing 6 strings:name, home_address, hostel_address, city, state and zip. Write a C program
todisplay your present address.
e. Write a C program to define a structurenamed DOB, which contains name, day, month and year. Using the conceptof
nested structures display your name and date of birth.
Week-8 FILES
a. WriteaCprogramtodisplaythecontentsofafile.
b. WriteaCprogramtocopythecontentsofonefiletoanother.
c. WriteaCprogramtoreversethefirstncharactersinafile,wherenisgivenbytheuser.
d. Two files DATA1 and DATA2 contain sorted lists of integers. Write a C program to merge the contents of two files
into a third file DATA i.e., the contents of the first file followed by those of the second are put in the third file.
e. WriteaCprogramtocountthe no.ofcharacterspresentinthefile.
a.
1.
1.
5
121
112
123
121
WEEK-1
OPERATORSANDEVALUATIONOFEXPRESSIONS
1.1 OBJECTIVE:
1. WriteaCprogramtocheckwhetheranumberisevenor oddusingternaryoperator.
2. WriteaCprogramtoperformtheadditionoftwonumberswithoutusing+ operator.
3. WriteaCprogramtoevaluatethearithmeticexpression((a+b/ c*d -e) *(f -g)). Read the
values a, b, c, d, e, f, g from the standard input device.
4. WriteaCprogramtofindthesumofindividualdigitsofa3digitnumber.
5. WriteaCprogramtoreadthevaluesofxandyandprinttheresultsofthefollowingexpressions in one
line:
iii. (x+y) /(x-y)
iv. (x+y)(x-y)
1.2 RESOURCES:
DevC++5.11
1.3 PROGRAMLOGIC:
Tocheckwhetheranumberisevenoroddusingternaryoperator
1. Start
2. Readn
3. (n%2==0?"EVEN":"ODD")
4. DisplayEVENifn%2==0
5. Otherwise ODD
6. Stop
Toperformtheadditionoftwonumberswithoutusing+operator
1. Start
2. Reada,b
3. sum=a-~b-1
4. Displaythevalueofsum
5. Stop
6
121
112
123
121
Toevaluatethearithmeticexpression((a+b/c*d-e)*(f - g)).
1. Start
2. Reada,b,c,d,e,f,g
3. A=a+b
4. B=A/c
5. C=(d-e)
6. D=(f-g)
7. CalculateB*C*D
8. StoreB*C*Dvalueto Result
9. DisplaytheResult
Tofindthesumofindividualdigitsofa3digit number.
1. Start
2. Readanumber N
3. InitializetheSum=0
4. ifn>0thencalculatereminder R=N%10
5. AddreminderRtoSum
6. StoreN/10valuetoN
7. IfN=0thenDisplaySum
8. Stop
Toreadthevaluesofxandyandprinttheresultsofthefollowingexpressionsinoneline
i. (x+y)/(x-y) ii. (x+y)(x-y)
i. (x+y) /(x-y)
1. Start
2. Readnumbersxandy
3. A=x+y
4. B=x-y
5. PerformA/B
6. StorethevalueofA/BinResult
7. DisplaytheResult
ii. (x+y)(x-y)
1. Start
2. Readnumbersxandy
7
121
112
123
121
3. A=x+y
4. B=x-y
5. PerformA*B
6. StorethevalueofA*BinResult
7. DisplaytheResult
1.4 PROCEDURE:
1. Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
2. Compile:F9
3. Execute:F10
1.5 SOURCECODE:
Tocheckwhetheranumberisevenoroddusingternaryoperator
#include<stdio.h>i
nt main()
{
intn;
printf("\n enter the values of n:");
scanf("%d",&n);
(n%2)?printf("odd"):printf("even");
return 0;
}
Toperformtheadditionoftwonumberswithoutusing+operator
#include<stdio.h>i
nt main()
{
inta,b,c;
printf("\nenterthevaluesofa,b:"); scanf("%d%d",&a,&b);
c=(a-~b)-1;
printf("sum=%d",c);
return 0;
}
8
121
112
123
121
Toevaluatethearithmeticexpression((a+b/ c*d-e)*(f- g)).
#include<stdio.h>in
t main()
{
inta,b,c,d,e,f,g,res;
printf("\n enter the values of a,b,c,d,e,f,g:");
scanf("%d%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f,&g);
res=((a+b/c*d-e)*(f-g));
printf("res=%d",res); return 0;
}
TofindthesumofIndividualdigitsofa3digitnumber
#include<stdio.h>i
nt main()
{
intn,d1,d2,d3;
printf("\nenterthevaluesof3digitno:"); scanf("%d",&n);
d1=n%10;
n=n/10;
d2=n%10;
n=n/10;
d3=n%10;
n=n/10;
n=d1+d2+d3;
printf("thesumofindividual number=%d",n);
}
Toreadthevaluesof xandyandprinttheresultsofthefollowingexpressionsinoneline
i. (x+y) /(x-y)
ii. (x+y)(x-y)
i. (x + y) / (x - y)
#include<stdio.h>
void main()
{
intx,y,A,B;
9
121
112
123
121
floatResult;
printf("Enterthevaluesofx,y\n");
scanf("%d %d " ,&x, &y);
A=(x+y);
B=(x-y);
Result=A/B
;printf("%f",Result);
}
ii. (x + y)(x - y)
#include<stdio.h>
void main()
{
int x,y,A,B;
floatResult;
printf("Enterthevaluesofx,y\n");
scanf("%d %d " ,&x, &y);
A=(x+y);
B=(x-y);
Result=A*B
;printf("%f",Result);
}
1.6 INPUT/OUTPUT
Tocheckwhetheranumberisevenoroddusingternaryoperator
10
121
112
123
121
Toperformtheadditionoftwonumberswithoutusing+operator
11
121
112
123
121
WEEK- 2
CONTROLSTRUCTURES
2.1 OBJECTIVE:
1. Write a C program, which takes two integer operands and one operator from the user, performs
the operationand then prints the result. (Consider the operators +, -, *, /, % and use switch
statement).
2. WriteaCprogramtocalculatethefollowingsum:
sum=1– x2/2!+ x4/4!–x6 /6!+x8/8!–x10/10!
3. WriteaCprogramtofindtherootsofaquadraticequation.
4. WriteaCprogramtocheckwhetheragiven3digitnumberisArmstrongnumberornot.
5. WriteaCprogramtoprintthenumbersintriangularform 1
1 2
1 23
1 23 4
2.2 RESOURCES:
DevC++5.11
2.3 PROGRAMLOGIC:
ArithmeticOperationsusingswitchcase
2.1.1 Start
2.1.2 Readtwonumbersaandb
2.1.3 Readyourchoiceofoperatorch
2.1.4 Ifch=‘+’thencalculateadd=a+banddisplaytheadditionresult.
2.1.5 Ifch=‘-‘thencalculatesub=a–banddisplaythesubtractionresult.
2.1.6 Ifch=‘*’thencalculatemul=a*banddisplaythemultiplicationresult.
2.1.7 Ifch=‘/’thencalculatediv=a/banddisplayt hedivisionresult.
2.1.8 Ifch=’%’thencalculatemod=a%banddisplaythemodulus result.
2.1.9 Otherwisedisplayinvalidoperator
2.1.10 Stop
12
121
112
123
121
Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
1. Start
2. Readx value.
3. Calculatesum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!.
4. Printsum.
5. Stop
RootsofQuadraticEquation
1. Start
2. Readthecoefficientsofaquadraticequationa,b,c
3. Calculatedeterminantd=b*b– 4*a*c
4. Ifd>0calculatetworealrootsr1=(-b+sqrt(d))/ (2*a)andr2=(-b+sqrt(d))/ (2*a)
5. Ifd=0thenrootsr1andr2areequal anddisplayr1=r2=-b/ (2*a)
6. Ifd<0thenrootsareimaginaryanddisplayrealroot=-b/(2*a)andimgroot =sqrt(-d)/ (2*a)
7. Stop
Toprintthenumbersintriangular form
1. Strat
2. Declarei,j,rows
3. Enternumber ofrows
4. Readrows
5. for(i=1;i<=rows;++i)
6. for(j=1;j<=i;++j)
7. Displayj
8. Stop
2.4 PROCEDURE:
2.1.11 Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
2.1.12 Compile: F9
2.1.13 Execute: F10
2.5 SOURCECODE:
ArithmeticOperationsusingswitchcase
#include<stdio.h>v
oid main()
{
13
121
112
123
121
int a,b;
charop;
printf("\nEntertwonumbera,b,anoperator:"); scanf("%d
%d %c",&a,&b,&op);
switch(op)
{
case'+':printf("\n Sum=%d",a+b);break;
case'-':printf("\nDifference=",a-b);break;
case'*':printf("\nProduct=",a*b);break;
case'/':printf("\nQuotient=",a/b);break;
case'%':printf("\nRemainder=",a%b);break;
default:printf("\nPleaseenteravalidinput");
break;
}
}
Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
#include<stdio.h>
#include<math.h>
void main()
{
int i = 2, n, s = 1, x, pwr = 1, dr;
floatnr = 1, x1, sum;
printf("\n\n\tentertheangle...:");
scanf("%d", &x);
x1=3.142*(x/180.0);
sum= x1;
printf("\n\tenterthenumberofterms...:");
scanf("%d", &n);
While( i<= n)
{
pwr=pwr+ 2;
dr=dr*pwr*(pwr -1);
sum=sum+(nr/dr)*s; s =
s * (-1);
nr=nr*x1*x1; i+=2;
}
14
121
112
123
121
printf("\n\tthesumofthesineseriesis..: %0.3f",sum);
}
RootsofQuadraticEquation#inc
lude<stdio.h> #include<math.h>
voidmain()
{
floata,b,c,r1,r2,d;
printf("enterthevaluesofequation:");
scanf("%f%f%f",&a,&b,&c);if(a==0)
printf("\nenternonzerovalues");
else
{
d=b*b-4*a*c;
if(d>=0)
{
r1=((-b+sqrt(d))/(2*a));
r2=((-b-sqrt(d))/(2*a));
printf("\ntherootsare=\t%f\t%f",r1,r2);
}
else
printf("\nrootsareimaginary");
}
}
Toprintthenumbersintriangular form
#include<stdio.h>v
oid main()
{
inti,j,n;
printf("\nEnterthenumberofrows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
15
121
112
123
121
printf("%5d",j);
}
printf("\n");
}
}
2.6 INPUT/OUTPUT:
ArithmeticOperationsusingswitchcase
Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
16
121
112
123
121
RootsofQuadraticEquation
Toprintthenumbersintriangular form
17
121
112
123
121
WEEK-3
ARRAYS
3.1 OBJECTIVE:
1. WriteaCprogramtofindthesecondlargestintegerinalistofintegers.
2. WriteaCprogramtoperformthefollowing:
i. Additionoftwomatrices
ii. Multiplicationoftwomatrices
3. WriteaCprogramtocountanddisplaypositive,negative,oddandevennumbersinanarray.
4. WriteaCprogramtomergetwosortedarraysintoanotherarrayinasortedorder.
5. WriteaCprogramtofindthefrequencyofaparticularnumber inalistofintegers.
3.2 RESOURCES:
BorlandC++5.02
3.3 PROGRAMLOGIC:
Findthesecondlargestintegerinalistofintegers
3.3.1 Readanarrayofsizen.
3.3.2 Readelementsintothearraya[n].
3.3.3 Assumebig=a[0].
3.3.4 Compareeachelementofarraya[i]withbigandswapa[i]=bigifanyelementislargerthanbig.
3.3.5 Repeatstep4untilallelementsofarrayarecomparedwithbig.
3.3.6 Oncethearrayissorted,findsecondbig=a[size-j-1].
3.3.7 Displaythesecondlargest element.
Additionoftwomatrics
1. Readtheno.ofrows(r1)andcols(c1)ofamatrixa[3][3].
2. Readtheno.ofrows(r2)andcols.(c2)ofmatrixb[3][3].
3. Ifc1=c2andr1=r2thenreadtheelementsintoboththematricesaandb
4. Addtheelementsoffirst matrixwith theelementsofsecondmatrix according to theirindex position.
5. Displaytheresultant matrix.
18
121
112
123
121
Multiplicationoftwomatrics
1. Readtheno.ofrows(r1)andcols(c1)ofamatrixa[3][3].
2. Readtheno.ofrows(r2)andcols.(c2)ofmatrixb[3][3].
3. Ifc1=r2thendisplaymatrixmultiplicationispossibleotherwisedisplayimpossible
4. Ifc1=r2thenreadtheelementsintoboththematricesaandb.
5. Initializearesultantmatrixc[3][3]with0.
6. Calculatec[i][j]=c[i][j]+a[i][k]* b[k][j].
7. Displaytheresultant matrix.
Countanddisplayof positive,negative,oddandevennumbersinanarray
1. Declareandreadvariablesn,i
2. Readelementsintoanarray
3. If(a[i]>0)thendisplaynumberispositive
4. If(a[i]%2==0)thendisplaynumberiseven
5. If(a[i]<0)thendisplaynumberisnegative
6. If(a[i]%2!=0)thendisplaynumberisodd
Mergetwosortedarraysintoanotherarrayinasortedorder
1. Declare3matricesa[50],b[50],c[100]
2. Readnumberofrowsandcolumnsm,n.
3. Readelementsformatrixaandb.
4. Sortthematricesifitisnotsorted.
5. Copytheelementsofmatrixaintomatrixc.
6. Thencopytheelementsofmatrixbintomatrix c.
7. Sorttheelementsofmatrixc.
3.4 PROCEDURE:
3.4.1 Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
3.4.2 Compile:F9
3.4.3 Execute:F10
3.5 SOURCECODE:
Programtofindthesecondlargestelementinanarray
#include<stdio.h>vo
id main()
{
19
121
112
123
121
int a[10],i,j,t;
printf("enter10nos\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<10;i++)
{
for(j=0;j<10;j++)
{
if(a[j]>a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nsecondlargestno.=%d",a[8]);
}
Additionoftwomatrics
#include<stdio.h>vo
id main()
{
int a[10][10],b[10][10],i,j,m,n,p,q;
printf("enterrow&columnofMat1\n");
scanf("%d%d",&m,&n);
printf("enterrow&columnofMat2\n");
scanf("%d%d",&p,&q);
if(m==p&&n==q)
{
printf("enterMat1\n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
20
121
112
123
121
{ scanf("%d",&a[i][j]);
}
}
printf("enterMat2\n");
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
{ scanf("%d",&b[i][j]);
}
}
printf("\nsumofthematrices\n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{ printf("%8d",a[i][j]+b[i][j]);
}
printf("\n");
}
printf("\ndifferenceofthematrices\n");
for(i=0;i<m;i++)
{ for(j=0;j<n;j++)
{ printf("%8d",a[i][j]-b[i][j]);
}
printf("\n");
}
}
else
printf("\noperationsnotpossible...");
}
Multiplicationoftwomatrics
#include<stdio.h>v
oid main()
{ int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf("enterrow&columnofMat1\n");
scanf("%d%d",&m,&n);
printf("enterrow&columnofMat2\n");
21
121
112
123
121
scanf("%d%d",&p,&q);
if(n==p)
{
printf("enterMat1\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enterMat2\n");
for(i=0;i<p;i++)
{ for(j=0;j<q;j++)
{ scanf("%d",&b[i][j]);
}
}
printf("\nmultipliedmatrix\n");
for(i=0;i<m;i++)
{ for(j=0;j<q;j++)
{ c[i][j]=0;
for(k=0;k<n;k++)
{ c[i][j]=c[i][j]+a[i][k]*b[k][j];
} printf("%8d",c[i][j]);
} printf("\n");
}
}
else
printf("\nmultiplicationisnot possible...");
}
Countanddisplayof positive,negative,oddandevennumbersinanarray
#include<stdio.h>v
oid main()
{
inta[10],i,o=0,p=0,e=0,n=0;
printf(" enter 10 nos\n");
22
121
112
123
121
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
if(a[i]%2==0)
{
e++;
}
else
{
o++;
}
if(a[i]>=0)
{
p++;
}
else
{
n++;
}
}
printf("\nevennos.=%d",e);
printf("\n odd nos.=%d",o);
printf("\n +ve nos.=%d",p);
printf("\n -ve nos.=%d",n);
}
}
Mergetwosortedarraysintoanotherarrayinasortedorder
#include<stdio.h>
#include<conio.h>
void main( )
{
intn,m,i,j,k,c[40],a[20],b[20];
printf("EnterhowmanyelementsforarrayA?:\n");
23
121
112
123
121
scanf("%d",&n);
printf("EnterhowmanyelementsforarrayB?:\n");
scanf("%d",&m);
printf("EnterelementsforA:-\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("EnterelementsforB:-\n");
for(j=0;j<m;j++)
scanf("%d",&b[j]);
i=j=k=0;
while(i<n&&j<m)
{
if(a[i]<b[j])
c[k++]=a[i++];
else
if(a[i]>b[j])
c[k++]=b[j++];
else
{
c[k++]=b[j++];
i++;
j++;
}
}
if(i<n)
{
int t;
for(t=0;t<n;t++)
c[k++]=a[i++];
}
if(j<m)
{
int t;
for(t=0;t<m;t++)
24
121
112
123
121
{
c[k++]=b[j++];
}
}
printf("\n\nMergedArrayC:\n\n")
for(k=0;k<(m+n);k++)
printf("\t\n%d",c[k]);
}
3.6 INPUT/OUTPUT:
Programtofindthesecondlargestelementinanarray
25
121
112
123
121
MatrixAddition
MatrixMultiplication
26
121
112
123
121
Countanddisplayof positive,negative,oddandevennumbersinanarray
Mergetwosortedarraysintoanotherarrayinasortedorder
27
121
112
123
121
WEEK-4
STRINGS
4.1 OBJECTIVE:
f. WriteaCprogramthatusesfunctionstoperformthefollowingoperations:
iii. Toinsertasubstringintoagivenmainstringfromagiven position.
iv. Todeletencharactersfromagivenpositioninagivenstring.
g. WriteaCprogramtodetermineifthegivenstringisapalindromeornot.
h. WriteaCprogramtofindastringwithinasentenceandreplaceitwithanotherstring.
i. WriteaCprogramthatreadsalineoftextandcountsalloccurrenceofaparticularword.
j. WriteaCprogramthatdisplaysthepositionorindexinthestringSwherethestringTbegins, or 1 if S
doesn’t contain T.
4.2 RESOURCES:
DevC++5.11
4.3 PROGRAMLOGIC:
Toinsert asubstringintoagivenmainstringfromagivenposition
1. Readthemainstringintoanarraya[50].
2. Readthesubstringintoanotherarrayb[30].
3. Enterthepositionatwhichwewanttoinsertthesubstringintomainstring.
4. Initializeanothercharacterarrayc[80].
5. Ifpos!=0thencopythecharactersfromarraya[50]toarrayc[80]tillit reachestopos–1.
6. Fromthecurrentpositioncopythecontentsofthearrayb[30]tillendtothirdarrayc[80].
7. Copytheremainingcharactersfromthefirstarraya[50]tilltheendtothethirdarrayc[80].
8. Displaythecontentsofthearrayc[80].
Todeletencharactersfromagivenpositioninagivenstring
1. Readastringintoacharacterarraya[50].
2. Readthepositionfromwhereithastodeletethecharacterspos.
3. Readtheno.ofcharacterstobedeletedn.
4. Initializeanothercharacterarrayb[50].
5. Ifpos!=0thencopythecharactersfromarraya[50]toarrayb[50]tillit reachestopos-1.
6. Skipncharactersfromthecurrentpositionbymakingpos=pos+n.
7. Copytheremainingcharactersfromthenewpositionofarraya[50]till
28
121
112
123
121
theendtob[50];
8. Displaythenewstringfromarrayb.
Determineifthegivenstringisapalindromeornot
1. InputaString
2. Initializel=0,Flag=0
3. WhileString[l]!=NULL
4. Incrementl
5. Initializei=0,j=l-1
6. Whilei< (l/2)+1
7. IfString[i]equalto String[j]
8. Flag=0
9. else
10. Flag=1
11. Incrementi,Decrementj
12. IfFlag==0
13. DisplaythestringaPalindrome
14. else
15. OtherwisethestringisnotaPalindrome
Findastringwithinasentenceandreplaceitwithanotherstring
1. Declare2matricesstr[100]andfind[100].
2. Initiallycount=0,i,j, flag
3. Reada string
4. Readthestringthatyouwanttoreplace
5. Replaceeachcharacteroforiginalstringwiththenewstring
6. Onceallcharactersarereplacedmakeflag=1and countthe characters.
Readsalineoftextandcountsalloccurrenceofaparticular word
1. Readthestringandthen displayed
2. Readthestringtobesearchedandthendisplayed
3. SearchingthestringTinstringSandthenperformthefollowingsteps
i. found=strstr(S,T)
ii. iffoundprintthesecondstringisfoundinthefirststringattheposition.Ifnotgotostep5
4. Printthe-1
5. Stop
29
121
112
123
121
4.4 PROCEDURE:
1. Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.C extension.
2. Compile:AltF9
3. Execute:CtrlF9
4.5 SOURCECODE:
Toinsertasubstringintoagivenmainstringfromagivenposition
#include <stdio.h>
#include<string.h>
int main() {
inti,j,p,s1=0,s2=0,tem=0;
charstr1[100],str2[100],temp[100];
printf("Enter the first string : ");
gets(str1);
printf("Enterthesecondstring:");
gets(str2);
printf("Enterthepositiontoinsertthesecondstring:");
scanf("%d",&p);
for(i=0;str1[i]!='\0';i++)
{
s1++;
}
for(i=0;str2[i]!='\0';i++)
{
s1++;
}
for(i=0;temp[i]!='\0';i++)
{
tem++;
}
j=0;
for(i=p;i<s1;i++)
{
temp[j]=str1[i];
j++;
30
121
112
123
121
}
str1[p]='\0';
j=0;
for(i=p;i<(s1+s2);i++)
{
str1[i]=str2[j];
j++;
}
strcat(str1,temp);
puts(str1);
}
Todeletencharactersfromagivenpositioninagivenstring
#include<stdio.h>
int main() {
int i,p,j,s1=0,n;
charstr[100],temp[100];
printf("Enterthestring:");
gets(str);
printf("Entertheposition:");
scanf("%d",&p);
printf("Enterthenumberofcharactersyouwanttodelete:"); scanf("%d",&n);
for(i=0;str[i]!='\0';i++){
s1++;
}
j=0;
for(i=p+n;i<s1;i++){
temp[j]=str[i];
j++;
}
str[p]='\0';
j=0;
for(i=p;i<s1-p+n;i++){
str[i]=temp[j];
j++;
}
31
121
112
123
121
puts(str);
}
Determineifthegivenstringisapalindromeornot
#include<stdio.h>
int main() {
int i,j,s1=0,count=0;
charstr[100],temp[100];
printf("Enterastring:");
gets(str);
for(i=0;str[i]!='\0';i++)
{
s1++;
}
j=0;
for(i=s1-1;i>=0;i--)
{
temp[j]=str[i];
j++;
}
temp[s1] = '\0';
for(i=0;i<s1;i++)
{
if(str[i]==temp[i]&&str[i]!='\0'&&temp[i]!='\0'){
count++;
}
}
if(count==s1)
{
printf("PALINDROME");
}
else
{
printf("NOTPALINDROME");
}
}
32
121
112
123
121
Findastringwithinasentenceandreplaceitwithanotherstring
#include<stdio.h>
int main()
{
charstr1[50],str2[50],str3[50],temp[50]; int
len1, len2, len3, i, j, p, match, k;
printf("\n\n\t ENTER A SENTENCE:");
gets(str1);
printf("\n\n\tENTERASTRINGWHICHYOUWANTTODELETE: ");
gets(str2);
printf("\n\n\tENTERANEWSTRINGWHICHYOUWANTTOINSERT:");
gets(str3);
i=0;//Findingthelengthofsentence
while(str1[i]!='\0')
{
i++;
}
len1=i-1;
i=0;//Findingthelengthofstring,todelete while(str2[i]!='\0')
{
i++;
}
len2=i-1;
i=0;//Findingthelengthofnewstring,toreplace while(str3[i]!='\0')
{
i++;
}
len3 = i-1;
for(i=0;i<=len1;i++)
{
match = 1;
for(j=0;j<=len2;j++)
{
if(str2[j]!=str1[i+j])
33
121
112
123
121
{
match=0;
break;
}
}
if(match){//Whenasubstringisfound,copyremainingStringtotemporaryString
for(k=0,j=i+len2+1;j<=len1;j++,k++){
temp[k]=str1[j];
}
temp[k] = '\0';
for(j=0;j<=len3;j++)
{
str1[i+j]=str3[j];
}
str1[i+j] = '\0';
for(p=0;temp[p]!='\0';p++)
{
str1[i+j+p]=temp[p];
}
str1[i+j+p]='\0';
len1=len1-len2+len3;//Updatelengthvalue i =
i + j;
}
}
printf("\n\n\tOUTPUTIS:");
puts(str1);
}
Readsalineoftextandcountsalloccurrenceofaparticular word
#include<stdio.h>
int main()
{
char str1[50], str2[50], str3[50], temp[50];
intlen1,len2,len3,i,j,p,match,k,count=0;
printf("\n\n\t ENTER A SENTENCE:");
gets(str1);
34
121
112
123
121
printf("\n\n\tENTERASTRINGWHICHYOUWANTTOCOUNTTHETIMESREPEATED: ");
gets(str2);
i=0;//Findingthelengthofsentence
while(str1[i]!='\0')
{
i++;
}
len1=i-1;
i=0;//Findingthelengthofstring,todelete while(str2[i]!='\0')
{
i++;
}
len2 = i-1;
for(i=0;i<=len1;i++)
{
match = 1;
for(j=0;j<=len2;j++)
{
if(str2[j]!=str1[i+j])
{
match=0;
break;
}
}
if(match)
{
count++;
}
}
printf("\t\t%soccurred%dtimes",str2,count);
}
35
121
112
123
121
WEEK-5
FUNCTIONS
5.1 OBJECTIVE:
1. WriteCprogramsthatusebothrecursiveandnon-recursivefunctions
iii. Tofindthefactorialofagiven integer.
iv. Tofindthegreatestcommondivisoroftwogivenintegers.
2. WriteCprogramsthatusebothrecursiveandnon-recursivefunctions
iii. ToprintFibonacciseries.
iv. TosolvetowersofHanoi problem.
3. WriteaCprogramtoprintthetransposeofagivenmatrixusingfunction.
4. WriteaCprogramthatusesafunctiontoreverseagiven string.
5.2 RESOURCES:
DevC++5.11
5.3 PROGRAMLOGIC:
FactorialofagivennumberbyusingRecursivefunction
5.3.1 Start
5.3.2 Readanumber N
5.3.3 Callafunctionfactorial(N)bypassingthevaluesofN
5.3.4 IfN=1thenitreturns1asthefactorial
5.3.5 Otherwiseitcalculatesthefactorialf=N*factorial(N-1)bycallingthesamefunctionagain
andagain
5.3.6 DisplaythefactorialofnumberN
5.3.7 Stop
FactorialofagivennumberbyusingNon-Recursivefunction
1. Start
2. Readanumber N
3. Initializefact=1
4. Calculatefact=fact*NusingaloopanddecrementNvaluetillN=1
5. DisplaythefactorialofnumberN
6. Stop
36
121
112
123
121
GCDof agiventwointegerbyusingRecursiveFunction
1. Start
2. Readtwonumbersaandb
3. Callafunctiongcd(a,b)bypassingthevalueofaandb
4. Checka!=b, then
5. Checka>bthencalculategcdof twonumbersbycallingthefunctiongcd(a-b,b)
6. Otherwisecalculategcdoftwonumbersbycallingthefunctiongcd(a,b-a)
7. Displaythegcdoftwonumbers
8. Stop
GCDof agiventwointegerbyusingNon-RecursiveFunction
1. Start
2. Readtwonumbersaandb
3. Checkifa !=bthen
4. Checkif a>=b-1 thenseta =a–b otherwisesetb=b– a
5. Displaythegcdasthevalueof a.
6. Stop
ToprintFibonacciSeriesusingNon-Recursivefunction
1. Start
2. initializethea=0,b=1
3. readn
4. ifn==1printa gotostep7.elsegotostep5
5. ifn==2printa,bgotostep7elseprinta,b
6. initializei=3
7. ifi<=ndoasfollows.Ifnot gotostep7
8. c=a+b
9. printc
10. a=b
11. b=c
12. incrementivalue
13. gotostep6(i)
14. Stop
37
121
112
123
121
ToprintFibonacciSeriesusingRecursivefunction
1. Start
2. Declarevariablesn,i,c
3. Readvariablen
4. for( c =1 ;c <=n ;c++)
5. DisplayFibonacci(i)
6. Incrementi
7. if( n ==0 )
8. return0
9. elseif ( n== 1)
10. return1
11. return(Fibonacci(n-1)+Fibonacci(n-2))
12. Stop
TosolveTowersofHanoiproblemusingRecursivefunction
1. Start
2. Initializethesource=a,intermediate=c,destination=d
3. readn
4. callthesubprogramHanoirecursion(nvalue,a,b,c)
5. stop
Subprogram:
1. ifn==1callthesubprogramHanoirecursion(num-1, a,c,b)
2. printtheoutputfromatob
3. callthesubprogramHanoirecursion(num-1,b,c,a)
4. returntomainprogram
Toreverseagivenstringusingrecursion
1. Start
2. Reada sentence
3. Usestrrev()functiontoreversea sentence
4. Displaythereversed sentence
5. Stop
5.4 PROCEDURE:
5.5 SOURCECODE:
FactorialofagivennumberbyusingRecursivefunction
#include<stdio.h>i
nt fact(int n)
{
if(n==0)
return 1;
else
returnn*fact(n-1);
}
voidmain()
{
intn,f;
printf("\nenterano.:");
scanf("%d",&n);
f=fact(n);
printf("\nfactorialof%dis%d",n,f);
}
FactorialofagivennumberbyusingNon-Recursivefunction#include<stdio.h>
intfact(intn)
{
int f=1,i;
if((n==0)||(n==1))
return(1);
else
{
for(i=1;i<=n;i++)
f=f*i;
}
return(f);
}
voidmain()
39
121
112
123
121
{
intn;
printf("enterthenumber :");
scanf("%d",&n);
printf("factoriaofnumber%d",fact(n));
}
GCDof agiventwointegerbyusingRecursiveFunction
#include<stdio.h>i
nt gcd(int m,int n)
{
if(n==0)
return m;
else
gcd(n,m%n);
}
voidmain()
{
inta,b,g,l;
printf("\n enter a: ");
scanf("%d",&a);
printf("\n enter b:");
scanf("%d",&b);
g=gcd(a,b);l=(a*b)/g;
printf("\nGCDof%dand%d:%d",a,b,g);
printf("\nLCMof%dand%d: %d",a,b,l);
}
GCDof agiventwointegerbyusingNon-RecursiveFunction
#include<stdio.h>i
nt gcd(int,int);
void main()
{
inta,b,x;
printf("\nentera:");
scanf("%d",&a);
printf("\nenterb:");
40
121
112
123
121
scanf("%d",&b);;
x=gcd(a,b);
printf("G.C.Dof%dand%dis %d",a,b,x);
}
intgcd(inta,int b)
{
int r;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
ToprintFibonacciSeriesusingRecursivefunction
#include<stdio.h>v
oid fib(int);
voidmain()
{
intn;
printf("\nenterthelimitoftheseries:");
scanf("%d",&n);
fib(n);
}
voidfib(intn)
{
int x=0,y=1,z,i;
printf("%5d%5d",x,y);
for(i=2;i<n;i++)
{
z=x+y;
printf("%5d",z);
x=y;
y=z;
}
41
121
112
123
121
}
FibonacciSeriesusingNon-Recursivefunction
#include<stdio.h>i
nt fibo(int,int);
void main()
{
intn,x,i;
printf("\nentertheno.ofterms:");
scanf("%d",&n);
printf("\nthefibonaccisequenceis:");
for(i=0;i<=n;i++)
{
x=fib(i);
printf("%5d",x);
}
}
intfib(intn)
{
if(n==0||n==1)
return n;
else
returnfib(n-1)+fib(n-2);
}
TowersofHanoiproblemusingNon-Recursivefunction
#include<stdio.h>
voidHanoinonrecursion(intnum,charsndl,charindl,chardndl)
{
charstkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp;
int top,add;
top=NULL;
one:
if(num==1)
{
printf("\nMovetopdiskfromneedle%ctoneedle%c",sndl,dndl); goto
four;
}
42
121
112
123
121
two:
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=3;
num=num-1;
sndl=sndl;
temp=indl;
indl=dndl;
dndl=temp;
gotoone;
three:
printf("\nMovetopdiskfromneedle%ctoneedle%c",sndl,dndl); top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=5;
num=num-1;
temp=sndl;
sndl=indl;
indl=temp;
dndl=dndl;
gotoone;
four:
if(top==NULL)
return;
num=stkn[top];
sndl=stksndl[top];
indl=stkindl[top];
dndl=stkdndl[top];
add=stkadd[top];
43
121
112
123
121
top=top-1;
if(add==3)
gotothree;
elseif(add==5)
gotofour;
}
voidmain()
{
intno;
printf("Entertheno.ofdisstobetransferred:");
scanf("%d",&no);
if(no<1)
printf("\nThere'snothingtomove");
else
printf("\n nonrecursive");
Hanoinonrecursion(no,'A','B','C');
}
TosolveTowersofHanoiproblemusingRecursivefunction
#include<stdio.h>
voidHanoirecursion(intnum,charndl1,charndl2,charndl3)
{
if(num==1)
{
printf("Movetopdiskfromneedle%ctoneedle%c",ndl1,ndl2);
return;
}
Hanoirecursion(num-1,ndl1,ndl3,ndl2);
printf("Movetopdisfromneedle%ctoneedlle%c",ndl1,ndl2);
Hanoirecursion(num-1,ndl3,ndl2,ndl1);
}
voidmain()
{
intno;
printf("Entertheno.ofdisktobetransferred:");
scanf("%d",&no);
if(no<1)
44
121
112
123
121
printf("\nThere'snothingtomove");
else
printf("\n recursive");
Hanoirecursion(no,'A','B','C');
}
Toreverseagivensentencebyusing recursion
#include<stdio.h>
#include<string.h>
void Reverse();
intmain()
{
printf("Enterasentence:");
Reverse();
return 0;
}
voidReverse()
{
char c;
scanf("%c",&c);
if(c!='\n')
{
Reverse();
printf("%c",c);
}
}
45
121
112
123
121
5.6 INPUT/OUTPUT:
FactorialofagivennumberbyusingRecursive/NonRecursivefunction
GCDof agiventwointegerbyusingRecursive/NonRecursiveFunction
46
121
112
123
121
ToprintFibonacciSeriesusingRecursive/Non-Recursivefunction
TowersofHanoiproblemusingRecursive/Non-Recursivefunction
47
121
112
123
121
Toreverseagivenstring
Toreverseagivennumberusingrecursion
48
121
112
123
121
WEEK-6
POINTERS
6.1 OBJECTIVE:
1. WriteaCprogramtoconcatenatetwostringsusingpointers.
2. WriteaCprogramtofindthelengthofstringusingpointers.
3. WriteaCprogramtocomparetwostringsusingpointers.
4. WriteaCprogramtocopyastringfromsourcetodestinationusingpointers.
5. WriteaCprogramtoreverseastringusingpointers.
6.2 RESOURCES:
DevC++5.11
6.3 PROGRAMLOGIC:
Toconcatenatetwostringsusingpointers
6.3.1 Start
6.3.2 Readtwostringsstr1&str2
6.3.3 Repeatloopuntilendofthecharacterinfirststringstr1andcopyeachcharacterintothird string
str3.
6.3.4 Repeat loop until end of the character in second string str2 and copy each character into
thirdstring str3.
6.3.5 AddlastcharacterasNULLcharacter(‘\0’)
6.3.6 Printthirdstring
6.3.7 Stop
Tofindthelengthofstringusingpointers
1. Start
2. Readonestringp
3. Assignppointertop1pointer
4. Repeatloopuntilendofthecharacterinthestringp1andeachtimeincrementlength
5. Printlengthofthestring
6. Stop
49
121
112
123
121
Tocomparetwostringsusing pointers.
1. Start
2. Readtwostringsstr1&str2
3. Repeatloopuntilfirststringcharacterandsecondstringcharacterequals
4. Iffirstandsecondreachendofthestringthentwostringsare equal
5. Elsetwostringsarenotequal
6. Stop
Tocopyastringfromsourcetodestinationusing pointers.
1. Start
2. ReadonestringSource
3. Assigntargetpointertotpointer
4. Repeatloopuntilendofthecharacterinthestringsourceandeachcharactercopyintotarget string
5. Printdestinationstringt
6. Stop
Toreverseastringusingpointers
1. Start
2. Readonestringstrptr
3. Repeatloopuntil endofthecharacterinthestringstrptrandcountthenumbercharactersinthe string
4. Repeatloopuntilcompleteallcharactersinthestringusingcountvariableandcopyeach
character from strptr to revptr
5. Printreversestringrevprt
6. Stop
6.4 PROCEDURE:
6.4.1 Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
6.4.2 Compile: F9
6.4.3 Execute: F10
6.5 SOURCECODE:
Toconcatenatetwostringsusingpointers
#include<stdio.h>#
define SIZE 20
50
121
112
123
121
voidconcat(char*,char*); int
main()
{
charstring1[SIZE]="\0",string2[SIZE]="\0";
printf("Enter String 1:\n");
gets(string1);printf("Enter
String2:\n"); gets(string2);
concat(string1,string2);
return 0;
}
voidconcat(char*str1,char*str2)
{
char *conc=str1;
while(*str1!='\0')
str1++;
*str1='';
++str1;
while(*str2!='\0')
{
*str1=*str2;
str1++,str2++;
}
*str1='\0';
printf("ConcatenatedString:\n");
puts(conc);
}
Tofindthelengthofstringusingpointers
#include<stdio.h>
#include<string.h>
void main()
{
chara[10],*ptr;
int i=0;
printf("\nenterastring:");
gets(a);
51
121
112
123
121
ptr=a;
while(*ptr!='\0')
{
i++;
ptr++;
}
printf("\nlengthofastringis%d",i);
}
Tocomparetwostringsusing pointers.
#include<stdio.h>
#include<string.h>
intcompare_strings(char*,char*);
voidmain()
{
chars1[50],s2[50],*p1,*p2;
int res;
printf("\nenterastrings1:");
gets(s1);
printf("\nenterastrings2:");
gets(s2);
res=compare_strings(s1,s2);
if(res==0)
printf("\nboththestringsareidentical");
else
printf("\nboththestringsarenotidentical");
}
intcompare_strings(char*p1,char*p2)
{
while(*p1==*p2)
{
if(*p1=='\0'||*p2=='\0')
break;
p1++;
p2++;
}
if(*p1=='\0'||*p2=='\0')
52
121
112
123
121
return0;
else
return-1;
}
Tocopyastringfromsourcetodestinationusing pointers.
#include<stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enterstrings1:");
scanf("%s",s1);
for(i=0;s1[i]!='\0';++i)
{
s2[i]= s1[i];
}
s2[i]='\0';
printf("copiedstring:%s",s2);
return 0;
getch();
}
Toreverseastringusingpointers.##i
nclude<stdio.h> #include<string.h>
voidmain()
{
char*cp,s[30];
int i,length;
printf("\nenterastring:"); gets(s);
cp=s;
length=strlen(s);
printf("\nthereverseofthestringis:");
for(i=length;i>=0;i--)
printf("%c",*(cp+i));
}
53
121
112
123
121
printf("\n\nReversedstringis:%s",rev);
getch();
}
6.6 INPUT/OUTPUT:
Toconcatenatetwostringsusingpointers
Tofindthelengthofstringusingpointers
54
Tocomparetwostringsusing pointers.
Tocopyastringfromsourcetodestinationusing pointers.
55
Toreverseastringusingpointers
56
WEEK-7
STRUCTURESANDUNIONS
7.1 OBJECTIVE:
1. WriteaCprogramthatusesfunctionstoperformthefollowingoperations:
i. Readingacomplexnumber
ii. Writingacomplex number
iii. Additionandsubtractionoftwocomplexnumbers
iv. Multiplication of two complex numbers. Note: represent complex number using a
structure.
2. WriteaCprogramtocomputethemonthlypayof100 employeesusingeachemployee’sname, basic
pay. The DA is computed as 52% of the basic pay. Gross-salary (basic pay + DA). Print the
employees name and gross salary.
3. Create a Book structure containing book_id, title, author name and price. Write a C program to
pass a structure as a function argument and print the book details.
4. Create a union containing 6 strings: name, home_address, hostel_address, city, state and zip.
Write a C program to display your present address.
5. Write a C program to define a structure named DOB, which contains name, day, month and
year. Using the concept of nested structures display your name and date of birth.
7.2 RESOURCES:
DevC++5.11
7.3 PROGRAMLOGIC:
ToperformtheAddition,Substraction,MultiplicationandDivisonoperationsbetweencomplex
numbers
7.2.1 Start
7.2.2 Declarestructureforcomplexnumbers
7.2.3 Readthecomplex number
7.2.4 Readchoice
7.2.5 Ifchoice=1thenadditionoperationwillperformanditcontainsfollowingsteps
7.2.5.1 w.realpart=w1.realpart+w2.realpart;
7.2.5.2 w.imgpart=w1.imgpart+w2.imgpart;gotostep4
7.2.6 Ifchoice=2thenmultiplicationoperationwillperformanditcontainsfollowing steps
7.2.6.1 w.realpart=(w1.realpart*w2.realpart)-(w1.imgpart*w2.imgpart);
7.2.6.2 w.imgpart=(w1.realpart*w2.imgpart)+(w1.imgpart*w2.realpart);gotostep4
7.2.7 Ifchoice=0thenexitoperationwillperform
57
7.2.8 Ifw.imgpart>0thenprintrealpart+imgpartelsePrintrealpart.
7.2.9 Stop
Printtheemployeesnameandgrosssalary
1. Start
2. Declarestructureforemployeedetails
3. Read100employee details
4. Repeatloop100employeesandcalculategrosssalaryofeach employee
5. Printeachemployeenameandgrosssalary
6. Stop
Topassastructureasafunctionargumentandprintthebookdetails
1. Start
2. Declarestructureforbookdetails
3. Assignabookdetailstostructure
4. Passastructureasargumentinfunction
5. Printthebookdetailsfromthefunction
6. Stop
Todisplayyourpresentaddressusingunion
1. Start
2. Declareunionforaddress details
3. Assignaddressto union
4. Printunion details
5. Stop
Todisplayyournameanddateofbirthusingnested structure
1. Start
2. Declarenestedstructureforaperson
3. Assignpersondetailstostructure
4. Printstructuredetails
5. Stop
58
7.4 PROCEDURE:
7.4.1 Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
7.4.2 Compile:F9
7.4.3 Execute:F10
7.5 SOURCECODE:
ToperformtheAddition,Subtraction,MultiplicationandDivisonoperationsbetweencomplex
numbers
#include<stdio.h>
#include<string.h>s
truct complex1
{
intr;
inti;
}c1,c2,c3;
void add(struct complex1 c1,struct complex1 c2);
void sub(struct complex1 c1,struct complex1 c2);
voidmulti(structcomplex1c1,structcomplex1c2); void
main()
{
printf("\nenterfirstcomplexno:");
scanf("%d%d",&c1.r,&c1.i);
printf("\nentersecondcomplexno:");
scanf("%d%d",&c2.r,&c2.i);
printf("\n enter first complex no:%d+i%d",c1.r,c1.i);
printf("\nentersecondcomplexno:%d+i%d",c2.r,c2.i);
add(c1,c2);
sub(c1,c2);
multi(c1,c2);
}
voidadd(structcomplex1c1,structcomplex1c2)
{
c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i;
printf("\nadditionoftwocomplexnumbersis%d+i%d",c3.r,c3.i);
59
}
voidsub(structcomplex1c1,structcomplex1c2)
{
c3.r=c1.r-c2.r;
c3.i=c1.i-c2.i;
printf("\nsubtractionoftwocomplexnumbersis %d+i%d",c3.r,c3.i);
}
voidmulti(structcomplex1c1,structcomplex1c2)
{
c3.r=(c1.r*c2.r)-(c1.i*c2.i);
c3.i=(c1.r*c2.i)+(c1.i*c2.r);
printf("\nmultiplicationoftwocomplexnumbersis%d+i%d",c3.r,c3.i);
}
Printtheemployeesnameandgrosssalary
#include<stdio.h>st
ruct employee
{
charname[20];
float basic;
float da;
float gross;
}e[5];
voidmain()
{
inti;
for(i=0;i<5;i++)
scanf("%s%f",e[i].name,&e[i].basic);
for(i=0;i<5;i++)
{
e[i].da=52.0/100*e[i].basic;
e[i].gross=e[i].da+e[i].basic;
printf("\nname=%sgross=%f",e[i].name,e[i].gross);
}
60
Topassastructureasafunctionargumentandprintthebookdetails
#include<stdio.h>
#include<string.h>s
truct book
{
intbookid;
chartitle[30];
charauthor[20];
float price;
};
voidprint_book(structbookb1);
void main()
{
structbookb1;
printf("\nenter book details:");
scanf("%d%s%s%f",&b1.bookid,b1.title,b1.author,&b1.price);
print_book(b1);
}
voidprint_book(structbookb1)
{
printf("\nbookdetails:%d\t%s\t%s\t%f",b1.bookid,b1.title,b1.author,b1.price);
}
Todisplayyourpresentaddressusingunion
#include<stdio.h>
#include<string.h>
union details
{
charname[20];
char home_add[30];
charhostel_add[30];
char city[10];
charstate[10];
int pincode;
}a;
voidmain()
{
61
strcpy(a.name,"rama");
printf("\n %s",a.name);
strcpy(a.home_add,"1-83/10,jubliehills");
printf("\n %s",a.home_add);
strcpy(a.hostel_add,"iare college");
printf("\n %s",a.hostel_add);
strcpy(a.city,"hyderabad");
printf("\n %s",a.city);
strcpy(a.state,"telangana");
printf("\n %s",a.state);
a.pincode=500043;
printf("\n %d",a.pincode);
getch();
}
Todisplayyournameanddateofbirthusingnested structure
#include<stdio.h>
#include<string.h>
void main()
{
structperson
{
charfname[20];
charlname[10];
struct dob
{
int
day;intmo
nth; int
}d; year;
}p;
printf("\n enter the person name and dob:");
scanf("%s%s%d%d%d",p.fname,p.lname,&p.d.day,&p.d.month,&p.d.year);
printf("\n my name is %5s %5s",p.fname,p.lname);
printf("\nmydobis%d-%d-%d",p.d.day,p.d.month,p.d.year);
}
62
7.6 INPUT/OUTPUT:
ToperformtheAddition,Subtraction,MultiplicationandDavisonoperationsbetweencomplex
numbers
Printtheemployeesnameandgrosssalary
To
63
Passastructureasafunctionargumentandprintthebook details
Todisplayyourpresentaddressusingunion
64
Todisplayyournameanddateofbirthusingnested structure
7.6.1 .
65
WEEK-8
FILES
8.1 OBJECTIVE:
1. WriteaCprogramtodisplaythecontentsofafile.
2. WriteaCprogramtocopythecontentsofonefiletoanother.
3. WriteaCprogramtoreversethefirstncharactersinafile,wherenisgivenbytheuser.
4. TwofilesDATA1andDATA2containsortedlistsofintegers.WriteaCprogramto mergethe contents
of two files into a third file DATA i.e., the contents of the first file followed by those of the
second are put in the third file.
5. WriteaCprogramtocounttheno.ofcharacterspresentinthefile.
8.2 RESOURCES:
DevC++5.11
8.3 PROGRAMLOGIC:
Todisplaythecontentsofafileonscreen
8.3.1 Start
8.3.2 Readfilename
8.3.3 Openfileinreadmode
8.3.4 Repeatuntilendofthefileandprintthecontentsifthefile
8.3.5 Closethefile
8.3.6 Stop
Copythecontentsfromonefileto another
1. Start
2. readcommandlinearguments
3. checkifnoofarguments=3ornot.Ifnotprint invalidnoofarguments
4. opensourcefileinreadmode
5. ifNULLpointer,thenprintsourcefilecannotbeopen
6. opendestinationfileinwritemode
7. ifNULLpointer,thenprintdestinationfilecannotbeopen
8. readacharacterfromsourcefileandwritetodestinationfileuntilEOF
9. Closesourcefileanddestinationfile
10. Stop
66
Reversencharacterina file
1. Start
2. readthecommandline arguments
3. checkifarguments=3ornot,Ifnotprintinvalidnoofarguments
4. opensourcefileinreadmode
5. ifNULLpointer,thenprintfilecannotbeopen
6. Storenoofcharstoreversein k
7. K=*argv[2]-48
7. readtheitemfromfilestreamusingfread
8. Storecharsfromlastpositiontoinitialpositioninanotherstring(temp)
9. printthetempstring
10. Stop
Mergethecontentsoftwofilesintothirdone
1. Openfile1.txtandfile2.txtinreadmode.
2. Openfile3.txtinwritemode.
3. Runalooptoonebyonecopycharactersoffile1.txttofile3.txt.
4. Runalooptoonebyonecopycharactersoffile2.txttofile3.txt.
5. Closeall files.
8.4 PROCEDURE:
8.4.1 Create:openDevC++5.11writeaprogramafterthatsavetheprogramwith.Cextension.
8.4.2 Compile:F9
8.4.3 Execute:F10
8.5 SOURCECODE:
Todisplaythecontentsofafileonscreen
#include<stdio.h>v
oidmain()
{
FILE*fp;
char ch;
fp=fopen("file.txt","r");
67
if(fp==NULL)
{
printf("fileopeningproblem");
return;
}
while(!feof(fp))
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}
Copythecontentsfromonefiletoanother
#include<stdio.h>v
oidmain()
{
FILE*fp1,*fp2; char
ch;
fp1=fopen("old.txt","r");
fp2=fopen("new.txt","w");
if(fp1==NULL||fp2==NULL)
{
printf("fileopeningproblem");
return;
}
while(!feof(fp1))
{
ch=fgetc(fp1);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
getch();
}
68
Reversencharacterinafile#inclu
de <stdio.h>#include<string.h>
intmain()
{
FILE *fp;
chara[50];
int i,n,count=0;
fp=fopen("program.txt","r");
if(fp==NULL)
{
printf("\nfileopeningproblem");
return;
}
printf("\nenterthenoofcharcterstoreverse:");
scanf("%d",&n);
while(count<n)
{
a[count]=fgetc(fp);
count++;
}
a[count]='\0';
fputs(strrev(a),stdout);
fclose(fp);
getch();
}
Mergethecontentsoftwofilesintothirdone
#include<stdio.h>v
oid main()
{
FILE*fp1,*fp2,*fp3;
char ch;
fp1=fopen("program.txt","r");
fp2=fopen("new.txt","r");
69
fp3=fopen("merge.txt","a");
if(fp1==NULL||fp2==NULL||fp3==NULL)
{
printf("fileopeningproblem");
return;
}
while(!feof(fp1))
{
ch=fgetc(fp1);
fputc(ch,fp3);
}
}
70
Copythecontentsfromonefiletoanother
Reversencharacterina file
71
Mergethecontentsoftwofilesintothirdone
72
73