You are on page 1of 7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified
Search

Home

Cprogrammingexamples

Cprogrammingexamples:Theseprogramsillustratevariousprogrammingelements,
conceptssuchasusingoperators,loops,functions,singleanddoubledimensionalarrays,
performingoperationsonstrings,files,pointersetc.Browsethecodefromsimplecprogram
tocomplicatedonesyouarelookingfor,everyoneofthemisprovidedwithoutput.C
programdownloadwithexecutablefiles,sothatyousaveonyourcomputerandrun
programswithoutcompilingthesourcecode.Allprogramsaremadeusingcprogramming
languageandCodeblocks,mostofthesewillworkunderDevC++compileralso.Download
softwareyouneedtodevelopcodes.Thefirstprogramprints"HelloWorld"onscreen.

Cprogrammingcodes
Helloworld
PrintInteger
Addition
OddorEven
Add,subtract,multiplyanddivide
Checkvowel
Leapyear
Adddigits
Factorial
HCFandLCM
Decimaltobinaryconversion
ncRandnPr
Addnnumbers
Swapping
Reversenumber
Palindromenumber
PrintPattern
Diamond
Primenumbers
Findarmstrongnumber
Generatearmstrongnumber
Fibonacciseries
Printfloyd'striangle
Printpascaltriangle
Additionusingpointers
Maximumelementinarray
Minimumelementinarray
Linearsearch
Binarysearch
http://www.programmingsimplified.com/cprogramexamples

1/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

Reversearray
Insertelementinarray
Deleteelementfromarray
Mergearrays
Bubblesort
Insertionsort
Selectionsort
Addmatrices
Subtractmatrices
Transposematrix
Multiplytwomatrices
Printstring
Stringlength
Comparestrings
Copystring
Concatenatestrings
Reversestring
Findpalindrome
Stringtointeger
Deletevowels
Csubstring
Checksubsequence
Sortastring
Removespaces
Changecase
Swapstrings
Character'sfrequency
Anagrams
Readfile
Copyfiles
Mergetwofiles
Listfilesinadirectory
Deletefile
Randomnumbers
Addcomplexnumbers
Printdate
GetIPaddress
Shutdowncomputer

Cprogramexamples
Example1Chelloworldprogram
/*Averysimplecprogramprintingastringonscreen*/
#include<stdio.h>

main()
{
printf("HelloWorld\n");
return0;
}

Outputofaboveprogram:
"HelloWorld"
Example2cprogramtotakeinputfromuserusingscanf
#include<stdio.h>

main()
{

http://www.programmingsimplified.com/cprogramexamples

2/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

intnumber;

printf("Enteraninteger\n");
scanf("%d",&number);

printf("Integerenteredbyyouis%d\n",number);

return0;
}

Output:
Enteranumber
5
Numberenteredbyyouis5
Example3usingifelsecontrolinstructions
#include<stdio.h>

main()
{
intx=1;

if(x==1)
printf("xisequaltoone.\n");
else
printf("Forcomparisonuse==as=istheassignmentoperator.\n");

return0;
}

Output:
xisequaltoone.
Example4loopexample
#include<stdio.h>

main()
{
intvalue=1;

while(value<=3)
{
printf("Valueis%d\n",value);
value++;
}

return0;
}

Output:
Valueis1
Valueis2
Valueis3
Example5cprogramforprimenumber
#include<stdio.h>

main()
{
intn,c;

printf("Enteranumber\n");
scanf("%d",&n);

if(n==2)
printf("Primenumber.\n");
else
{
for(c=2;c<=n1;c++)
{
if(n%c==0)

http://www.programmingsimplified.com/cprogramexamples

3/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

break;
}
if(c!=n)
printf("Notprime.\n");
else
printf("Primenumber.\n");
}
return0;
}

Example6commandlinearguments
#include<stdio.h>

main(intargc,char*argv[])
{
intc;

printf("Numberofcommandlineargumentspassed:%d\n",argc);

for(c=0;c<argc;c++)
printf("%d.Commandlineargumentpassedis%s\n",c+1,argv[c]);

return0;
}

Abovecprogramprintsthenumberandallargumentswhicharepassedtoit.
Example7Arrayprogram
#include<stdio.h>

main()
{
intarray[100],n,c;

printf("Enterthenumberofelementsinarray\n");
scanf("%d",&n);

printf("Enter%delements\n",n);

for(c=0;c<n;c++)
scanf("%d",&array[c]);

printf("Arrayelementsenteredbyyouare:\n");

for(c=0;c<n;c++)
printf("array[%d]=%d\n",c,array[c]);

return0;
}

Example8functionprogram
#include<stdio.h>

voidmy_function();

main()
{
printf("Mainfunction.\n");

my_function();

printf("Backinfunctionmain.\n");

return0;
}

voidmy_function()
{
printf("Welcometomyfunction.Feelathome.\n");
}

Example9Usingcommentsinaprogram
#include<stdio.h>

http://www.programmingsimplified.com/cprogramexamples

4/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

main()
{
//Singlelinecommentincsourcecode

printf("Writingcommentsisveryuseful.\n");

/*
*Multilinecommentsyntax
*Commentshelpustounderstandcodelatereasily.
*Willyouwritecommentswhiledevelopingprograms?
*/

printf("Goodluckcprogrammer.\n");

return0;
}

Example10usingstructuresincprogramming
#include<stdio.h>

structprogramming
{
floatconstant;
char*pointer;
};

main()
{
structprogrammingvariable;
charstring[]="ProgramminginSoftwareDevelopment.";

variable.constant=1.23;
variable.pointer=string;

printf("%f\n",variable.constant);
printf("%s\n",variable.pointer);

return0;
}

Example11cprogramforFibonacciseries
#include<stdio.h>

