Post on 03-Aug-2020
CS11001/CS11002ProgrammingandDataStructures
(PDS)(Theory:3-0-0)
Teacher:SourangshuBha@acharyasourangshu@gmail.com
h@p://cse.iitkgp.ac.in/~sourangshu/
DepartmentofComputerScienceandEngineeringIndianInsJtuteofTechnologyKharagpur
AcompleteCprogram
voidPRINT(){
prin1(“HelloEverybody!!!\n”);}
voidPRINT_I(intb){
prin1(“%d\n”,b);}
voidPRINT_F(floatp,floatq){
prin1(“%2.1f%2.2f\n”,p,q);}
/*prog.c*/#include<stdio.h>voidPRINT();voidPRINT_I(int);voidPRINT_F(float,float);voidmain(){
inta=10;floatx,y;scanf(“%d%d”,&x,&y);PRINT();PRINT_I(a);PRINT_F(x,y);
}
CompilaJonandExecuJon
$cc–Wallprog.c$$./a.out2.343.45HelloEverybody!!!102.33.45$
AcompleteCprogram/*prog.c*/#include<stdio.h>voidPRINT();voidPRINT_I(int);voidPRINT_F(float,float);voidmain(????){
inta=10;floatx,y;scanf(“%d%d”,&x,&y);PRINT();PRINT_I(a);PRINT_F(x,y);
}
voidPRINT(){
prin1(“HelloEverybody!!!\n”);}
voidPRINT_I(intb){
prin1(“%d\n”,b);}
voidPRINT_F(floatp,floatq){
prin1(“%2.1f%2.2f\n”,p,q);}
CommandLineArguments
• Commandlineargumentsmaybepassedbyspecifyingthemundermain().
intmain(intargc,char*argv[]);
Argument Count Array of Strings
as command line arguments including the command itself.
Passingparameterstomain()
#include<stdio.h>intmain(intargc,char*argv[]){inti;for(i=0;i<argc;i++){prin1("%d:%s\n",i,argv[i]);}return0;}
$cc-Wallwk13_commandline.c$./a.out0:./a.out$./a.outHI0:./a.out1:HI$./a.outIndianInshtuteofTechnology0:./a.out1:Indian2:Inshtute3:of4:Technology
Passingparameterstomain()
#include<stdio.h>intmain(intargc,char*argv[]){inti;for(i=0;i<argc;i++){prin1("%d:%s\n",i,argv[i]);}return0;}
$Jme./a.outIndianInsJtuteofTechnology0:./a.out1:Indian2:Inshtute3:of4:Technologyreal0m0.002suser0m0.001ssys0m0.001s
Passingparameterstomain()#include<stdio.h>intmain(intargc,char*argv[]){inti;for(i=0;i<argc;i++){prin1("%d:%s\n",i,argv[i]);}return0;}
$./a.outAnirban218.30:./a.out1:Anirban2:213:8.3
./a.out Anirban 21 8.3
argc=4
./a.out Anirban
21 argv
8.3
LibraryfuncJonsscanf()
• Headerfile:– #include<stdio.h>
• Funchonprototype:– intsscanf(constchar*str,constchar*format,...);
• Conversioncharacterissameasscanf().
Passingparameterstomain()
#include<stdio.h>intmain(intargc,char*argv[]){inti;for(i=0;i<argc;i++){prin1("%d:%s\n",i,argv[i]);}return0;}
#include<stdio.h>intmain(intargc,char*argv[]){charname[20];intage;floatcgpa;sscanf(argv[1],"%s",name);sscanf(argv[2],"%d",&age);sscanf(argv[3],"%f",&cgpa);prin1("%s%d%f\n",
name,age,cgpa);return0;}
$./a.outAnirban218.30:./a.out1:Anirban2:213:8.3$
$./a.outAnirban218.3Anirban218.300000$
FuncJonstoconvertstringstonumbers
• Oncewe'vegotastringwithanumberinit(eitherfromafileorfromtheusertyping)wecanuseatoioratoftoconvertittoanumber
• Thefunchonsarepartofheaderfilestdlib.hchar numberstring[]= "3.14"; int i; double pi; pi= atof (numberstring); i= atoi ("12"); Bothofthesefunchonsreturn0iftheyhaveaproblem
Example:AveragefromCommandLine
#include<stdio.h>#include<stdlib.h>intmain(intargc,char*argv[]){floatsum=0;inti,num;num=argc-1;for(i=1;i<=num;i++) sum+=atof(argv[i]);prin1("Average=%f\n",sum/(float)num);return0;}
$ ./a.out 45 239 123 Average=135.666667 $
Passingparameterstomain()• Twoparameterswillbepassedtofunchonmain()through
commandline–argcandargv.
• Nameoftheparametersarefixed.
• argcisofintegertypeanditstoresthenumberofparameters(delimitedbyspace)inthecommandline.
• argvisa2Darrayofcharactersanditstoresallthewordsinthecommandline.
• Bydefaultalltheparametersaretakenasarrayofcharacters(strings)thatcanbeconvertedtootherdatatypes.
FileHandling
AdvantagesofFilehandling
• Athmessizeoftheprograminputisverylarge.
• Duringtheteshngphaseprovidinginputsintheinterachvewayistedious.
• Thesizeoftheprogramoutputmaybelargeenoughandwillnotfitinasinglescreen.
• Youmaywishtostoretheoutputforfutureanalysis.
FilehandlinginC
• Afileneedstobeopenedfirstforanyinput/outputoperahonsonthefile.– Itmaybeopenedforreading/wrihng/appending.
• Thefilemustbeclosedoncetheuse/handlingofthefileisover.
• Inbetweentheaddressofthefilewillbestoredinapointerdatatypeviz.,FILE*.
FilehandlinginC
• InCweuseFILE*torepresentapointertoafile.• fopenisusedtoopenafile.ItreturnsapointertothefileifsuccessfullyopenedthefileelseitreturnsNULL.
FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* DO SOMETHING */ }
exit()funcJon• Somehmeserrorcheckingmeanswewantan"emergencyexit"fromaprogram.Wewantittostopdead.
• Inmainwecanuse"return"tostop.• Infunchonswecanuseexittodothis.• Libraryfilestdlib.histheheaderfileforexit()funchon.
FILE*fptr;charfilename[]="file2.dat";fptr=fopen(filename,"w");if(fptr==NULL){prin1(“ERRORINFILECREATION”);exit(-1);}
Modesforopeningfiles
• Thesecondargumentoffopenisthemodeinwhichweopenthefile.
• "r"opensafileforreading.
• "w"createsafileforwrihng-andwritesoverallpreviouscontents(deletesthefilesobecareful!).
• "a"opensafileforappending-wrihngontheendofthefile.
Closingafile
• Wecancloseafilesimplyusingfclose()andthefilepointer.
FILE *fptr; char filename[]= "myfile.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf ("Cannot open file to write!\n"); exit(-1); } fprintf (fptr,"Hello World of filing!\n"); fclose (fptr);
Opening
Access
closing
WriJngtoafileusingfprin\()
• fprin1()worksjustlikeprin1andsprin1exceptthatitsfirstargumentisafilepointer.
FILE *fptr; fptr= fopen ("file.dat","w"); /* Check it's open */ fprintf (fptr,"Hello World!\n");
ReadingDataUsingfscanf()
FILE*fptr;fptr=fopen(“input.dat”,“r”);/*Checkit'sopen*/if(fptr==NULL){prin1(“Errorinopeningfile\n”);}fscanf(fptr,“%d%d”,&x,&y);
20 30
input.dat
x=20 y=30
ReadinglinesfromafileusingWecanreadastringusingfgets().
FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000,fptr) != NULL) { printf ("Read line %s\n",line); }
fgets() takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF).
Checkwhetheramatrixissymmetricornot–V1
#include<stdio.h>intReadMat(intmat[1000][1000]){inti,j,size;prin1(“Matrixsize?:\n");scanf("%d",&size);for(i=0;i<size;i++)for(j=0;j<size;j++)scanf("%d",&mat[i][j]);returnsize;}
intmain(){charsymm='y';inti,j,size,mat[1000][1000];size=ReadMat(mat);for(i=0;i<size;i++){for(j=i+1;j<size;j++){if(mat[i][j]!=mat[j][i])symm='n';break;}if(symm=='n')break;}if(symm=='y')prin1("SymmetrixMatrix\n");elseprin1("NotSymmetric");return0;}
Checkwhetheramatrixissymmetricornot–V2
#include<stdio.h>intReadMat(intmat[1000][1000]){inti,j,size;FILE*fp;fp=fopen("Matrix.txt","r");//prin1(“Matrixsize:\n");fscanf(fp,"%d",&size);for(i=0;i<size;i++)for(j=0;j<size;j++)fscanf(fp,"%d",&mat[i][j]);fclose(fp);returnsize;}
intmain(){charsymm='y';inti,j,size,mat[1000][1000];size=ReadMat(mat);for(i=0;i<size;i++){for(j=i+1;j<size;j++){if(mat[i][j]!=mat[j][i])symm='n';break;}if(symm=='n')break;}if(symm=='y')prin1("SymmetrixMatrix\n");elseprin1("NotSymmetric");return0;}
Checkwhetheramatrixissymmetricornot–V3
#include<stdio.h>intReadMat(intmat[1000][1000]){charfilename[100];inti,j,size;FILE*fp;scanf(“%s”,filename);fp=fopen(filename,"r");//prin1(“Matrixsize:\n");fscanf(fp,"%d",&size);for(i=0;i<size;i++)for(j=0;j<size;j++)fscanf(fp,"%d",&mat[i][j]);fclose(fp);returnsize;}
intmain(){charsymm='y';inti,j,size,mat[1000][1000];size=ReadMat(mat);for(i=0;i<size;i++){for(j=i+1;j<size;j++){if(mat[i][j]!=mat[j][i])symm='n';break;}if(symm=='n')break;}if(symm=='y')prin1("SymmetrixMatrix\n");elseprin1("NotSymmetric");return0;}
Checkwhetheramatrixissymmetricornot–V4
#include<stdio.h>intReadMat(charfilename,intmat[1000][1000]){inti,j,size;FILE*fp;fp=fopen(filename,"r");//prin1(“Matrixsize:\n");fscanf(fp,"%d",&size);for(i=0;i<size;i++)for(j=0;j<size;j++)fscanf(fp,"%d",&mat[i][j]);fclose(fp);returnsize;}
intmain(intargc,char*argv[]){charsymm='y';inti,j,size,mat[1000][1000];size=ReadMat(argv[1],mat);for(i=0;i<size;i++){for(j=i+1;j<size;j++){if(mat[i][j]!=mat[j][i])symm='n';break;}if(symm=='n')break;}if(symm=='y')prin1("SymmetrixMatrix\n");elseprin1("NotSymmetric");return0;}
BalancedSymbolChecking
Inprocessingprogramsandworkingwithcomputerlanguagestherearemanyinstanceswhensymbolsmustbebalanced{},[],()
WriteaprogramthatwilltakeaCprogramfileascommandlineinputandprintswhetheralltheparenthesis,curlyandsquarebracketsthatareopenedhasclosedornot.
BalancedSymbolCheckingwhile(line[i]!='\0'){switch(line[i]){case'(':pbracket++;break;case')':pbracket--;break;case'{':cbracket++;break;case'}':cbracket--;break;case'[':sbracket++;break;case']':sbracket--;break;}i++;}}fclose(fp);if(pbracket==0)prin1("ParentesisOpen-Close.\n");elseprin1("ParentesisMismatches.\n");if(cbracket==0)prin1("CurlyOpen-Close.\n");elseprin1("CurlyMismatches.\n");if(sbracket==0)prin1("SquareOpen-Close.\n");elseprin1("SquareMismatches.\n");return0;}
#include<stdio.h>#include<stdlib.h>intmain(intargc,char*argv[]){FILE*fp;charline[500];inti,pbracket,cbracket,sbracket;fp=fopen(argv[1],"r");if(fp==NULL){prin1("Fileopeningerror...exihng");exit(0);}pbracket=cbracket=sbracket=0;while(!feof(fp)){fgets(line,100,fp);i=0;
Didfileopenproperly?
Fileendisnotreached.
BalancedSymbolChecking
Inprocessingprogramsandworkingwithcomputerlanguagestherearemanyinstanceswhensymbolsmustbebalanced{},[],()
FollowingCsyntax: - {}[]()….isallowed - {[}]()…isnotallowed.
Algorithm:BalancedSymbolChecking
• Makeanemptystack
• Readcharactersunhlendoffile– Ifasymbolisanopeningsymbolpushitontothestack– Ifasymbolisaclosingsymbolpopthestack
• ifthestackisemptyreportanerror• ifthepoppedsymboldoesnotmatchtheclosingsymbolreportanerror
• Ifthestackisemptyreportsymbolsarebalanced.
• Elsereportanerror
HomeworkWriteaCprogramthatwilltakeanyCprogramascommandlineinputandwillreportanysyntaxerrorduetobalancinginbracketsymbols.
ThreespecialI/Ostreams
• Threespecialfilestreamsaredefinedinthe<stdio.h>header
• stdinreadsinputfromthekeyboard
• stdoutsendoutputtothescreen
• stderrprintserrorstoanerrordevice(usuallyalsothescreen)
• Whatmightthisdo?
fprintf (stdout,"Hello World!\n");
Anexampleprogram#include<stdio.h>intmain(){ inti; fprin1(stdout,"Givevalueofi\n"); fscanf(stdin,"%d",&i); fprin1(stdout,"Valueofi=%d\n",i); fprin1(stderr,"Noerror:Butanexampletoshowerrormessage.\n");
return0;}$./a.outGivevalueofi15Valueofi=15Noerror:Butanexampletoshowerrormessage.$
Display on the screen
InputFile&OutputFileredirecJon
• Onemayredirecttheinputandoutputfilestootherfiles(otherthanstdinandstdout).
• Usage:Supposetheexecutablefileisa.out$ ./a.out <in.dat >out.dat
15
in.dat
Give value of i Value of i=15
out.dat
No error: But an example to show error message.
Display screen
Example1:Reverseastackusingrecursion
Youarenotallowedtouseloopconstructslikewhile,for..etc
Sampleinput:1234Sampleoutput:4321
4 3 2 1
top
1 2 3 4
top
Example2:Sortastackusingrecursion
Youarenotallowedtouseloopconstructslikewhile,for..etc
Sampleinput:1418-530Sampleoutput: 301814-5
30 -5 18 14
top
-5 14 18 30
top
Example3:ImplementaJonofMergingoperaJoninMergeSortusing
Stacks
-9 -3 56 90
top
-5 14 18 30
top
18 30 56 90
top
-9 -5 -3 14
Example4:Givenastack,printtheNextGreaterElement(NGE)foreveryelement.
• Foranystackthebo}ommostelementalwayshasnextgreaterelementas-1
• Forastackwhichissortedindecreasingorder,allelementshavenextgreaterelementas-1.
• Fortheinputstack[4,5,2,25],thenextgreaterelementsforeachelementareasfollows.
• Element NGE4 55 252 2525 -1
Example5:ImplementaStackusingaLinkedList
-9 -3 56 90
top
90 56 -3 -9
head
Example6:PrintfirstNFibonacciNumbersusingaQueue
Thequeueinihallycontains0and1
1 0
frontrear
Example7:UseaStacktoreverseaQueue
30 -5 18 14
frontrear
14 18 -5 30
top
14 18 -5 30
frontrear
Example 8: Create a newQueuewith givenelementsappendedattheendoftheQueueinareverseorder
*Hint-Youcanuseastackinordertoachievetheoutcome
30 -5 18 14
frontrear
14 18 -5 30
frontrear
30 -5 18 14
Example9:ImplementaStackusingaQueuedatastructure
ForagivenstackcreateasamesizearraywhichyouaregoingtouseasaQueue.
Pushandpopoperahonofstack’sshouldbeemulatedwiththeEnqueueandDequeueoperahon.
YoucanuseanintermediateQueuefortheaboveimplementahon.
Example10:ImplementaQueueusingaLinkedList
30 -5 18 14
head 30 -5 18 14
frontrear