Introduction To Programming Lab Manual
Introduction To Programming Lab Manual
INTRODUCTION TO
PROGRAMMING
LABORATORY MANUAL
Department of
COMPUTERSCIENCE&ENGINEERING
Name
Roll No.
Class I-B.TECH-ISEM
Branch CSE
Regulation R23
Name of theLab INTRODUCTION TO PROGRAMMING
Academic year
INCHARGE H.O.D
Department of Computer Science & Engineering A.Soma Raju M.Tech.,MD,CSE
ST.MARY’S GROUP OF INSTITUTIONS GUNTUR FOR WOMEN
JNTU-KAKINADA, Chebrolu, Andhra Pradesh, India- 533449
VISION
To evolve as a Premier Engineering Institution in the Country with it’s continues strive for
excellence in Education, Research and Technological Services.
MISSION
Togeneratethecommunityofhighlylearnedstudentswithgreateracquirementofknowledge and to
apply it professionally with due consideration for ecological, economic and ethical issues.
Toprovideknowledge-basedtechnologicalservicesatthebest satisfactionofsocietyand for the
industrial needs.
Tofostertheresearchand disseminateresearch findings.
Tobuildincapabilitiesforadvancingeducation,technology, values, managementandresearch at
international standards.
VISION
To explore innovative approaches to enhance and expand learning opportunities through
the integration of various technologies.
Tobuildastrongresearchandteachingenvironmentthatrespondstothereal-time challenges of
the industry
MISSION
To inculcate the blend of competence, aptitude of knowledge and investigate flair
through devising an ambient environment for sustainable learning.
To transform attitude, values, priorities by changing mindset and instill positive outlook
for socially conscious intellectual development.
Incubate,applyandspreadinnovativeideastoevolvethedepartmentasacentreof excellence in
thrust areas
PROGRAMEDUCATIONALOBJECTIVES(PEO):
PEO1Provideastrongfoundationrequiredtocomprehend,analyse,designanddevelop solutions to real
world computing problems.
PEO2Exposethe studentsto industrypractices for providing computing solutionsusing current
models and techniques.
PEO3Enablethestudentstopursuehigherstudiesandactiveresearch.
PEO4Fostersustainedprofessionaldevelopmentthroughlife-longlearningtoadaptnew computing
technologies
PO7.EnvironmentandSustainability:Understandtheimpactoftheprofessional 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 responsibilitiesand
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 communityand withsocietyat large, suchas, 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 principlesand applythese to one’sownwork, asamember
and leader in a team, to manage projects and in multidisciplinary environments.
PO12.Life-longLearning: Recognizetheneed for,andhave thepreparationandabilityto engage
in independent and lifelong learning in the broadest context of technological
change
PSO1Ability to apply their skills in the field of algorithms, networking, web design, cloud
computing and databases.
Syllabus
UNIT I
WEEK1
Objective: Getting familiar with the programming environment on
thecomputer and writing the first program.
SuggestedExperiments/Activities:
Tutorial1:Problem-solvingusingComputers.
Lab1:Familiarizationwithprogrammingenvironment
i) BasicLinuxenvironmentanditseditorslikeVi,Vim&Emacsetc.
ii) ExposuretoTurboC,gcc
iii) Writingsimpleprogramsusingprintf(),scanf()
WEEK2
Objective: Getting familiar with how to formally describe a solution to
aprobleminaseriesoffinitestepsbothusingtextualnotationandgraphic notation.
SuggestedExperiments/Activities:
Tutorial 2: Problem-solving using Algorithms and Flow
charts.Lab1:Convertingalgorithms/flowchartsintoCSourcecode.
Developingthealgorithms/flowchartsforthefollowingsampleprograms
i) Sumandaverageof3numbers
ii) ConversionofFahrenheittoCelsiusandviceversa
iii) Simpleinterestcalculation
WEEK3
Objective: Learn how to define variables with the desired data-type,
initializethemwithappropriatevaluesandhowarithmeticoperatorscanbeusedwith
variables and constants.
SuggestedExperiments/Activities:
Tutorial3:Variabletypesandtypeconversions:
Lab3: Simple computational problemsusing arithmeticexpressions.
i) Findingthesquarerootofagivennumber
ii) Findingcompoundinterest
Departmentof CSE,SMGGEngineeringCollege
WEEK13:
Objective: Explore the basic difference between normal and pointer
variables,Arithmeticoperationsusingpointersandpassingvariablestofunctionsusing
pointers
SuggestedExperiments/Activities:
Tutorial13:Callbyreference,danglingpointers
Lab13:SimplefunctionsusingCallbyreference,Danglingpointers.
i) WriteaCprogramtoswaptwonumbersusingcallbyreference.
ii) DemonstrateDanglingpointerproblemusingaCprogram.
iii) WriteaCprogramtocopyonestringintoanotherusingpointer.
iv) WriteaCprogramtofindnooflowercase,uppercase,digitsandother
characters using pointers.
WEEK14:
Objective:TounderstanddatafilesandfilehandlingwithvariousfileI/O
functions.Explorethedifferencesbetweentextandbinaryfiles.
SuggestedExperiments/Activities:
Tutorial 14: File handling Lab
14: File operations
i) WriteaCprogramtowriteandreadtextintoafile.
ii) Write a Cprogram to write and read text into a binary file using
fread()andfwrite()
iii) Copythecontentsofonefiletoanotherfile.
iv) WriteaCprogramtomergetwofilesintothethirdfileusingcommand-line
arguments.
v) Findno.oflines,wordsandcharactersinafile
vi) WriteaCprogramtoprintlastncharactersofagivenfile
DepartmentofIT,GIETEngineeringCollege
DEPARTMENTOFINFORMATION TECHNOLOGY
LESSONPLAN
COURSE: COMPUTERP ROGRAMMING LAB
ACADEMICYEAR: 2025-26
i) BasicLinuxenvironmentanditseditorslike Vi,
Vim & Emacs etc.
1 Projector 3
ii) ExposuretoTurboC,gcc
iii) Writingsimpleprogramsusingprintf(),scanf()
i) Sumandaverageof3numbers
ii) Conversion of Fahrenheit to Celsius and
2 Projector 3
viceversa
iii) Simpleinterestcalculation.
i) Findingthesquarerootofagivennumber
ii) Findingcompoundinterest
3 Projector 3
iii) Areaofatriangleusingheron’sformulae
iv) Distance travelled by an object
i) Evaluatethefollowingexpressions.
a. A+B*C+(D*E)+F*G
b. A/B*C-B+A*D/3
c. A+++B---A
4 d. J=(i++)+(++i) Projector 3
Department of cse
i) C program to find the max and min of four
numbers using if-else.
ii) Cprogramtogenerateelectricitybill.
iii) Findtherootsofthequadraticequation.
5 Projector 3
iv) C program to simulate a calculator using
switch case.
v) Cprogramtofindthegivenyearisaleapyear
ornot.
i) Find the factorial of given number using
anyloop.
ii) Find the given number is a primeor not.
6 Projector 3
iii) Computesineandcosseries
iv) Checkinganumberpalindrome
v) Constructapyramidofnumbers
i) Findtheminandmaxofa1-Dintegerarray.
ii) Performlinearsearchon1Darray.
iii) Thereverseofa1Dintegerarray
7 Projector 3
iv) Find 2’s complement of the given binary
number.
v) Eliminateduplicateelementsinanarray.
i) Additionoftwomatrices
ii) Multiplicationtwomatrices
iii) Sortarrayelementsusingbubblesort
8 iv) Concatenatetwostringswithoutbuilt-in Projector 3
functions
v) Reverseastringusingbuilt-inandwithout
built-instringfunctions
Departmentof CSE
i) Cprogramtofindthesumofa1Darrayusing
malloc()
ii) Cprogramtofindthetotal,averageofn
students using structures
iii) Enter n students data using calloc() and
9 Projector 3
display failed students list
iv) Read student name and marks from the
command line and display the student details
along with the total.
v) Cprogramtoimplementrealloc()
i) Create and display a singly linked list using
self-referential structure.
ii) Demonstrate the differences between
10 structures and unions using a C program. Projector 3
iii) Cprogramtoshift/rotateusingbitfields.
iv) Cprogramtocopyonestructurevariableto
another structure of the same type.
i) CfunctiontocalculateNCRvalue.
ii) Cfunctiontofindthelengthofastring.
iii) Cfunctiontotransposeofamatrix.
11 Projector 3
iv) C function to demonstrate numerical
integrationofdifferentialequationsusingEuler’s
method
i) recursive function to generate Fibonacci
series.
ii) recursive function to find the lcm of two
numbers.
12 iii) recursive function to find the factorial of a Projector 3
number.
iv) CProgramtoimplementAckermannfunction
using recursion.
v) recursive function to find the sum of series.
Department of CSE
i) C program to swap two numbers using call
byreference.
ii) DemonstrateDanglingpointerproblemusing a
C program.
13 iii) Cprogramtocopyonestringintoanother Projector 3
using pointer.
iv) Cprogramtofindnooflowercase,
uppercase, digits and other
charactersusingpointers.
i) Cprogramtondreadtextintoafile.
ii) C program to nd read text into a binary
fileusing fread() and fwrite()
iii) Copythecontentsofonefiletoanotherfile.
iv) Cprogramtomergetwofilesintothethird file
14 using command-line Projector 3
arguments.
v) Find no. of lines, words and characters in a
file
vi) Cprogramtoprintlastncharactersofa
givenfile.
TotalNo. ofhours:42
Textbooks:
1. AjayMittal, ProgramminginC:Apracticalapproach,Pearson.
2. ByronGottfried,Schaum'sOutlineofProgrammingwithC, McGrawHill
ReferenceBooks:
1. BrianW.KernighanandDennisM.Ritchie,TheCProgrammingLanguage,PrenticeHallof India
2. CProgramming,AProblem-SolvingApproach,Forouzan,Gilberg,Prasad, CENGAGE
Department of CSE
28. Additionoftwomatrices
29. Multiplicationtwomatrices
30. Sortarrayelementsusingbubblesort
31. Concatenatetwostringswithoutbuilt-infunctions
32. Reverseastringusingbuilt-inandwithoutbuilt-instringfunctions
33. Cprogramtofindthesumofa1Darrayusingmalloc()
34. C program to find the total, average of n students using
structures
35. Enternstudentsdatausingcalloc()anddisplayfailedstudentslist
36. Read student name and marks from the command line and display the
student
37. detailsalongwiththetotal.
38. Cprogramtoimplementrealloc()
39. Createand displaya singlylinked listusing self-referential structure.
40. Demonstratethedifferences betweenstructures andunions usinga C
41. program.
42. Cprogramtoshift/rotateusingbitfields.
43. Cprogramtocopyonestructurevariabletoanotherstructureof
Thesame type.
44. CfunctiontocalculateNCRvalue.
45. Cfunctiontofindthelengthofastring.
46. Cfunctiontotransposeofamatrix.
47. Cfunctiontodemonstratenumericalintegrationofdifferential
48. equationsusingEuler’smethod
49. recursivefunctiontogenerateFibonacciseries.
50. recursivefunctiontofindthelcmoftwonumbers.
51. recursivefunctiontofindthefactorialofanumber.
52. CProgramtoimplement Ackermannfunctionusingrecursion.
53. recursivefunctiontofindthesumofseries.
54. Cprogramtoswaptwonumbersusingcallbyreference.
55. DemonstrateDanglingpointerproblemusingaCprogram.
56. Cprogram tocopy one stringinto anotherusing pointer.
57. Cprogramtofind nooflowercase,uppercase,digitsandother
DepartmentofIT,GIETEngineeringCollege
58. charactersusingpointers.
59. Cprogramtowriteandreadtextintoafile.
60. Cprogramtowriteandreadtextintoabinaryfileusingfread()and
61. fwrite()
62. Copythecontentsofonefiletoanotherfile.
63. Cprogramtomergetwofilesintothethirdfileusingcommand-line
64. arguments.
65. Findno.oflines,wordsandcharactersinafile
66. Cprogramtoprintlastncharactersofagivenfile
DepartmentofIT,GIETEngineeringCollege
LinuxEnvironmentandItsEditors
LinuxEnvironmentandItsEditors
Exp.No:
Date:
1. Aim:
BasicLinuxenvironmentanditseditorslikeVi, Vim&Emacsetc.
2. SoftwareRequired:
Linux
3. Theory:
Creating a basic Linuxenvironment and installing text editorslike Vi, Vim, and Emacscan be
doneonaLinux-basedsystem.Here'sastep-by-stepguideto set upabasicLinuxenvironment and
install these text editors:
1. **ChooseaLinuxDistribution**:
You can choose a Linux distribution that suits your preferences. Popular choices include
Ubuntu, Debian, Fedora, CentOS, and others. You can download the ISO image of the
distributionyouprefer fromtheofficialwebsiteandinstallit onavirtualmachineoraphysical computer.
2. **InstallLinux**:
FollowtheinstallationinstructionsforyourchosenLinuxdistribution.Duringtheinstallation, you
will be asked to create a user account and set a password. Ensure that you have internet access.
3. **Updatethe System**:
Afterinstallation, open a terminal and update your system to ensure you have the latest
software packages. Use the package manager that comes with your distribution:
OnDebian/Ubuntu:
```bash
Deptof CSE
LinuxEnvironmentandItsEditors
sudoaptupgrade
```
OnFedora:
```bash
sudodnfupdate
```
4. **InstallTextEditors**:
-**Vi/Vim**:
```bash
sudoapt installvim#OnDebian/Ubuntu
```
-**Emacs**:
YoucaninstallEmacsusingyourdistribution'spackagemanager:
```bash
sudoaptinstallemacs#OnDebian/Ubuntu
Deptof CSE
LinuxEnvironmentandItsEditors
sudodnfinstallemacs#OnFedora
```
5. **Usage**:
```bash
vifilename.txt
```
```bash
emacsfilename.txt
```
6. **LearntheEditors**:
Deptof CSE
ExposuretoTurboC,gcc
ExposuretoTurboC,gcc
Exp.No:
Date:
1. Aim:
Exposureto TurboC,gcc
2. SoftwareRequired:
TurboC
3. Theory:
Exposure to Turbo C and GCC (GNU Compiler Collection) can be valuable for individuals
interested inprogramming and software development, especiallyin the C and C++ programming
languages. These two development environments have been widely used for many years and
offer different advantages.
1. **TurboC**:
- **Advantages**:
- Simpleandeasy-to-useIDE,especiallyforbeginners.
- Well-suitedforlearningCandC++programmingbasics.
- Providedacompactandefficientdevelopment environmentforitstime.
- **Disadvantages**:
- Outdatedandnolongeractivelymaintained.
- Limitedcompatibilitywithmodernoperatingsystems.
ExposuretoTurboC,gcc
- MaynotsupportallthefeaturesofthelatestC/C++ standards.
2. **GCC(GNUCompiler Collection)**:
- **Overview**: GCC is a powerful and widely used collection of compilers and tools for
various programming languages, including C, C++, and others. It is open-source software and
can be used on various platforms.
- **Advantages**:
- Cross-platformcompatibility;itcanbeusedonvariousoperating systems.
- SupportsthelatestCandC++standardsandfeatures.
- Highlyconfigurableand extensible.
- Continuouslyupdatedandmaintainedbytheopen-source community.
- **Disadvantages**:
- Mayhaveasteeperlearningcurveforbeginnersduetoitsconfigurability.
- Requiresfamiliaritywiththecommand-lineinterface.
Exposure to both Turbo C and GCC can provide a balanced understanding of the history and
evolution of C and C++ development tools:
- Turbo C can help beginners grasp the basics of C and C++ programming in a simple and user-
friendly environment.
- GCC can be essential for those who want to work on modern and cross-platformprojects, as it
provides access to the latest language features and a wide range of development tools.
In the real world, many professional C and C++ developers primarily use GCC or other modern
IDEs like Visual Studio Code, CLion, or Xcode, depending on their platform and project
requirements. However, understanding the foundations and history of these tools can be
beneficialforawell-roundedknowledgeofprogramminginCandC++.
SimpleProgramUsingprintf(),scanf()
ExpNo:
Date:
1. Aim:
2. SoftwareRequired:
TurboC
3. Theory:
The input and output functions used in C language.printf( ) is a output statement used to display
the output on the console deviece . scanf( ) is the input statement which is used to read the
information from the user. These functions can be used by including the header file “stdio.h” in
the program.
4. Program:
#include<stdio.h>
#include<conio.h>
main()
printf("######"); printf("\
n#");
printf("\n#");
printf("\n####");
printf("\n#");
printf("\n#");
getch();
Dept of CSE
SimpleProgramUsingprintf(),scanf()
5. SampleInputandOutput:
######
#
#
####
#
#
4. Program:
#include<conio.h>
#include<stdio.h>
main()
inta,b;
printf("Enter a value:");
scanf("%d",&a); printf("\
nEnterbvalue:");
scanf("%d",&b);
printf("\na=%d\nb=%d",a,b); getch();
return0;
Dept of CSE
SimpleProgramUsingprintf(),scanf()
5. SampleInputandOutput:
Enter a value: 6
Enterbvalue:34
a=6
b=34
6. Result:
SuccessfullyExecuted.
7. Reference:
https://www.programiz.com/c-programming/examples
Dept of CSE
Calculating Marks
SumandAverageofThree Numbers
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindsumandaverageofthreenumbers.
2. SoftwareRequired:
TURBOC
3. Theory:
Inthisprogram,wefirstdeclared fourvariablesx,y,z,sum.
Afterthatcreatedanothervariablenamedavgwiththehelpoffloatdatatype.
Inthis avg variable, we willstorethe average ofthe numberthree and inthe sumvariable, we will
store the sum of the number three.
Afterdeclaringthe variables,wegot input threenumbersfromtheuserandstorethosevalues in the
x, y, z variables.
Afterthis,weCalculatethesum of threenumbersusingtheformula(sum =x +y +z) and stored its
result in the sum variable.
Afterthat,weprintthesumofthree numbers.
Afterthis,weCalculatetheaverageofthreenumbersusingtheformula(average= sum/count) and
stored its result in the avg variable.
Finally, we printed the stored value in this avg variable onthe screen with the help ofprintf()
function.
4. Program:
#include<stdio.h>
#include<conio.h>
main()
inta,b,c;
Deptof CSE
Calculating Marks
float sum,avg;
printf("Enterthreevalues:");
scanf("%d%d%d",&a,&b,&c),
sum=a+b+c;
avg=sum/3;
nTheaverageofthreenumbers=%f",avg); getch();
5. Algorithm:
1. Input:Receivethreenumbers,a,b,andc.
2. Sum:Calculate the sumofa,b,andc byaddingthemtogether:sum= a + b+c.
3. Average:Calculatetheaveragebydividingthesumby3:average =sum/3.
4. Output: Theaverage is the resultyou'relookingfor,representing the average of the three
numbers.
Deptof CSE
Calculating Marks
6. FlowChart:
7. SampleInputandOutput:
Enterthreevalues:5 6 7
The sum of three numbers=18.000000
Theaverageofthreenumbers=6.000000
8. Result:
Sumandaverage ofthree numberexecutedSuccessfully.
9. Reference:
https://cstutorialpoint.com/c-program-to-find-the-sum-and-average-of-three-numbers/
Deptof CSE
ConversionofFahrenheittoCelsiusandViceVersa
ConversionofFahrenheittoCelsiusandViceVersa
Exp.No:
Date:
1. Aim:
ImplementaCprogramforconversionofFahrenheittoCelsiusandviceversa
2. SoftwareRequired:
TURBOC
3. Theory:
Celsius is represented byoC and Fahrenheitis representedbyoF. Thereis aformula toconvert Celsius
to Fahrenheit, using which we will be able to convert Celsius to Fahrenheit.
FormulatoConvertTemperatureFromCelsiusToFahrenheit
Fahrenheit=(celsius*1.8)+32
FormulatoConvertTemperatureFromFahrenheittoCelsius
Celsius=((Fahrenheit-32)*5)/9;
4. Program:
#include<stdio.h>i
nt main()
{
floatt1,t2,c,f;
printf("EnterTemperatureinCelsius:");
scanf("%f",&t1);
printf("\nEnterTemperatureinFahrenheit:");
Deptof CSE
ConversionofFahrenheittoCelsiusandViceVersa
scanf("%f",&t2);
//TemperatureFromCelsiusToFahrenheit f=(t1*9/5)+32;
//ConvertingFahrenheitintoCelsius c
= ((t2-32)*5)/9;
printf("\nTemperatureinFahrenheit:%f",f);
printf("\nTemperature in Celsius: %f",c); return
0;
}
5. Algorithm:
1. ProgramStart
2. Declarationof variable
3. EntertemperatureinCelsius
4. EntertemperatureinFahrenheit
5. ConvertingconversionintoFahrenheit
6. ConvertingFahrenheitintoCelsius
7. Displayingresult
8. ProgramEnd
Deptof CSE
ConversionofFahrenheittoCelsiusandViceVersa
6. FlowChart:
7. SampleInputandOutput:
Temperature in Fahrenheit : 95
TemperatureinFahrenheit:95.000000
8. Result:
ConversionofFahrenheittoCelsiusandViceVersaisExecuted Successfully.
9. Reference:
https://cstutorialpoint.com/c-program-to-convert-temperature-from-celsius-to-fahrenheit-and-
fahrenheit-to-celsius/
Deptof CSE
SimpleInterest Calculation
SimpleInterestCalculation
ExpNo:
Date:
1. Aim:ImplementingaCprogramtofindsimpleinterestcalculation
2. SoftwareDeveloped:
TurboC
3.Theory:
Simple interest is a quick method of calculating the interest charge on a loan. In this article, we
will learn to calculate the simple interest in C programming language.
Simple interest is determined by multiplying the daily interest rate by the principal by thenumber
of days that elapse between payments. Divide the product of these three values toconvert the
percentage value of the interest rate into decimals.
Simple InterestFormula
Si=p*t*r/100
4. Program:
#include<stdio.h>
#include<conio.h>
int main()
floatp,t,r;
float interest,amount;
printf("Enterprincipalamount=");
scanf("%f",&p);
DeptofIT,GIETEngineeringCollege,Rajahmundry
SimpleInterest Calculation
printf("\nEntertimeperiodinyears=");
scanf("%f",&t);
printf("\nEnterrateofinterest=");
scanf("%f",&r);
interest=(p*t*r)/100;
amount=p+interest;
printf("\nprincipalamount=%f",p);
nRate of interest=%f=",r);
getch();
4. Algorithm:
Step1: START
Step2:Declarevariablesp, n,randsi.
Step3 :Readthevaluesofvariablep ( principal) , n( Number ofyears) ,r( RateofInterest ). Step 4 :
calculate the values of“ si = ( p * n * r )/100 “ .
Step5:Displaysi(simple interest ).
Step 6 : STOP
DeptofIT,GIETEngineeringCollege,Rajahmundry
SimpleInterest Calculation
5. FlowChart:
6. SampleInput andOutput:
Enterprincipalamount=500000
Enter time period in years=5
Enter rate of interest=2
principalamount=500000.000000
Time period=5.000000
Rateofinterest=2.000000
SimpleInterestfor5.000000yearsat2.000000rateis=50000.000000 The
total amount=550000.000000
7. Result:
SuccessfullyExecuted
8. References:
https://www.geeksforgeeks.org/c-program-for-simple-interest/
DeptofIT,GIETEngineeringCollege,Rajahmundry
SquareRootofa GivenNumber
SquareRootofaGiven Number
Expno:
1. Aim:ImplementingaCprogramtofindthesquarerootofagivennumber.
2. SoftwareRequired:
TurboC
3. Theory:
ASquarerootofanumberisavaluethat,whenmultipliedbyitself,givesthenumber.
4. Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>i
nt main()
{
inta;
float square;
printf("Enterthevalueforwhichyouwant tofindsqareroot::");
scanf("%d",&a);
square=sqrt(a);
printf("\nThesquarerootof%dis=%f",a,square);
getch();
}
5. SampleInputandOutput:
6. Result:
SuccessfullyExecuted.
7. Reference:
https://www.codingbroz.com/c-program-to-find-square-root-of-a-number/
DeptofIT,GIETEngineeringCollege,Rajahmundry
CompoundInterest
CompoundInterest
Exp.No:
Date:
1. Aim:Implementing aCprogramtofindcompoundinterest.
2. SoftwareRequired:
TurboC
3. Theory:
CompoundInterestformula:
Formula to calculate compound interest annually is given by:
Amount=P(1+R/100)t
4. Program:
#include<stdio.h>
#include<math.h>
intmain()
{
floatprinciple,rate,time,CI;
/*Inputprinciple,timeandrate*/
printf("Enter principle (amount): ");
scanf("%f", &principle);
printf("Entertime:");
scanf("%f", &time);
Deptof cse
CompoundInterest
printf("Enterrate:");
scanf("%f", &rate);
/*Calculatecompoundinterest*/
CI=principle*(pow((1+rate /100),time));
return0;
}
5. SampleInputandOutput:
Enterprinciple(amount):1200
Enter time: 2
Enterrate:5.4
CompoundInterest= 1333.099243
6. Result:
SuccessfullyExecuted
7. Reference:
https://www.geeksforgeeks.org/c-program-for-compound-interest/
Deptof cse
TriangleUsingHeron’sFormulae
TriangleUsingHeron’sFormulae
Exp.No:
Date:
1. Aim:
ImplementingaCprogramtofindareaoftriangleusingheron’sformulae.
2. SoftwareRequired:
TurboC
3. Program:
#include<stdio.h>
#include<math.h>
int main()
{
float s1,s2,s3,s,area;
printf("\nEnterthelengthofthreesidesoftriangle");
scanf("%f %f %f", &s1,&s2, &s3);
s= (s1+s2+s3)/2;
area = sqrt(s*(s-s1)*(s-s2)*(s-s3));
printf("Areaoftriangle:%0.4f\n",area);
return0;
}
4. SampleInputand Output:
Enterthelengthofthreesidesoftriangle54 87
90
Areaoftriangle:2272.0667
5. Result:
Successfullycompleted.
6. References:
https://btechgeeks.com/c-program-to-calculate-area-of-any-triangle-using-herons-formula/
DeptofIT,GIETEngineeringCollege,Rajahmundry
DistanceTravelledbyan Object
DistanceTravelledbyanObject
Exp.No:
Date:
1. Aim:
ImplementingaCprogramtofindthedistancetravelledbyanobject.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main() {
floatu,a,s;
int t;
scanf("%f%f",&a,&u);
printf("enterthevalueoftime");
scanf("%d",&t); s=(u*t)+
(a*t*t)/2;printf("%f",s);
return0;
DeptofIT,GIETEngineeringCollege,Rajahmundry
DistanceTravelledbyan Object
4. SampleInputandOutput:
enterthevalues4
enterthevalueoftime2
14.000000
5. Result:
SuccessfullyExecuted.
6. Reference:
https://btechgeeks.com/c-program-to-calculate-area-of-any-triangle-using-herons-formula/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Evaluate Expressions
EvaluateExpressions
Exp.No:
Date:
1. Aim:
ImplementingaCprogramtoEvaluatethefollowing expressions.
a. A+B*C+(D*E)+F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J=(i++)+(++i)
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
inti=5,j,result_a,result_b,result_c;
printf("a.Result ofexpressionA+B*C+(D*E)+F*Gis:%d\n",result_a);
result_b = A / B * C - B + A * D / 3;
printf("b.ResultofexpressionA/B*C-B+A*D/3is:%d\n",result_b); result_c
DeptofIT,GIETEngineeringCollege,Rajahmundry
Evaluate Expressions
printf("c.ResultofexpressionA+++B---Ais:%d\n",result_c); j =
(i++) + (++i);
0;
4. Algorithm:
Step 1: DeclareA,B,C,D,E,F,G,i,j.
Step2:ReadA,B,C,D,E,F,G,i,jValues.
Step3:Evaluatethebelowexpressionsresult_a=A+B*C+(D*E)+F*G.result_b=A /B
*C-B+A*D /3.result_c = A+++ ++B---A.J= (i++)+ (++i).
Step4:Printresult_a,result_b,result_c,j
5. SampleInputandOutput:
a. ResultofexpressionA+B*C+(D*E)+F*Gis:70
c. ResultofexpressionA+++B---Ais:11
6. Result:
SuccessfullyExecuted.
7. Reference:
https://www.educba.com/expression-evaluation-in-c
DeptofIT,GIETEngineeringCollege,Rajahmundry
MaximumofThreeNumbersUsingConditionalOperator
MaximumofThreeNumbersUsingConditionalOperator
Exp.No:
Date:
1. Aim:
ImplementingaCprogramtofindthemaximumofthreenumbersusingconditionaloperator.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
intnum1,num2,num3,max;
scanf("%d%d%d",&num1,&num2,&num3);
max=(num1>num2)?((num1>num3)?num1:num3):((num2>num3)?num2:
num3);printf("Maximum number is %d\n", max);
return0;
DeptofIT,GIETEngineeringCollege,Rajahmundry
MaximumofThreeNumbersUsingConditionalOperator
4. Algorithm:
Step-1:Declarenum1,num2,num3,max.
Step-2:Readnum1,num2,num3usingscanf()function.
Step-3:Calculatemaxvalueusingtheconditionaloperator(ternaryoperator)tofindthe maximum.
Step-4:Printmaxvalue.
Step-5:Exitorterminatethe program.
5. SampleInputandOutput:
Enterthreenumbers:456
Maximum number is 6
6.Result:
SuccessfullyExecuted.
7.Reference:
https://www.geeksforgeeks.org/conditional-or-ternary-operator-in-c/
DeptofIT,GIETEngineeringCollege,Rajahmundry
CalculatingMarks
CalculatingMarks
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
int marks[5],i;
printf("Entermarksof5subjects:");
for(i=0;i< 5;i++)
scanf("%d",&marks[i]);
total += marks[i];
printf("Totalmarks:%.2f\n",total);
DeptofIT,GIETEngineeringCollege,Rajahmundry
CalculatingMarks
printf("Averagemarks:%.2f\n",average);
return 0;
4. SampleInputandOutput:
Entermarksof5 subjects: 45
56
35
50
70
Totalmarks: 256.00
Averagemarks:51.20
5. Result:
SuccessfullyExecuted.
6. Reference:
https://w3codeworld.com/article/72/c-program-to-enter-the-marks-of-five-subjects-and-
calculate-total--average--and-percentage
DeptofIT,GIETEngineeringCollege,Rajahmundry
MaxandMinofFoirNumbersusingIf-Else
MaxAndMinofFourNumbersUsingIf-Else
Exp.No:
Date:
1. Aim:
Implement aCprogramtofindthemaxandminoffournumbersusingif-else.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
intn1,n2,n3,n4; int
max, min;
printf("Enterfournumbers:");
scanf("%d%d%d%d",&n1,&n2,&n3,&n4); if
(n1 >= n2 && n1 >= n3 && n1 >= n4)
{
max=n1;
}
else if(n2>=n1&&n2>=n3&&n2>=n4)
{
max=n2;
}
else if(n3>=n1&&n3>=n2&&n3>=n4)
{
max=n3;
}
else
{
max=n4;
DeptofIT,GIETEngineeringCollege,Rajahmundry
MaxandMinofFoirNumbersusingIf-Else
}
if(n1<=n2&& n1<=n3&&n1<=n4)
{
min=n1;
}
else if(n2<=n1&&n2<=n3&&n2<=n4)
{
min=n2;
}
else if(n3<=n1&&n3<=n2&&n3<=n4)
{
min=n3;
}
else
{
min=n4;
}
printf("Maximumis:%d\n",max);
printf("Minimum is: %d\n", min);
return0;
}
4. SampleInputandOutput:
Enterfour numbers:5680 90
Maximumis: 90
Minimumis:0
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3resource.com/c-programming-exercises/basic-declarations-and-expressions/c-
programming-basic-exercises-58.php
DeptofIT,GIETEngineeringCollege,Rajahmundry
GenerateElectricityBill
GenerateElectricityBill
Exp.No:
Date:
1. Aim:
ImplementaCprogramtogenerateelectricity bill.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
intunit;
float amt, total_amt, sur_charge;
printf("Entertotalunitsconsumed:");
scanf("%d", &unit);
if(unit<= 50)
{
amt=unit*0.50;
}
elseif(unit<=150)
{
amt=25+((unit-50) * 0.75);
}
elseif(unit<=250)
{
amt=100+((unit-150) * 1.20);
}
else
{
amt=220+((unit-250) * 1.50);
DeptofIT,GIETEngineeringCollege,Rajahmundry
GenerateElectricityBill
}
sur_charge = amt * 0.20;
total_amt=amt+sur_charge;
printf("ElectricityBill=Rs.%.2f",total_amt);
return 0;
}
4. SampleInputandOutput:
Entertotalunitsconsumed:500
5.Result:
SuccessfullyExecuted.
6.Reference:
https://codeforwin.org/c-programming/c-program-to-calculate-electricity-bill
DeptofIT,GIETEngineeringCollege,Rajahmundry
RootsofQuadraticEquation
RootsofQuadraticEquation
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofind rootsofquadraticequation.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
#include<math.h>
main()
{
doublea,b,c;
doublediscriminant,root1, root2;
printf("Enterthecoefficientsofthequadraticequation(a,b,c):"); scanf("%lf
%lf %lf", &a, &b, &c);
discriminant =b*b-4*a*c; if
(discriminant > 0)
{
root1=(-b+sqrt(discriminant))/(2*a);
root2=(-b- sqrt(discriminant)) /(2 *a);
printf("Tworealanddistinctroots:\n");
printf("Root 1 = %.2lf\n", root1);
printf("Root 2 = %.2lf\n", root2);
}
else if(discriminant==0)
{
root1=-b/(2*a);
printf("Onerealroot(doubleroot):\n");
printf("Root = %.2lf\n", root1);
DeptofIT,GIETEngineeringCollege,Rajahmundry
RootsofQuadraticEquation
}
else
{
doublerealPart=-b/(2 * a);
doubleimaginaryPart=sqrt(-discriminant)/(2*a);
printf("Two complex roots:\n");
printf("Root 1=%.2lf+%.2lfi\n",realPart,imaginaryPart);
printf("Root 2= %.2lf- %.2lfi\n", realPart, imaginaryPart);
}
return0;
}
4. SampleInputand Output:
Enterthecoefficientsofthequadraticequation(a,b,c):4 5
Twocomplexroots:
Root1=-0.62+ 1.05i
Root2=-0.62-1.05i
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/quadratic-roots
DeptofIT,GIETEngineeringCollege,Rajahmundry
CalculatorUsingSwitchCase
CalculatorUsingSwitchCase
Exp.No:
Date:
1. Aim:
Implement aCprogramtosimulateacalculatorusingswitchcase.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
charop;
doublefirst,second;
printf("Enteranoperator(+,-,*,/):");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf%lf",&first,&second);
switch (op)
{
case'+':
printf("%.1lf+%.1lf=%.1lf", first,second,first +second); break;
case'-':
printf("%.1lf-%.1lf=%.1lf", first,second,first -second); break;
case'*':
printf("%.1lf*%.1lf=%.1lf",first,second,first *second); break;
case'/':
printf("%.1lf/%.1lf=%.1lf",first, second,first/second);
DeptofIT,GIETEngineeringCollege,Rajahmundry
CalculatorUsingSwitchCase
break;
default:
printf("Error!operator isnotcorrect");
}
return0;
}
4. SampleInputandOutput:
Enteranoperator(+,-,*,/):* Enter
two operands: 3 6
3.0*6.0=18.0
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/calculator-switch-case
DeptofIT,GIETEngineeringCollege,Rajahmundry
LeapYearorNot
LeapYearorNot
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindthegivenyearisaleapyearor not.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
int year;
printf("Enterayear:");
scanf("%d", &year);
if((year% 4==0 && year%100!=0)||(year%400 ==0))
{
printf("%disa leapyear.\n",year);
}
else
{
printf("%disnotaleapyear.\n",year);
}
return0;
}
DeptofIT,GIETEngineeringCollege,Rajahmundry
LeapYearorNot
4. SampleInputandOutput:
Enter a year: 2023
2023isnotaleapyear.
5.Result:
SuccessfullyExecuted.
6.Reference:
https://www.tutorialspoint.com/learn_c_by_examples/leap_year_program_in_c.htm
DeptofIT,GIETEngineeringCollege,Rajahmundry
FactorialOfGivenNumberUsingLoop
FactorialOfGivenNumberUsingLoop
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindthefactorialofgivennumber usinganyloop.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
int i=1, f = 1, n;
printf("Inputthenumber:");
scanf("%d", &n);
while(i<=n)
{
f=f*i; i+
+;
}
printf("TheFactorialof%dis:%d\n",n, f);
return 0;
}
4. SampleInputandOutput:
Inputthenumber : 6
TheFactorialof6is: 720
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3resource.com/c-programming-exercises/for-loop/c-for-loop-exercises-15.php
DeptofIT,GIETEngineeringCollege,Rajahmundry
PrimeorNot
PrimeOrNot
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindgivennumberisaprimeor not.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
intn,i,m=0,flag=0;
printf("Enterthenumbertocheckprime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Numberisnotprime");
flag=1;
break;
}
}
if(flag==0)printf("Number
isprime"); return 0;
}
4. SampleInputandOutput:
Enterthenumbertocheckprime:4 Number
is not prime
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/prime-number
SineandCosSeries
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoComputesineandcosseries
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
#include<math.h>
//Functiontocalculatefactorialofanumber double
factorial(int n) {
double fact= 1.0;
for(int i=1;i<=n;i++){ fact
*= i;
}
return fact;
}
intmain(){
doublex,sinX=0.0,cosX=0.0; int n;
//Prompttheuserto entertheangle inradiansandthenumberofterms intheseries printf("Enter the
angle in radians (x): ");
scanf("%lf",&x);
printf("Enterthenumberoftermsintheseries:");
scanf("%d", &n);
//Calculatesine(x)andcosine(x)usingtheTaylorseriesexpansions for (int
i = 0; i< n; i++) {
intexponent=2* i+1;
doubleterm=pow(-1,i) *pow(x, exponent) /factorial(exponent);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Sineand consSeries
sinX+=term;
if(i%2==0){
//Forcosine,thetermswithevenexponentsareadded cosX
+= term;
}
}
// Display the results
printf("sin(x) = %.6lf\n", sinX);
printf("cos(x)=%.6lf\n",cosX);
return0;
}
4. SampleInputandOutput:
Entertheangleinradians(x): 4
Enterthenumberoftermsintheseries:4
sin(x) = -1.384127
cos(x) = 12.533333
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.codingconnect.net/c-program-sine-series/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Number Palindrome
NumberPalindrome
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoCheckinganumberpalindrome
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
int num, r, sum = 0, t;
printf("Inputanumber:");
scanf("%d", &num);
for(t= num;num!=0;num= num/10)
{
r=num%10;
sum=sum*10+r;
}
if(t ==sum)
printf("%disapalindromenumber.\n",t);
else
printf("%disnotapalindromenumber.\n", t);
return0;
}
Deptof cse,SMGGEngineeringCollege,A.Somaraju
Number Palindrome
4. SampleInputandOutput:
Inputanumber:121
121isapalindromenumber.
Input a number: 123
123isnotapalindromenumber.
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3resource.com/c-programming-exercises/for-loop/c-for-loop-exercises-38.php
Deptof cse,SMGGEngineeringCollege,A.Somaraju
PyramidofNumbers
PyramidOfNumbers
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoConstructapyramidofnumbers.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
{
int i,space,rows,k=0,count =0,count1=0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for(i= 1; i<= rows; ++i)
{
for(space= 1;space <=rows-i;++space)
{
printf("");
++count;
}
while(k !=2 * i-1)
{
if(count<=rows -1)
{
printf("%d",i+k);
++count;
}else
{
++count1;
DeptofIT,GIETEngineeringCollege,Rajahmundry
PyramidofNumbers
232
34543
4567654
567898765
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/pyramid-pattern
DeptofIT,GIETEngineeringCollege,Rajahmundry
MinandMaxA1-DIntegerArray
MinAndMaxof A1-DIntegerArray
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindtheminandmaxofa1-Dinteger array.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
void main()
{
int arr1[100];
inti,mx,mn,n;
printf("\n\nFind maximumand minimumelement inanarray:\n");
printf(" \n");
printf("Inputthenumberofelementsto bestoredinthearray:");
scanf("%d",&n);
printf("Input %delementsinthearray:\n",n);
for(i=0;i<n;i++)
{
printf("element-%d:",i);
scanf("%d",&arr1[i]);
}
mx = arr1[0];
mn = arr1[0];
for(i=1;i<n;i++)
{
if(arr1[i]>mx)
{
mx=arr1[i];
MinandMaxA1-DIntegerArray
}
if(arr1[i]<mn)
{
mn=arr1[i];
}
}
printf("Maximum element is : %d\n", mx);
printf("Minimumelementis:%d\n\n",mn);
}
4. SampleInputandOutput:
Findmaximumandminimumelementinanarray:
element-0: 12
element-1: 35
element-2: 3
element-3: 90
element-4: 1
Maximumelementis:90
Minimum element is : 1
5.Result:
SuccessfullyExecuted.
6.Reference:
https://www.w3resource.com/c-programming-exercises/array/c-array-exercise-9.php
LinearSearchOn1DArray
LinearSearchOn1DArray
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoPerformlinear searchon1Darray.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
{
inta[10],search,i,n;
printf("Enternumberofelementsinarray\n"); scanf("%d",
&n);
printf("Enter%dinteger(s)\n",n); for
(i = 0; i< n; i++)
scanf("%d",&a[i]);
printf("Enteranumbertosearch\n");
scanf("%d", &search);
for(i= 0; i< n;i++)
{
if(a[i] == search)
{
printf("%dispresentatlocation%d.\n",search,i+1); break;
}
}
if(i==n)
printf("%disn'tpresentinthearray.\n",search);
return 0;
LinearSearchOn1DArray
}
4. SampleInputandOutput:
Enternumberofelementsinarray 4
Enter4integer(s)
12
90
-1
Enteranumbertosearch
12
12ispresentatlocation1.
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programmingsimplified.com/c/source-code/c-program-linear-search
ReverseA1DIntegerArray
ReverseA1DIntegerArray
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoreversea1Dinteger array.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
{
int n,i,j,a[10], b[10];
printf("Enterthenumberofelementsinarray\n");
scanf("%d", &n);
printf("Enterthearrayelements\n"); for
(i = 0; i<n ;i++)
scanf("%d",&a[i]);
for(i=n-1,j=0;i>=0;i--,j++) b[j] =
a[i];
for(i=0;i<n;i++) a[i]
= b[i];
printf("Reversearrayis\n"); for
(i = 0; i< n; i++)
printf("%d\n",a[i]);
return 0;
}
ReverseA1DIntegerArray
4. SampleInputandOutput:
Enterthenumberofelementsinarray 5
Enterthearrayelements
12
34
9
1
0
Reversearrayis
0
1
9
34
12
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3schools.in/c-programming/examples/reverse-array
2’sComplementofTheGivenBinaryNumber
2’sComplementofTheGivenBinaryNumber
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofind2’scomplementofthegivenbinarynumber.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
#define SIZE 8
int main()
{
charbinary[SIZE+1],onesComp[SIZE+1],twosComp[SIZE+1]; int i,
carry=1;\
printf("Enter%dbitbinaryvalue:",SIZE);
/*Input8-bitbinarystring*/ gets(binary);
/*Findonescomplementofthebinarynumber*/ for(i=0;
i<SIZE; i++)
{
if(binary[i]=='1')
{
onesComp[i]='0';
}
elseif(binary[i]=='0')
{
onesComp[i]='1';
}
}
2’sComplementofTheGivenBinaryNumber
onesComp[SIZE]='\0';
/*
* Add1tothe onescomplement
*/
for(i=SIZE-1;i>=0;i--)
{
if(onesComp[i]=='1'&&carry==1)
{
twosComp[i]='0';
}
elseif(onesComp[i] =='0'&&carry==1)
{
twosComp[i]='1';
carry=0;
}
else
{
twosComp[i]=onesComp[i];
}
}
twosComp[SIZE]='\0';
4. SampleInputandOutput:
Enter8bitbinaryvalue:01110111
Original binary = 01110111
Ones complement = 10001000
Twoscomplement=10001001
5.Result:
SuccessfullyExecuted.
6.Reference:
https://codeforwin.org/c-programming/c-program-to-find-twos-complement-of-binary-number
EliminateDuplicateElementsinAnArray
EliminateDuplicateElementsinAnArray
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoEliminateduplicateelementsinanarray.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
{
inta[50],i,j,k,count=0,dup[50],n;
printf("Enter size of the array");
scanf("%d",&n);
printf("EnterElementsofthearray:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
dup[i] = -1;
}
printf("Enteredelementare:"); for(i=0;i<n;i+
+)
{
printf("%d",a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1; j<n;j++)
{
if(a[i]==a[j]){
EliminateDuplicateElementsinAnArray
EnterElementsofthe array:0134532421
AfterdeletingtheduplicateelementtheArrayis:013452
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.tutorialspoint.com/c-program-to-delete-the-duplicate-elements-in-an-array
AdditionofTwoMatrices
AdditionofTwoMatrices
Exp.No:
Date:
1. Aim:
ImplementaCprogramforAdditionoftwomatrices.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
intr,c,a[10][10],b[10][10],sum[10][10],i,j;
printf("Enterthenumberofrows(between1and100):");
scanf("%d", &r);
printf("Enterthenumberofcolumns(between1and100):");
scanf("%d", &c);
printf("\nEnterelementsof1stmatrix:\n"); for
(i = 0; i< r; ++i)
for(j=0;j<c;++j)
printf("Enterelement a%d%d:",i+1,j+1);
scanf("%d", &a[i][j]);
printf("Enterelementsof2ndmatrix:\n");
for(j=0;j<c;++j)
DeptofIT,GIETEngineeringCollege,Rajahmundry
AdditionofTwoMatrices
printf("Enterelement b%d%d:",i+1,j+1);
scanf("%d", &b[i][j]);
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
printf("\nSumoftwomatrices:\n"); for
(i = 0; i< r; ++i)
for(j=0;j<c;++j)
printf("%d",sum[i][j]); if
(j == c - 1)
printf("\n\n");
return0;
4. SampleInputandOutput:
Enter the number of rows (between 1 and 100): 2
Enterthenumberofcolumns(between1and100):2 Enter
DeptofIT,GIETEngineeringCollege,Rajahmundry
AdditionofTwoMatrices
Enterelementa11:12
Enter elementsof2ndmatrix:
Sumoftwomatrices:
135
66
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/add-matrix
DeptofIT,GIETEngineeringCollege,Rajahmundry
MultiplicationofTwoMatrices
MultiplicationofTwoMatrices
Exp.No:
Date:
1. Aim:
ImplementaCprogramforMultiplicationoftwo matrices.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
main()
{
intc,d,p,q,m,n,k,tot=0;
intfst[10][10],sec[10][10],mul[10][10];
printf("Please insertthenumberofrowsandcolumnsforfirst matrix \n");
scanf("%d%d", &m, &n);
printf("Insertyourmatrixelements:\n"); for (c
= 0; c < m; c++)
for(d=0;d<n;d++)
scanf("%d",&fst[c][d]);
printf("Please insertthenumberofrowsandcolumnsforsecond matrix\n"); scanf("
%d %d", &p, &q);
if(n!= p)
printf("Yourgivenmatricescannotbe multiplied witheachother. \n"); else
{
printf("Insertyourelementsforsecondmatrix\n"); for
(c = 0; c < p; c++)
for(d=0;d<q;d++)
scanf("%d",&sec[c][d]);
for(c=0;c<m; c++)
DeptofIT,GIETEngineeringCollege,Rajahmundry
MultiplicationofTwoMatrices
{
for(d= 0;d<q;d++)
{
for(k= 0;k<p;k++)
{
tot=tot+ fst[c][k]*sec[k][d];
}
mul[c][d]=tot;
tot = 0;
}
}
printf("Theresult ofmatrixmultiplicationorproductofthematricesis: \n"); for (c =
0; c < m; c++)
{
for (d = 0; d < q; d++)
printf("%d\t",mul[c][d]);
printf(" \n ");
}
}
return0;
}
4. SampleInputandOutput:
Pleaseinsertthenumberofrowsandcolumnsforfirstmatrix 2 2
Insertyourmatrixelements:
11
11
Pleaseinsertthenumberofrowsandcolumnsforsecondmatrix 2 2
DeptofIT,GIETEngineeringCollege,Rajahmundry
MultiplicationofTwoMatrices
Insertyourelementsforsecondmatrix 2
22
Theresultofmatrixmultiplicationorproductofthematrices is:
4 4
4 4
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3schools.in/c-programming/examples/matrix-multiplication-in-c
DeptofIT,GIETEngineeringCollege,Rajahmundry
BubbleSort
BubbleSort
Exp.No:
Date:
1. Aim:
ImplementaCprogramSortarrayelementsusingbubble sort.
2. SoftwareRequired:
TURBOC
3. Theory:
Bubble Sort is the simplest sorting algorithmthat works by repeatedly swapping the adjacent
elements if they are in the wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity is quite high.
4. Program:
#include<stdio.h>bubble
(int*a,intn)
{
int tem,count, i,j;
for(i=0;i<n-1;i++)
{
count=0;
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
tem=a[j];
a[j]=a[j+1];
a[j+1]=tem;
count=1;
}
DeptofIT,GIETEngineeringCollege,Rajahmundry
BubbleSort
}
if(count==0)
break;
}
}
main()
{
int n,a[100],i;
printf("\nenternumberofelements:");
scanf("%d",&n);
printf("\nenterarrayelements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nTheelementsbeforesorting:"); for(i=0;i<n;i+
+)
printf("%d",a[i]);
bubble(a,n);
printf("\nTheelementsaftersortingare:");
for(i=0;i<n;i++)
printf("%d",a[i]);
return 0;
}
5. Algorithm:
Bubble(a,n)
Begin
Forj=0ton-1-Iby1do If
Settmp=a[j];
DeptofIT,GIETEngineeringCollege,Rajahmundry
BubbleSort
Set a[j]=a[j+1];
Seta[j+1]=tmp;
Endif
Endfor
endfor
end
6. SampleInputandOutput:
Enternumberofelements:5
Enterarrayelements:45921357
Theelementsbeforesorting: 45921357
Theelementsaftersortingare : 39214557
7. Result:
BubbleSortProgramSuccessfullyExecuted.
6.Reference:
https://www.geeksforgeeks.org/bubble-sort/
DeptofIT,GIETEngineeringCollege,Rajahmundry
ConcatenatingTwoStringsWithoutBuilt-InFunctions
ConcatenatingTwoStringsWithoutBuilt-InFunctions
Exp.No:
Date:
1. Aim:
3. Program:
void main(void)
charstr1[25],str2[25];
int i=0,j=0;
printf("\nEnterFirstString:");
gets(str1);
printf("\nEnterSecondString:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
str1[i]=str2[j];
j++;
ConcatenatingTwoStringsWithoutBuilt-InFunctions
i++;
str1[i]='\0';
printf("\nConcatenatedStringis%s",str1);
4. SampleInputandOutput:
EnterFirstString:sai
ConcatenatedStringissaideepthi
5.Result:
SuccessfullyExecuted.
6.Reference:
https://www.w3schools.in/c-programming/examples/concatenate-two-strings-without-using-
strcat
ReverseAStringUsingBuilt-InandWithoutBuilt-InStringFunctions
ReverseAStringUsingBuilt-InandWithoutBuilt-InString
Functions
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoReverseastring usingbuilt-inandwithoutbuilt-instringfunctions
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
charstr[100];
intl, i;
printf("\n\nPrint individualcharactersofstringinreverseorder:\n"); printf("\
n");
printf("Inputthestring:");
fgets(str, sizeof str, stdin);
l=strlen(str);
printf("Thecharactersofthestring inreverseare: \n");
for(i=l;i>=0;i--)
{
printf("%c", str[i]);
}
printf("\n");
}
DeptofIT,GIETEngineeringCollege,Rajahmundry
ReverseAStringUsingBuilt-InandWithoutBuilt-InStringFunctions
4. SampleInputandOutput:
Printindividualcharactersofstringinreverseorder :
Inputthestring:saideepthi
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.tutorialspoint.com/cprogramming/index.htm
DeptofIT,GIETEngineeringCollege,Rajahmundry
Sumofa1DArrayUsingMalloc
Sumofa1DArrayUsingMalloc()
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<malloc.h>
#include <stdlib.h>
void main()
inti, n;
int*a,*b,*c;
printf("Enterthesizeofthearrays\n");
scanf("%d", &n);
a=(int*)malloc(n* sizeof(int));
b=(int*)malloc(n* sizeof(int));
printf("EnterElementsofFirstList\n");
scanf("%d",a+ i);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Sumofa1DArrayUsingMalloc
printf("EnterElementsofSecondList\n"); for
(i = 0; i< n; i++)
scanf("%d",b+i);
printf("ResultantListis\n");
printf("%d\n",*(c+i));
return0;
DeptofIT,GIETEngineeringCollege,Rajahmundry
Sumofa1DArrayUsingMalloc
4. SampleInputandOutput:
Enterthesizeofthearrays 5
EnterElementsofFirstList 12
23 34 1 2
EnterElementsofSecondList 13456
ResultantListis
13263868
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.sanfoundry.com/c-program-compute-sum-two-one-dimensional-arrays-using-
malloc/
DeptofIT,GIETEngineeringCollege,Rajahmundry
TotalAverageofNstudentsusingStructures
Total,AverageofnstudentsusingStructures
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindthetotal,averageofnstudentsusingstructures.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
struct student
char name[10];
floatm1,m2,m3;
float avg,total;
};
void main()
structstudents[20];
int n,i;
floattavg,sum=0.0;
printf("Enterthenumberofstudent=");
scanf("%d",&n);
for(i=0;i<n;i++)
printf("Enter thedetailof%dstudents\n",i+1);
DeptofIT,GIETEngineeringCollege,Rajahmundry
TotalAverageofNstudentsusingStructures
printf("\nEnterName=");
scanf("%s",s[i].name);
%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
for(i=0;i<n;i++)
if(s[i].avg>=35)
printf("\n%shasscoredabovetheaveragemarks",s[i].name); else
printf("\n%shasscoredbelowtheaveragemarks",s[i].name);
4. SampleInputandOutput:
Enterthenumberofstudent=2
Enter Name=deepu
Enterthethreesubjectscore
45 56 67
Enterthedetailof2students
Enter Name=deepthi
Enterthethreesubjectscore
78 45 78
DeptofIT,GIETEngineeringCollege,Rajahmundry
TotalAverageofNstudentsusingStructures
deepthihasscoredabovetheaveragemarks1
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
DisplayFailedStudentsUsingCalloc()
DisplayFailedStudentsUsingCalloc()
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
struct Student
charname[50];
introllNumber;
float marks;
};
int main()
intn;
printf("Enterthenumberofstudents:");
scanf("%d", &n);
structStudent*students=(structStudent*)calloc(n,sizeof(structStudent)); for
printf("Name:");
scanf("%s",students[i].name);
scanf("%d",&students[i].rollNumber);
printf("Marks: ");
scanf("%f",&students[i].marks);
printf("\nListoffailedstudents:\n");
if(students[i].marks<=40.0)
printf("Name:%s\n", students[i].name);
printf("RollNumber:%d\n",students[i].rollNumber);
n");
free(students);
return 0;
Enterthenumberofstudents:2
Name: divitha
DisplayFailedStudentsUsingCalloc()
RollNumber: 1
Marks:90
Enterdetails forstudent2:
Name: deepu
RollNumber:2
Marks:40
Listoffailed students:
Name: deepu
RollNumber:2
Marks:40.00
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
Readstudentnameand marks fromthecommandlineanddisplaythestudentdetails
Readstudentnameandmarksfromthecommandlineanddisplay the
student details
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
struct Student
{ char name[50];
int marks;
};
intmain(intargc,char*argv[]){ if
(argc< 2) {
printf("Usage:%s<number_of_students>\n",argv[0]); return
1;
intn= atoi(argv[1]);
structStudent*students=(structStudent*)calloc(n,sizeof(structStudent)); if
(students == NULL) {
printf("Memoryallocationfailed.Exiting...\n");
DeptofIT,GIETEngineeringCollege,Rajahmundry
Readstudentnameand marks fromthecommandlineanddisplaythestudentdetails
return1;
for(inti=0;i<n;i++){
scanf("%s",
students[i].name);printf("Entermarksofstud
&students[i].marks);
int total= 0;
intfailedCount = 0;
{ total +=
students[i].marks; if
(students[i].marks< 40) {
failedCount++;
floataverage=(float)total/n;
printf("\nStudent Details:\n");
printf("Averagemarks:%.2f\n",average);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Readstudentnameand marks fromthecommandlineanddisplaythestudentdetails
if (failedCount> 0) {
printf("\nFailedstudentslist:\n");
DeptofIT,GIETEngineeringCollege,Rajahmundry
Readstudentnameand marks fromthecommandlineanddisplaythestudentdetails
for(inti=0;i<n;i++) {
if(students[i].marks<40){
printf("Name:%s,Marks:%d\n",students[i].name, students[i].marks);
}else{
printf("\nNostudents failed.\n");
free(students);
return 0;}
4. SampleInputandOutput:
Enterthenumberofstudents:2
Enternameofstudent 2: deepu
Totalmarks: 35
Averagemarks:17.5
Name:deepu,Marks:23
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Realloc()Function
Realloc()Function
Exp.No:
Date:
1. Aim:
ImplementaCprogramforrealloc()function.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
int main()
intn=4,i,*p,s=0;
p=(int*)calloc(n,sizeof(int)); if(p
== NULL)
printf("Error!memorynotallocated.");
exit(0);
printf("Enterelementsofarray:"); for(i
= 0; i< n; ++i)
scanf("%d",p+i); s
+= *(p + i);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Realloc()Function
printf("Sum: %d",s);
printf("Enterelementsofarray:");
scanf("%d",p+i); s
+= *(p + i);
printf("Sum:%d",s);
return 0;
4. SampleInputandOutput:
Enterelements ofarray:2354
Sum:14
Enterelements ofarray:234501
Sum:28
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.tutorialspoint.com/use-of-realloc-in-c
DeptofIT,GIETEngineeringCollege,Rajahmundry
SinglyLinkedList
SinglyLinkedList
Exp.No:
Date:
1. Aim:
Implement aCprogramtoCreateanddisplayasinglylinkedlistusingself-referentialstructure.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
struct node
intdata;
structnode *next;
};
int main()
structnode*second=NULL;
head->data = 1;
second->data = 2;
SinglyLinkedList
third->data=3;
head->next=second;
second->next=third;
third->next=NULL;
structnode*current=head;
printf("%d",current->data);
current = current->next;
return0;
4. SampleInputandOutput:
123
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.prepbytes.com/blog/c-programming/self-referential-structure-in-c/
Differencesbetweenstructuresandunions
Differencesbetweenstructuresandunions
Exp.No:
Date:
1. Aim:
Demonstratethedifferencesbetweenstructuresandunionsusing aC program.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
struct Person
charname[50];
int age;
};
unionData{
intintegerData;
floatfloatData;
};
int main()
strcpy(person1.name,"John");
person1.age = 25;
data1.integerData=42;
DeptofIT,GIETEngineeringCollege,Rajahmundry
Differencesbetweenstructuresandunions
printf("Structure - Person:\n");
printf("Name:%s\n",person1.name);
printf("\n");
printf("Union-Data:\n");
printf("IntegerData:%d\n",data1.integerData);
data1.floatData = 3.14;
printf("FloatData:%f\n",data1.floatData);
return 0;
4. SampleInputandOutput:
Structure-Person:
Name: John
Age: 25
Union-Data:
Integer Data:42
FloatData: 3.140000
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Shift/Rotateusingbitfields
Shift/Rotateusingbitfields
Exp.No:
Date:
1. Aim:
ImplementaCprogramtoshift/rotateusingbitfields.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
structBitfieldRotation
unsignedintdata:4;
};
voidleftRotate(structBitfieldRotation*bf)
voidrightRotate(structBitfieldRotation*bf)
voiddisplayBitfield(structBitfieldRotationbf)
printf("BitfieldData:%X\n", bf.data);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Shift/Rotateusingbitfields
int main()
bitfield.data = 0xC;
printf("Original Bitfield:\n");
displayBitfield(bitfield);
leftRotate(&bitfield); printf("\
displayBitfield(bitfield);
rightRotate(&bitfield); printf("\
nAfterRightRotation:\n");
displayBitfield(bitfield);
return0;
4. SampleInputandOutput:
OriginalBitfield:
Bitfield Data: C
AfterLeftRotation:
Bitfield Data:
9AfterRightRotation
BitfieldData:C
5. Result:
SuccessfullyExecuted.
6. Reference:
DeptofIT,GIETEngineeringCollege,Rajahmundry
Shift/Rotateusingbitfields
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Copy onestructurevariabletoanotherstructureofthesametype
Copyonestructurevariabletoanotherstructureofthesametype
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
struct Student
charname[50];
int age;
floatmarks;
};
voidcopyStruct(structStudent*dest,conststructStudent*src)
strcpy(dest->name,src->name);
dest->age = src->age;
dest->marks=src->marks;
voiddisplayStudent(conststructStudent*student)
printf("Name:%s\n",student->name);
DeptofIT,GIETEngineeringCollege,Rajahmundry
Copy onestructurevariabletoanotherstructureofthesametype
printf("Marks:%.2f\n",student->marks);
int main()
structStudentstudent1={"JohnDoe",20,85.5}; struct
Student student2;
copyStruct(&student2,&student1);
printf("Original Student:\n");
displayStudent(&student1);
printf("\nCopied Student:\n");
displayStudent(&student2);
return0;}
4. SampleInputandOutput:
OriginalStudent:
Name:JohnDoe
Age: 20
Marks: 85.50
CopiedStudent:
Name:JohnDoe
Age: 20
Marks:85.50
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
NCR valueusingFunction
NCRvalueusingFunction
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
voidmain()
intn,r,ncr;
printf("\nEnterthevalueforNandR\n"); scanf("%d%d",
&n, &r);
printf("\nThevalueofncris:%d",ncr);
intfact(intz)
intf=1,i;
if(z== 0)
return(f);
}
NCR valueusingFunction
else
f=f*i;
return(f);
4. SampleInputandOutput:
EnterthevalueforNandR 5 2
Thevalueofncris:10
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.sanfoundry.com/c-program-ncr/
Find thelengthofa string
Findthelengthofastring
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindthelengthofastringusingFunctions.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
#include<string.h>in
t main(){
printf("\nEntertheString:");
scanf("%s",str);
len= strlen(str);
printf("\nLengthofthegivenstringis%d", len);
return(0);}
4. SampleInputandOutput:
Lengthofthegivenstringis7
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.codingninjas.com/studio/library/c-program-to-count-length-of-string-using-library-
function
DeptofIT,GIETEngineeringCollege,Rajahmundry
Transposeofa MatrixusingFunction
TransposeofaMatrixusingFunction
Exp.No:
Date:
1. Aim:
ImplementaCprogramtofindTransposeofaMatrixusingFunction.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
#define N 4
inti, j;
for(j=0;j<N;j++)
B[i][j]=A[j][i];
int main()
intA[N][N]= { {1,1,1,1},
{2,2,2,2},
{3,3,3,3},
{4,4,4,4}};
intB[N][N],i,j;
transpose(A,B);
Transposeofa MatrixusingFunction
printf("Resultmatrixis\n"); for
(i = 0; i< N; i++) {
for(j=0;j<N;j++)
printf("%d",B[i][j]);
printf("\n");
return0;
4. SampleInputandOutput:
Resultmatrixis
1234
1234
1234
1234
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.geeksforgeeks.org/c-transpose-matrix/
Euler’smethod.
Euler’smethod.
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
doubleequation(double x,double y)
returnx+y;
voideulerMethod(doublex0,doubley0,doubleh,doublexn)
printf("Euler'sMethod:\n");
printf("x\t\t y\n");
{ printf("%.4f\t%.4f\
n",x,y); y = y + h *
equation(x, y);x = x + h;
intmain(){
DeptofIT,GIETEngineeringCollege,Rajahmundry
Euler’smethod.
doublex0=0.0;
doubley0=1.0;
double h = 0.1;
doublexn=1.0;
eulerMethod(x0,y0,h,xn);
return 0;}
4. SampleInputandOutput:
Euler'sMethod:
x y
0.0000 1.0000
0.1000 1.1000
0.2000 1.2200
0.3000 1.3620
0.4000 1.5282
0.5000 1.7210
0.6000 1.9431
0.7000 2.1974
0.8000 2.4872
0.9000 2.8159
1.0000 3.1875
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
DeptofIT,GIETEngineeringCollege,Rajahmundry
FibonacciSeries.
Fibonacciseries
Exp.No:
Date:
1. Aim:
WritearecursivefunctiontogenerateFibonacciseries.
2. SoftwareRequired:
TURBOC
3. Program:
#include
<stdio.h>intfibonacci
(intnum)
if(num==0)
return0;
elseif(num== 1)
return1;
else
}
FibonacciSeries.
int main()
FibonacciSeries.
intnum;
scanf("%d", &num);
inti;
for(i=0;i<num;i++)
printf("%d,", fibonacci(i));
return0;
4. SampleInputandOutput:
Enterthenumberofelementstobe intheseries:10 0, 1,
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.scaler.com/topics/fibonacci-series-in-c-using-recursion/
LCMoftwonumbers
LCMoftwoNumbers
Exp.No:
Date:
1. Aim:
Writearecursivefunctiontofind thelcmoftwonumbers.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int lcm(inta,intb)
return(a*b);
intmain(){
intnum1,num2;
printf("Enterthefirstnumber:");
scanf("%d", &num1);
printf("Enterthesecondnumber:");
scanf("%d", &num2);
printf("LCMof%dand%dis:%d\n",num1,num2,lcm(num1,num2)); return
0;
}
LCMoftwonumbers
4. SampleInputandOutput:
Enterthefirstnumber:53
Enterthesecondnumber: LCMof5and3is: 15
5. Result:
SuccessfullyExecuted.
6. Reference:
https://codeforwin.org/c-programming/c-program-to-find-lcm-of-two-numbers-using-recursion
Factorialofanumbers
FactorialofaNumber
Exp.No:
Date:
1. Aim:
Writearecursivefunctiontofind thefactorialofanumber.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
unsignedlonglongfactorial(intn)
if(n== 0||n==1)
return1;
else
returnn*factorial(n -1);
int main()
intnum;
printf("Enteranon-negativeinteger:");
scanf("%d", &num);
Dept of cse
Factorialofanumbers
if(num<0)
printf("Pleaseenteranon-negativeinteger.\n");
else
printf("Factorialof%dis:%llu\n",num,factorial(num));
return0;
4. SampleInputandOutput:
Enteranon-negativeinteger:5
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programiz.com/c-programming/examples/factorial-recursion
Dept of cse
Ackermannfunctionusingrecursion
Ackermannfunctionusingrecursion
Exp.No:
Date:
1. Aim:
WriteaCProgramtoimplementAckermannfunctionusingrecursion.
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
intA(intm,intn);
main()
intm,n;
scanf("%d%d",&m,&n); printf("\
nOUTPUT::%d\n",A(m,n));
intA(intm,intn)
if(m==0)
returnn+1;
else if(n==0)
returnA(m-1,1);
else
returnA(m-1,A(m,n-1));
Ackermannfunctionusingrecursion
4. SampleInputandOutput:
Entertwonumbers::
13
OUTPUT :: 5
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.codezclub.com/c-implement-ackermann-function/
SumofSeriesusingRecursiveFunction
SumofSeriesusingRecursiveFunction
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
doubleseriesSum(intn)
if(n== 0)
return0;
else
int main()
intterms;
printf("Enterthenumberoftermsinthe series:");
scanf("%d", &terms);
DeptofIT,GIETEngineeringCollege,Rajahmundry
SumofSeriesusingRecursiveFunction
if(terms<0)
printf("Pleaseenter anon-negativeintegerforthenumberofterms.\n");
else
printf("Sumoftheseries:%lf\n",seriesSum(terms));
return0;
4. SampleInputandOutput:
Enterthenumberoftermsintheseries:5 Sum
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.geeksforgeeks.org/c-program-to-find-sum-of-natural-numbers-using-recursion/
DeptofIT,GIETEngineeringCollege,Rajahmundry
Swappingoftwonumbersusingcallbyreference
Swappingoftwonumbersusingcallbyreference
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
int main()
inta,b;
printf("\nAfter Swapping:\n");
printf("\na=%d\n\nb=%d",a,b);
return0;
swap(int*x,int*y)
inttemp;
Swappingoftwonumbersusingcallbyreference
temp=*x;
*x=*y;
*y=temp;
4. SampleInputandOutput:
Entervalueofa&b:3049
Before Swapping:
a=30
b=49
After Swapping:
a=49
b=30
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.programming9.com/programs/c-programs/194-swapping-of-two-numbers-using-
call-by-reference-in-c-functions
Danglingpointerproblem
Danglingpointerproblem
Exp.No:
Date:
1. Aim:
DemonstrateDanglingpointerproblemusingaCprogram.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
int*createIntArray(intsize)
int*arr=(int*)malloc(size*sizeof(int));
return arr;
int main()
int*arr=createIntArray(5);
arr[i]=i+1;
printf("Valuesusingvalidpointer:\n");
{
Danglingpointerproblem
printf("%d", arr[i]);
printf("\n");
free(arr);
printf("Valuesusingdanglingpointer:\n"); for
printf("%d", arr[i]);
printf("\n");
return 0;
4. SampleInputandOutput:
Valuesusingvalid pointer:
12345
Valuesusingdangling pointer:
003539355205
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.prepbytes.com/blog/c-programming/dangling-pointer-in-c/
Copy onestringintoanother
Copyonestringintoanother
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
voidcopy_string(char*,char*);
main()
charsource[100],target[100];
gets(source);
copy_string(target,source);
printf("Targetstringis\"%s\"\n",target);
return 0;
voidcopy_string(char*target,char *source)
while(*source)
*target=*source;
source++;
Copy onestringintoanother
target++;
*target='\0';
4. SampleInputandOutput:
Entersourcestring
saideepthi
Targetstringis"saideepthi"
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.w3schools.in/c-programming/examples/copy-string-using-pointers
NoofLowercase,Uppercase,Digitsandothercharactersusingpointers
NoofLowercase,Uppercase,Digitsandothercharactersusing
pointers
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
int main()
charstr[100];
int i;
intupper=0,lower=0,num=0,special=0;;
gets(str);
for(i=0;str[i] !='\0';i++)
if(str[i]>='A'&&str[i]<='Z')
upper++;
}
NoofLowercase,Uppercase,Digitsandothercharactersusingpointers
elseif(str[i]>='a'&&str[i]<='z')
lower++;
elseif(str[i]>='1'&&str[i]<='9')
num++;
else
special++;
nSpecialcharacters:%d",special); getch();
}
NoofLowercase,Uppercase,Digitsandothercharactersusingpointers
4. SampleInputandOutput:
Pleaseenterthestring
Sai Deepthi @1
Numbers: 1
Specialcharacters:3
5. Result:
SuccessfullyExecuted.
6. Reference:
https://code4coding.com/program-to-count-uppercase-lowercasespecial-character-and-numeric-
values-in-c/
WriteandReadTextintoafile
WriteandReadTextintoa file
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
int main()
FILE*file;
file=fopen("example.txt","w");
if (file == NULL)
printf("Couldnotopenthefileforwriting.\n");
return 1;
fprintf(file,"WritingtoafileinCiseasy!\n");
fclose(file);
file=fopen("example.txt","r"); if
(file == NULL)
{
WriteandReadTextintoafile
printf("Couldnotopenthefileforreading.\n"); return
1;
charch;
while((ch=fgetc(file))!=EOF)
putchar(ch);
fclose(file);
return 0;
4. SampleInputandOutput:
Content ofthefile:
WritingtoafileinCiseasy!
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
writeandreadtextintoabinaryfileusingfread()andfwrite()
writeandreadtextintoabinaryfileusingfread()andfwrite()
Exp.No:
Date:
1. Aim:
ImplementaCprogramtowriteandreadtextintoabinaryfileusingfread()andfwrite().
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
struct Person
charname[50];
int age;
};
int main()
FILE*file;
file=fopen("example.bin","wb");
if (file == NULL)
printf("Couldnotopenthefileforwriting.\n");
return 1;
structPersonperson1={"deepu", 25};
writeandreadtextintoabinaryfileusingfread()andfwrite()
fwrite(&person1,sizeof(structPerson),1,file);
fwrite(&person2,sizeof(structPerson),1,file); fclose(file);
file=fopen("example.bin","rb"); if
(file == NULL)
printf("Couldnotopenthefileforreading.\n"); return
1;
fread(&readPerson1,sizeof(structPerson),1,file);
fread(&readPerson2,sizeof(structPerson),1,file);
printf("Person1:Name=%s,Age=%d\n",readPerson1.name,readPerson1.age);
printf("Person2:Name=%s,Age=%d\n",readPerson2.name,readPerson2.age);
fclose(file);
return0;
}
writeandreadtextintoabinaryfileusingfread()andfwrite()
4. SampleInputandOutput:
Data readfromthefile:
Person1:Name=deepu,Age=25
Person2:Name=divitha,Age=5
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
Copythecontentsofonefiletoanotherfile.
Exp.No:
Date:
1. Aim:
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
int main()
FILE*sourceFile,*destinationFile;
sourceFile=fopen("source.txt","r");
if (sourceFile == NULL)
printf("Couldnotopenthesourcefileforreading.\n"); return 1;
destinationFile=fopen("destination.txt","w"); if
(destinationFile == NULL)
printf("Couldnotopenthedestinationfileforwriting.\n"); fclose(sourceFile);
return1;
}
charch;
while((ch=fgetc(sourceFile))!=EOF)
fputc(ch,destinationFile);
fclose(sourceFile);
fclose(destinationFile);
printf("Filecontentscopiedsuccessfully.\n"); return
0;
4. SampleInputandOutput:
Couldnotopenthesourcefilefor reading.
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
Mergetwofilesintothethirdfileusingcommand-linearguments
Mergetwofilesintothethirdfileusingcommand-linearguments
Exp.No:
Date:
1. Aim:
WriteaCprogramtomergetwofilesintothethirdfileusingcommand-linearguments.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
intmain(intargc,char*argv[]){ if
(argc != 4) {
printf("Usage:%s<inputFile1><inputFile2><outputFile>\n",argv[0]);
return 1;
FILE*inputFile1,*inputFile2,*outputFile;
if(inputFile1==NULL) {
printf("Couldnotopenthefirstinputfile forreading.\n");
inputFile2=fopen(argv[2],"r"); if
(inputFile2 == NULL) {
printf("Couldnotopenthesecondinputfileforreading.\n"); fclose(inputFile1);
Mergetwofilesintothethirdfileusingcommand-linearguments
return1;//Returnanerrorcode
outputFile=fopen(argv[3],"w"); if
(outputFile == NULL) {
printf("Couldnotopentheoutputfileforwriting.\n");
fclose(inputFile1);
fclose(inputFile2);
return1;//Returnanerrorcode
charch;
while((ch=fgetc(inputFile1))!=EOF)
{ fputc(ch, outputFile);
while((ch=fgetc(inputFile2))!=EOF)
{ fputc(ch, outputFile);}
fclose(inputFile1);
fclose(inputFile2);
fclose(outputFile);
printf("Filesmergedsuccessfully.\n");
return 0; }
4. SampleInputandOutput:
Filesmergedsuccessfully
5. Result:
SuccessfullyExecuted.
6. Reference:https://www.vtuloop.com/program-13-c-programming-lab/
Findno.oflines, wordsandcharactersina file
Findno.oflines,wordsandcharactersinafile
Exp.No:
Date:
1. Aim:
Findno.oflines,wordsand charactersinafile
2. SoftwareRequired:
TURBOC
3. Program:
#include<stdio.h>
voidcountLinesWordsCharacters(FILE*file,int*lines,int*words,int *characters)
intch;
intinWord=0;
*lines=*words=*characters=0; while
(*characters)++; if
(ch == '\n')
(*lines)++;
} else if (inWord == 0)
{ inWord=1;//Insideaword
Dept of CSE
Findno.oflines, wordsandcharactersina file
(*words)++;
intmain()
{ FILE*fil
e;
charfileName[50];
printf("Enterthenameofthefile:");
scanf("%s", fileName);
file=fopen(fileName,"r"); if
(file == NULL) {
printf("Couldnotopenthefileforreading.\n"); return
intlines,words,characters;
countLinesWordsCharacters(file,&lines,&words,&characters); fclose(file);
printf("Numberofcharacters:%d\n",characters); return
0;
4. SampleInputandOutput:
Dept of CSE
Findno.oflines, wordsandcharactersina file
Couldnotopenthefileforreading.
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
Dept of CSE
Printlastn charactersofagivenfile
Printlastncharactersofagivenfile
Exp.No:
Date:
1. Aim:
WriteaCprogramto printlastncharactersofagivenfile.
2. SoftwareRequired:
TURBOC
3. Program:
#include <stdio.h>
#include<stdlib.h>
voidprintLastNCharacters(FILE*file,intn)
fseek(file,0,SEEK_END);
longstartPosition=fileSize-n; if
(startPosition< 0)
startPosition=0;
fseek(file,startPosition,SEEK_SET);
int ch;
while((ch=fgetc(file)) !=EOF)
putchar(ch);
Deptof CSE
Printlastn charactersofagivenfile
int main()
FILE*file;
charfileName[50];
int n;
printf("Enterthenameofthefile:");
scanf("%s", fileName);
file=fopen(fileName,"r");
if (file == NULL)
printf("Couldnotopenthefileforreading.\n"); return
1;
printf("Enterthevalueof'n':"); scanf("%d",
&n);
printf("Last%dcharactersofthefile:\n",n);
printLastNCharacters(file, n);
fclose(file);
return 0;
Deptof CSE
Printlastn charactersofagivenfile
4. SampleInputandOutput:
Couldnotopenthefileforreading.
5. Result:
SuccessfullyExecuted.
6. Reference:
https://www.vtuloop.com/program-13-c-programming-lab/
Deptof CSE