main()
{
intn,first=0,second=1,next,c;

printf("Enterthenumberofterms\n");
scanf("%d",&n);

printf("First%dtermsofFibonacciseriesare:\n",n);

for(c=0;c<n;c++)
{
if(c<=1)
next=c;
else
{
next=first+second;
first=second;
second=next;
}
printf("%d\n",next);
}

return0;
}

Example12cgraphicsprogramming
#include<graphics.h>
#include<conio.h>

main()
{
intgd=DETECT,gm;

initgraph(&gd,&gm,"C:\\TC\\BGI");

http://www.programmingsimplified.com/cprogramexamples

5/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

outtextxy(10,20,"Graphicssourcecodeexample.");

circle(200,200,50);

setcolor(BLUE);

line(350,250,450,50);

getch();
closegraph();
return0;
}

ForGCCusers
IfyouareusingGCConLinuxoperatingsystemthenyouneedtomodifyprograms.For
exampleconsiderthefollowingprogramwhichprintsfirsttennaturalnumbers
#include<stdio.h>
#include<conio.h>

intmain()
{
intc;

for(c=1;c<=10;c++)
printf("%d\n",c);

getch();
return0;
}

Abovesourcecodeincludesaheaderfile <conio.h> andusesfunctiongetch,butthisfile


isBorlandspecificsoitworksinturboccompilerbutnotinGCC.SothecodeforGCC
shouldbelike
#include<stdio.h>

intmain()
{
intc;

/*forloop*/

for(c=1;c<=10;c++)
printf("%d\n",c);

return0;
}

IfusingGCCthensavethecodeinafilesaynumbers.c,tocompiletheprogramopenthe
terminalandentercommandgccnumbers.c,thiswillcompiletheprogramandtoexecute
theprogramentercommand./a.out,donotusequoteswhileexecutingcommands.

Cprogrammingtutorial
Cprogramconsistsoffunctionsanddeclarationsorinstructionsgiventothecomputerto
performaparticulartask.Theprocessofwritingaprograminvolvesdesigningthe
algorithm,aflowchartmayalsobedrawn,andthenwritingthesourcecode,after
developingtheprogramyouneedtotestitanddebugitifitdoesnotmeettherequirement.
Tomakeaprogramyouneedatexteditorandacompiler.Youcanuseanytexteditorof
yourchoiceandacompiler.Ccompilerconvertssourcecodeintomachinecodethat
consistsofzeroandoneonlyanddirectlyexecutedonmachine.AnIDEorIntegrated
DevelopmentEnvironmentprovidesatexteditor,compiler,debuggeretc.fordeveloping
programsorprojects.DownloadCodeblocksIDEitprovidesanidealenvironmentfor
development.ItcanimportMicrosoftVisualC++projects,extendableasitusesplugins,
opensourceandcrossplatform.
Acprogrammusthaveatleastonefunctionwhichismain,functionconsistsofdeclaration
http://www.programmingsimplified.com/cprogramexamples

6/7

11/8/2015

Cprogrammingexamples|ProgrammingSimplified

andstatements,astatementisanexpressionfollowedbyasemicolon,forexamplea+b,
printf("cprogramexamples")areexpressionsanda+bandprintf("Cisaneasytolearn
computerprogramminglanguage.")arestatements.Touseavariablewemustindicateits
typewhetheritisaninteger,float,character.Clanguagehasmanybuiltindatatypesand
wecanmakeourownusingstructuresandunions.Everydatatypehasitsownsizethat
maydependonmachineforexampleanintegermaybeof2or4Bytes.Dataisstoredin
binaryformi.e.groupofbitswhereeachbitmaybe'0'or'1'.Keywordssuchasswitch,case,
default,registeretc.arespecialwordswithpredefinedmeaningandcan'tbeusedforother
purposes.Memorycanbeallocatedduringcompiletimeoratruntimeusingmallocor
calloc.Clanguagehasmanyfeaturessuchasrecursion,preprocessor,conditional
compilation,portability,pointers,multithreadingbyusingexternallibraries,dynamic
memoryallocationduetowhichitisusedformakingportablesoftwareprogramsand
applications.NetworkingAPI'sareavailableusingwhichcomputeruserscancommunicate
andinteractwitheachother,sharefilesetc.Cstandardlibraryoffersfunctionsfor
mathematicaloperations,characterstringsandinput/outputandtime.Theprocessof
makingprogramswhichisknownascodingrequiresknowledgeofprogramminglanguage
andlogictoachievethedesiredoutput.Soyoushouldlearncprogrammingbasicsandstart
makingprograms.Learningdatastructuressuchasstacks,queues,linkedlistsetc.usingc
programmingprovidesyouagreaterunderstandingasyoulearneverythingindetail.
Generalbeliefistogoforotherhighlevellanguagesbutit'sagoodideatolearncbefore
learningC++orJava.C++programminglanguageisobjectorientedanditcontainsallthe
featuresofclanguagesolearningcfirstwillhelpyoutoeasilylearnC++andthenyoucan
goforJavaprogramming.

CprogrammingPDFdownloadsandothersoftware
Devc++compiler
Chandbook
Essentialc

Cprogrammingbooks
Ifyouareabeginnerthenbuyanyoneoffirsttwobooksmentionedbelowandifyouhave
previousprogrammingexperienceoryouknowbasicsofclanguagethenyoucanbuythird
one.
LetUsCByYashavantKanetkar
PROGRAMMINGWITHCByByronGottfried,JitenderChhabra
TheCProgrammingByBrianKernighanandDennisRitchie

PythonGUIAppBuilder
BuildGUI,WebandMobileApps.FreeDownload
Windows/OSX/Linux

http://www.programmingsimplified.com/cprogramexamples

7/7

You might also like