Upload
others
View
26
Download
0
Embed Size (px)
Citation preview
CS11001/CS11002ProgrammingandDataStructures
(PDS)(Theory:3-0-0)
Teacher:SourangshuBha@[email protected]
h@p://cse.iitkgp.ac.in/~sourangshu/
DepartmentofComputerScienceandEngineeringIndianInsJtuteofTechnologyKharagpur
TentaJveSyllabusIntroducJontodigitalcomputersBasicprogrammingconstructs
VariablesandsimpledatatypesAssignmentsInput/outputCondi7onsandbranchingLoopsanditera7onItera7vesearchingandsor7ngalgorithmsProgrammingExamples:Sor7ng…etc
Advancedprogrammingconstructs
Func7onsandrecursionRecursivesor7ngalgorithmsArraysandstrings StructuresPointersanddynamicmemoryalloca7on
FileHandling
TentaJveSyllabus
PerformanceanalysisofprogramsDatastructures
AbstractdatatypesOrderedlistsStacksandqueues
ProgrammingLanguage:C
CourseMaterials
Donotusebookswri@enonspecificCcompilerslikeTurboC,gccUseanystandardtextbookonANSICSomeusefultextbooks:ü BrianW.KernighanandDennisM.Ritchie
TheCProgrammingLanguage,Pren7ceHallofIndia.ü E.Balaguruswamy
ProgramminginANSIC,TataMcGraw-Hillü ByronGoTried
Schaum’sOutlineofProgrammingwithC,McGraw-Hillü SeymourLipschutz,
DataStructures,Schaum’sOutlineSeries,TataMcGraw-Hillü EllisHorowitz,SatrajSahniandSusanAnderson-Freed,
FundamentalsofDataStrcuturesinC,W.H.FreemnandCompany
CourseMaterials
Webreferences:
hWp://cse.iitkgp.ac.in/~pds/
SomeusefulsoYware:hWp://cse.iitkgp.ac.in/~pds/soYware/
Notes:
hWp://cse.iitkgp.ac.in/~pds/notes/
Courserelatedinforma7onandannouncements:hWp://cse.iitkgp.ac.in/~pds/current/
A@endanceintheclassesisMANDATORY
StudentshavingpooraWendancewillbepenalizedintermsofthefinalgrade/deregistra7on.
ProxyintheaWendancewillbeheavilypenalized.Eachproxyin
theclasswillresultinthededuc7onof5marksfromtotalmarksyouobtained.
ItisyourresponsibilitytochecknosuchaWendancemarked
againstyou.
CourseFactsforsecJon1,2,3
Ø SecJons:1,2,3Ø ClassRoom:V2
Ø TimeSchedule:Monday8:00–09:55am,Wednesday12:00–12:55pm
Ø ClassTeacher:SudeshnaSarkar
Ø TeachingAssistant(TA):AbhijitMondal
AnandaDasMadhumitaMallickSaptarshiMisra
CourseFactsforsecJons4,5Ø SecJons:4,5Ø ClassRoom:NR121
Ø TimeSchedule:Wednesday12:00–12:55pm,Thursday11:00–11:55,Friday9:00–09:55
Ø ClassTeacher:DebasisSamanta
Ø TeachingAssistant(TA):CheemaBaljeetSingh
SreejaSRAnushriSahaAnoopA
CourseFactsforsecJons6,7Ø SecJons:6,7Ø ClassRoom:NR222
Ø TimeSchedule:Monday(10:00-10:55);Wednesday(9:00-9:55);Thursday(10:00-10:55)
Ø ClassTeacher:SourangshuBhaWacharya
Ø TeachingAssistant(TA):RijulaKar,
AbirDey,SangaChaki,SankarshanMridha
CourseFactsDistribuJonofMarks:
ClassTest1: 10MidSemesterExam: 30ClassTest2: 10EndSemesterExam: 50
ImportantDates:
ClassTest1:Thursday,February2,2017,7:00-8:00pmClassTest2: WednesdayMarch15,20177:00-8:00pmMid-Semester: February12-21,2017(asperins7tuteschedule)End-Semester: April20–April28,2017(asperins7tuteschedule)
TentaJvesyllabusoftests:
CT1syllabus: Un7lArraysandStringsMidSem: Un7lFunc7ons,includingrecursionCT2: Un7lArrays(2D)EndSem: Everything
Let us see
WhatisaComputer?
Central Processing
Unit (CPU)
Input Device
Output Device
Main Memory
Storage (Hard disk)
It is a machine which can accept data, process them, and output results.
The Box
CentralProcessingUnit(CPU)
– Allcomputa7onstakeplacehereinorderforthecomputertoperformadesignatedtask.
– Ithasalargenumberofregisterswhichtemporarilystoredataandprograms(instruc7ons).
– Ithascircuitrytocarryoutarithme7candlogicopera7ons,takedecisions,etc.
– Itretrievesinstruc7onsfromthememory,interprets(decodes)them,andperformtherequestedopera7on.
while<powerison>1.fetchtheinstruc@on <decodeit>2.executetheinstruc@on
• Usessemiconductortechnology• Allowsdirectaccess• RAM–RandomAccessMemory
– Somemeasurestoberemembered• 1K=210(=1024)• 1M=220(=onemillionapprox.)• 1G=230(=onebillionapprox.)
MainMemory
InputOutput(I/O)• InputDevice
– Keyboard,Mouse,Scanner,DigitalCamera• OutputDevice
– Monitor,Printer• StoragePeripherals
– Magne7cDisks:harddisk,floppydisk• Allowsdirectaccess
– Op7calDisks:CDROM,CD-RW,DVD• Allowsdirectaccess
– FlashMemory:pendrives• Allowsdirectaccess
– Magne7cTape:DAT• Onlysequen7alaccess
TypicalConfiguraJonofaPC
• CPU: Intel(R)Core(TM) i5-4570CPU,3.2GHz
• MainMemory: 4GB• HardDisk: 500GB• FloppyDisk: Notpresent• CDROM: DVDRWcombo-drive• InputDevice: Keyboard,Mouse• OutputDevice: Monitor• Ports: USB,Firewire,Infrared
NumberSystem• Decimalnumbersystem
– Tendigits:0,1,2,3,4,5,6,7,8,9– Everydigitposi7onhasaweight:powerof10.
• Example:234 =2x102+3x101+4x100
250.67=2x102+5x101+0x100 +6x10-1+7x10-2
Numbersystemindigitalcomputer
• Adigitalcomputerisbuiltoutof7nyelectronicswitches.– Fromtheviewpointofeaseofmanufacturingandreliability,suchswitchescanbeinoneoftwostates,ONorOFF.
– Thiscanberepresentedby0(OFF)and1(ON).
• Thissuggestsforabinarynumbersystemforadigitalcomputer.
ConceptofBitsandBytes• Bit
– Asinglebinarydigit(0or1).• Nibble
– Acollec7onoffourbits(say,0110).• Byte
– Acollec7onofeightbits(say,01000111).• Kilobyte(KB),MB,GB
– ?????• Word
– Dependsonthecomputer.– Typically4or8bytes(thatis,32or64bits).
DecimalandBinary
• Ak-bitdecimalnumber– Canexpressunsignedintegersintherange0to10k–1
• Fork=3,from0to999.
• Ak-bitbinarynumber– Canexpressunsignedintegersintherange0to2k–1
• Fork=8,from0to255.• Fork=10,from0to1023.
ComputerLanguages
• MachineLevelLanguage(MLL)– Expressedinbinary.– Directlyunderstoodbythecomputer.– Notportable;variesfromonemachinetypetoanother.
• ProgramwriWenforonetypeofmachinewillnotrunonanothertypeofmachine.
– Difficulttouseinwri7ngprograms.
Example:MachineLevelLanguage
Binary Hexadecimal
ComputerLanguages• AssemblyLevelLanguage(ALL)
– Mnemonicformofmachinelanguage.– Easiertouseascomparedtomachinelanguage.
• Forexample,use“ADD”insteadof“10110100”.
– Notportable(likemachinelanguage).– Requiresatranslatorprogramcalledassembler.
Assembler Assembly language program
Machine language program
Example:AssemblyLevelLanguage
• Assemblylanguageisalsodifficulttouseinwri7ngprograms.– Requiresmanyinstruc7onstosolveaproblem.
• Example:Findtheaverageofthreenumbers.MOV A,X ; A = X ADD A,Y ; A = A + Y
ADD A,Z ; A = A + Z DIV A,3 ; A = A / 3
MOV RES,A ; RES = A
RES = (X + Y + Z) / 3
High-LevelLanguage• Machinelanguageandassemblylanguagearecalledlow-levellanguages.– Theyareclosertothemachine.– Difficulttouse.
• High-levellanguagesareeasiertouse.– Theyareclosertotheprogrammer.– Examples:
• Fortran,Cobol,C,C++,Java.– Requiresanelaborateprocessoftransla7on.
• UsingasoYwarecalledcompiler.– Theyareportableacrossplavorms.
Example:HighLevelLanguage
• Example:Findtheaverageofthreenumbers.
RES = (X + Y + Z) / 3
TherelaJonship
HighLevelLanguage
AssemblyLevelLanguage
MachineLevelLanguage
Assembler
Compiler
ClassificaJonofSoeware
1. Applica7onSoYware• Usedtosolveapar7cularproblem.• Editor,financialaccoun7ng,weatherforecas7ng,etc.
2. SystemSoYware• Helpsinrunningotherprograms.• Compiler,opera7ngsystem,etc.
OperaJngSystems
• A system soYware to interface between computerhardware and soYware resources includingapplica7onprograms.
• Categoriesofopera7ngsystems:– Singleuser– Mul7user
• Timesharing• Mul7tasking• Real7me
OperaJngSystems• Popularopera7ngsystems:
– DOS: single-user– Windows: single-usermul7tasking– Unix: mul7-user– Linux: afreeversionofUnix
• ThelaboratoryclasswillbebasedonUnix.
Programming in C
UniversalstarJngpoint
#include <stdio.h> int main() { printf (“Hello World\n”); return 0;
}
Header file includes functions for input/output
Main function is executed when you run the program. (Later we will see how to pass its parameters)
Curly braces within which statements are executed one after another.
Statement for printing the sentence within double quotes (“..”). ‘\n’ denotes end of line.
Returnvaluetofunc7on
1. Writeaprogramandsaveit.2. Compiletheprogramusingthecorrectcompiler.3. Executetheprogram
Threestepstofollow
1.vihello.c#include<stdio.h>intmain(){prini("HelloWorld\n");return0;}2.$cchello.c$3.$./a.outHelloWorld
IntroducJontoC• Cisageneral-purpose,structuredprogramminglanguage.
– Resemblesotherhigh-levelstructuredprogramminglanguages,suchasPascalandFortran-77.
– Alsocontainsaddi7onalfeatureswhichallowittobeusedatalowerlevel.
• Ccanbeusedforapplica7onsprogrammingaswellasforsystemsprogramming.
• Thereareonly32keywordsanditsstrengthliesinitsbuilt-infunc7ons.
• Cishighlyportable,sinceitrelegatedmuchcomputer-dependentfeaturestoitslibraryfunc7ons.
HistoryofC• Originallydevelopedinthe1970’sbyDennisRitchieatAT&TBellLaboratories.– OutgrowthoftwoearlierlanguagesBCPLandB.
• Popularitybecamewidespreadbythemid1980’s,withtheavailabilityofcompilersforvariousplavorms.
• Standardiza7onhasbeencarriedouttomakethevariousCimplementa7onscompa7ble.– AmericanNa7onalStandardsIns7tute(ANSI)
StructureofaCprogram• EveryCprogramconsistsofoneormorefunc7ons.
– Oneofthefunc7onsmustbecalledmain.
– Theprogramwillalwaysbeginbyexecu7ngthemainfunc7on.
• Eachfunc7onmustcontain:– Afunc7onheading,whichconsistsofthefunc@onname,followedbyanop7onallistofargumentsenclosedinparentheses.
– Alistofargumentdeclara@ons.
– Acompoundstatement,whichcomprisestheremainderofthefunc7on.
StructureofaCprogram
• Eachcompoundstatementisenclosedwithinapairofbraces:‘{‘and‘}’– Thebracesmaycontaincombina7onsofelementarystatementsandothercompoundstatements.
• Commentsmayappearanywhereinaprogram,enclosedwithindelimiters‘/*’and‘*/’.– Example:
a=b+c;/*ADDTWONUMBERS*/
#include <stdio.h> int main() {
int n; scanf(“%d”,&n); printf(“%d”,n); return 0;
}
InandOutonly#include <stdio.h> int main() {
int n; scanf(“%d”,&n); printf(“%d”,n+n); return 0;
}
#include <stdio.h> int main() {
int n,m; scanf(“%d”,&n);/* Read the value of n */ m=n+n; printf(“%d”,m); return 0;
}
InandOutonly
#include <stdio.h> int main() {
int n,m; scanf(“%d”,&n);/* Read the value of n */ m=n+n; printf(“%d”,m); return 0;
}
Control character for printing value of m in decimal digits.
Integers variables declared before their usage.
Comments within /* .. */
Input statement for reading variable from the keyboard
#include <stdio.h> #define PI 3.1416 double area_of_circle(float); double area_of_circle (float radius) {
return PI*radius*radius; } int main() {
int squareSide; double area; scanf(“%d”, &squareSide); area= area_of_circle(squareSide/2); printf(“Area of the circle enclosing the square of side %d
is: %f\n”, squareSide, area); return 0;
}
AcompleteCprogramIncludeheaderfiles
Declareglobalvariables,constantsandfunc7on
prototypes
Func7onbodies
Theremustbeamainfunc7oninanyCprogram.
#include <stdio.h> #define PI 3.1416 double area_of_circle(float); double area_of_circle (float radius) {
return PI*radius*radius; } int main() {
int squareSide; double area; scanf(“%d”, &squareSide); area= area_of_circle(squareSide/2); printf(“Area of the circle enclosing the square of side %d
is: %f\n”, squareSide, area); return 0;
}
AcompleteCprogramPreprocessor statement. Replace PI by 3.1416 before compilation.
Function called
Example of a function called as per need from main program.
main()funcJon:startofexecuJon
TheCCharacterSet
• TheClanguagealphabet:– UppercaseleWers‘A’to‘Z’– LowercaseleWers‘a’to‘z’– Digits‘0’to‘9’– Certainspecialcharacters:
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank
IdenJfiers• Iden7fiers
– Namesgiventovariousprogramelements(variables,constants,func7ons,etc.)
– MayconsistofleIers,digitsandtheunderscore(‘_’)character,withnospacebetween.
– FirstcharactermustbealeWer.
– Aniden7fiercanbearbitrarylong.• SomeCcompilersrecognizeonlythefirstfewcharactersofthename(16or31).
– Casesensi7ve• ‘area’,‘AREA’and‘Area’arealldifferent.
Keywords• Keywords
– Reservedwordsthathavestandard,predefinedmeaningsinC.
– Cannotbeusedasiden7fiers.
– OKwithincomments.
– StandardCkeywords:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
ValidandInvalidIdenJfiers• ValididenJfiers
Xabcsimple_interesta123LISTstud_nameEmpl_1Empl_2avg_empl_salary
• InvalididenJfiers10abc“hello”simpleinterest(area)%rate
int::integerquan7tyTypicallyoccupies4bytes(32bits)inmemory.
char::singlecharacterTypicallyoccupies1byte(8bits)inmemory.
float::floa7ng-pointnumber(anumberwithadecimalpoint)Typicallyoccupies4bytes(32bits)inmemory.
double::double-precisionfloa7ng-pointnumber
BasicDataTypesinC
Precisionreferstothenumberofsignificantdigitsa6erthedecimalpoint.
AugmentedDataType
• Someofthebasicdatatypescanbeaugmentedbyusingcertaindatatypequalifiers:– short– long– signed– unsigned
• Typicalexamples:– shortint– longint– unsignedint
Integertype
Type Storagesize(inbyte) Valuerange
char 1 -128to127or0to255unsignedchar 1 0to255signedchar 1 -128to127
int 2or4 -32,768to32,767or-2,147,483,648to2,147,483,647
unsignedint 2or4 0to65,535or0to4,294,967,295short 2 -32,768to32,767unsignedshort 2 0to65,535
long 4 -2,147,483,648to2,147,483,647unsignedlong 4 0to4,294,967,295
Integertype
unsignedcharè1byteè8bits è00000000to11111111è0to255
11111111è1×27+1×26+1×25+1×24+1×23+1×22+1×21+1×20
signedcharè1byteè8bits è00000000to11111111è-128to127
1111111è1×26+1×25+1×24+1×23+1×22+1×21+1×20
FloaJng-pointtype
Type Storagesize(inbyte) Valuerange Precision
float 4 1.2E-38to3.4E+38 6decimalplacesdouble 8 2.3E-308to1.7E+308 15decimalplaceslongdouble 10 3.4E-4932to1.1E+4932 19decimalplaces
E or e means “10 to the power of”
ASCIITable
ExtendedASCIITable(AmericanStandardCodeforInforma7onInterchange)
SomeExamplesofDataTypes
• int0,25,-156,12345,-99820
• char‘a’,‘A’,‘*’,‘/’,‘’
• float23.54,-0.00345,25.02.5E12,1.234e-5
E or e means “10 to the power of”
Constants
Constants
Numeric Constants
Character Constants
string single character
floating-point integer
IntegerConstants
• Consistsofasequenceofdigits,withpossiblyaplusoraminussignbeforeit.– Embeddedspaces,commasandnon-digitcharactersarenotpermiWedbetweendigits.
• Maximumandminimumvalues(for32-bitrepresenta7ons)Maximum::2147483647Minimum::–2147483648
FloaJng-pointConstants• Cancontainfrac7onalparts.
• Verylargeorverysmallnumberscanberepresented.23000000canberepresentedas2.3e7
• Twodifferentnota7ons:1. Decimalnota7on
25.0,0.0034,.84,-2.2342. Exponen7al(scien7fic)nota7on
3.45e23,0.123e-12,123E2 e means “10 to the power of”
SingleCharacterConstants
• Containsasinglecharacterenclosedwithinapairofsinglequotemarks(‘’).– Examples::‘2’,‘+’,‘Z’
• Somespecialbackslashcharacters‘\n’ newline‘\t’ horizontaltab‘\’’ singlequote‘\”’ doublequote‘\\’ backslash‘\0’ null
StringConstants
• Sequenceofcharactersenclosedindoublequotes(““).– ThecharactersmaybeleWers,numbers,specialcharactersandblankspaces.
• Examples:“nice”,“GoodMorning”,“3+6”,“3”,“C”
• Differencesfromcharacterconstants:– ‘C’and“C”arenotequivalent.– ‘C’hasanequivalentintegervaluewhile“C”doesnot.
Variables
• Itisadatanamethatcanbeusedtostoreadatavalue.
• Unlikeconstants,avariablemaytakedifferentvaluesinmemoryduringexecu7on.
• Variablenamesfollowthenamingconven7onforiden7fiers.– Examples::temp,speed,name2,current
Example int a, b, c; char x; a = 3; b = 50; c = a – b; x = ‘d’; b = 20; a = a + 1; x = ‘G’;
Variables
Constants
DeclaraJonofVariables
• Therearetwopurposes:1. Ittellsthecompilerwhatthevariablenameis.2. Itspecifieswhattypeofdatathevariablewillhold.
• Generalsyntax:data-typevariable-list;
• Examples:intvelocity,distance;inta,b,c,d;floattemp;charflag,op7on;
AddressandContent
1349
1350
1351
1352
speed
11101010
int speed;
speed=234;
speed 234 &speed 1350
Binaryof234
Everyvariablehasanaddress(inmemory),anditscontents.
AddressandContent
• InCterminology,inanexpressionspeedreferstothecontentsofthememoryloca7on.
&speedreferstotheaddressofthememoryloca7on.
• Examples:printf (“%f %f %f”, speed, time, distance); scanf (“%f %f”, &speed, &time);
AnExample
#include <stdio.h> int main() { float speed, time, distance; scanf (“%f %f”, &speed, &time); distance = speed * time; printf (“\n The distance traversed is: \n”, distance); return 0; }
Address of speed
Content of speed
AssignmentStatement
• Usedtoassignvaluestovariables,usingtheassignmentoperator(=).
• Generalsyntax:variable_name = expression;
• Examples:velocity = 20; b = 15; temp = 12.5; A = A + 10; v = u + f * t; s = u * t + 0.5 * f * t * t;
AdvancedAssignmentStatement
• Assignmentduringdeclara7onint speed = 30; char flag = ‘y’;
• Mul7plevariableassignmenta = b = c = 5; flag1 = flag2 = ‘y’;
speed = flow = 20.0;
OperatorsinExpressions
Operators
Arithmetic Operators
Relational Operators
Logical Operators
ArithmeJcOperators
• Addi7on::+• Subtrac7on::–• Division:: /• Mul7plica7on::*• Modulus:: %
X + Y 48
X – Y 2
X * Y 575
X / Y ?
X % Y ??
X=25; Y=23;
OperatorPrecedence
• Indecreasingorderofpriority1. Parentheses::()2. Unaryminus::–53. Mul7plica7on,Division,andModulus4. Addi7onandSubtrac7on
• Foroperatorsofthesamepriority,evalua7onisfromleYtorightastheyappear.
• Parenthesismaybeusedtochangetheprecedenceofoperatorevalua7on.
Examples:ArithmeJcexpressions
v = u + f * t; è X = x * y / z è A = a + b – c * d / e èA = -b * c + d % e è
Examples:ArithmeJcexpressions
v = u + f * t; è v=u+(f*t);X = x * y / z è X=(x*y)/zA = a + b – c * d / e èA=((a+b)-((c*d)/e))A = -b * c + d % e èA=(((-b)*c)+(d%e))
IntegerArithmeJc
• Whentheoperandsinanarithme7cexpressionareintegers,theexpressioniscalledintegerexpression,andtheopera7oniscalledintegerarithme@c.
• Integerarithme7calwaysyieldsintegervalues.
RealArithmeJc
• Involvingonlyrealorfloa7ng-pointoperands(includingdouble,longdouble).
• Sincefloa7ng-pointvaluesareroundedtothenumberofsignificantdigitspermissible,thefinalvalueisanapproxima7onofthefinalresult. A=22/7*7*7=(((22/7)*7)*7)=153.86 =(((22*7)/7)*7)=154
• Themodulusoperatorcannotbeusedwithrealoperands.
ArithmeJc–integer/real
• AnexpressioncontainsonlyintegeroperandsèIntegerarithme7cwillbeperformed.
• AnexpressioncontainsonlyrealoperandsèRealarithme7cwillbeperformed.
• AnexpressioncontainsintegerandrealboththeoperandsèRealarithme7cwillbeperformed.
TypecasJng
• Afaultyreciprocalfinder
#include <stdio.h> int main () { int n; scanf("%d",&n); printf("%d\n",1/n); return 0;
}
Thedivision1/nisofintegers(quo7ent).Theformat%disforprin7ngintegers.
TypecasJng
#include <stdio.h>
int main () {
int n;
scanf("%d",&n);
printf("%f\n",1.0/n);
return 0; }
#include <stdio.h>
int main () {
int n;
float x;
scanf("%d",&n);
x=(float)1/n; printf("%f\n",x);
return 0;
}
TypecasJng
Integertorealint a=10; float b;
b=(float)a;
Realtointeger
int a; float b=3.14; a=(int)b;
Realtoreal float b; double c=3.14;
b=(float)c;
Realtoreal float b;
double c; c=22.0/7.0;
b=(float)c;