Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf ·...
Transcript of Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf ·...
ProgrammingandDataStructure
Prof.IndranilSenGupta
DepartmentofComputerScience&Engg.IndianInstituteofTechnology
Kharagpur
SomeGeneralAnnouncements
Autumn Semester2019 Programming and DataStructure 3
AbouttheCourse
• WillbeconductedwithaL-T-Pratingof3-0-0.
• LaboratorywithaL-T-Pof0-1-3.
• Evaluation inthetheorycourse:– Mid-semester 30%– End-semester 50%– Twoclasstestsandattendance 20%
Autumn Semester2019 Programming and DataStructure 4
CourseMaterials
• Theslidesforthelectureswillbemadeavailableontheweb(inPDFform).http://cse.iitkgp.ac.in/~saptarshi/
courses/pdstheory2019a/
• Allimportantannouncementswillbeputuponthewebpage.
Autumn Semester2019 Programming and DataStructure 5
ATTENDANCEINTHECLASSESISMANDATORY
Studentshavingpoorattendancewillbepenalizedintermsofthefinalgrade.
Autumn Semester2019 Programming and DataStructure 6
Text/ReferenceBooks&Notes
1. TheCProgrammingLanguage(2nd orhigheredition)Kernighan&Ritchie,Prentice-HallofIndia
2. ProgrammingwithC(2nd orhigheredition)B.S.Gottfried,Schaum’sOutlineSeries,TataMcGraw-Hill
3. ProgramminginANSIC(2nd orhigheredition)E.Balagurusamy,TataMcGraw-Hill,NewDelhi
4. DatastructuresS.Lipschutz,Schaum’sOutlineSeries,TataMcGraw-Hill
5. DatastructuresusingCandC++(2nd orhigheredition)Y.Langsam,M.J.Augenstein,A.M.Tanenbaum,Prentice-HallofIndia
6. http://cse.iitkgp.ac.in/~pds/notes/
Introduction
Autumn Semester2019 Programming and DataStructure 8
WhatisaComputer?
CentralProcessing
Unit(CPU)
InputDevice
OutputDevice
MainMemory
StoragePeripherals
It is a machine which can accept data, process them, and output results.
Autumn Semester2019 Programming and DataStructure 9
• CPU– Allcomputationstakeplacehereinorderforthecomputertoperformadesignatedtask.
– Ithasanumberofregisterswhichtemporarilystoredataandprograms(instructions).
– Ithascircuitrytocarryoutarithmeticandlogicoperations,takedecisions,etc.
– Itretrievesinstructionsfromthememory(fetch),interprets(decode)them,andperformstherequestedoperation(execute).
Autumn Semester2019 Programming and DataStructure 10
• MainMemory– Usessemiconductortechnology.– Memorysizesintherangeof4to16Gbytesaretypicaltoday.
– Somemeasurestoberemembered• 1K(kilo) =210 (=1024)• 1M(mega) =220 (=onemillionapprox.)• 1G(giga) =230 (=onebillionapprox.)• 1T(tera) =240 (=onetrillionapprox.)
Autumn Semester2019 Programming and DataStructure 11
• InputDevice– Keyboard,Mouse,Scanner
• OutputDevice– Monitor,Printer
• StoragePeripherals– MagneticDisks:harddisk,floppydisk
• Allowsdirect(semi-random)access– OpticalDisks:CDROM,CD-RW,DVD,BlueRay
• Allowsdirect(semi-random)access– FlashMemoryandSolidStateDrive
• Allowsdirectaccess– MagneticTape:DAT
• Onlysequentialaccess
Autumn Semester2019 Programming and DataStructure 12
Howdoesacomputerwork?
• Storedprogramconcept.– Maindifferencefromacalculator.
• Whatisaprogram?– Setofinstructionsforcarryingoutaspecifictask.
• Whereareprogramsstored?– Insecondarymemory,whenfirstcreated.– Broughtintomainmemory,duringexecution.
Autumn Semester2019 Programming and DataStructure 13
NumberSystem::TheBasics
• Weareaccustomedtousingtheso-calleddecimalnumbersystem.– Tendigits::0,1,2,3,4,5,6,7,8,9– Everydigitpositionhasaweightwhichisapowerof10.
• Example:234 =2x102 +3x101 +4x100
250.67=2x102 +5x101 +0x100 +6x10-1 +7x10-2
Autumn Semester2019 Programming and DataStructure 14
Contd.
• Adigitalcomputerisbuiltoutoftinyelectronicswitches.– Fromtheviewpointofeaseofmanufacturingandreliability,suchswitchescanbeinoneoftwostates,ONandOFF.
– Aswitchcanrepresentadigitintheso-calledbinarynumbersystem,0and1.
• Acomputerworksbasedonthebinarynumbersystem.
• Binarynumbersystem– Twodigits::0and1– Everydigitpositionhasaweightwhichisapowerof2.
• Example:1110=1x23 +1x22 +1x21 +0x20
=14(indecimal)
Autumn Semester2019 Programming and DataStructure 15
Autumn Semester2019 Programming and DataStructure 16
ConceptofBitsandBytes
• Bit– Asinglebinarydigit(0or1).
• Nibble– Acollectionoffourbits(say,0110).
• Byte– Acollectionofeightbits(say,01000111).
• Word– Dependsonthecomputer.– Typically4or8bytes(thatis,32or64bits).
Autumn Semester2019 Programming and DataStructure 17
Contd.
• Ank-digitdecimalnumber– Canexpressunsignedintegersintherange0to10k – 1.
• Fork=3,from0to999.
• Ank-bitbinarynumber– Canexpressunsignedintegersintherange0to2k – 1.
• Fork=8,from0to255.• Fork=10,from0to1023.
Autumn Semester2019 Programming and DataStructure 18
ClassificationofSoftware
• Twocategories:1. ApplicationSoftware
• Usedtosolveaparticularproblem.• Editor,financialaccounting,weatherforecasting,
mathematicaltoolbox,etc.
2. SystemSoftware• Helpsinrunningotherprograms.• Compiler,operatingsystem,etc.
Autumn Semester2019 Programming and DataStructure 19
ComputerLanguages
• MachineLanguage– Expressedinbinary.
• 10110100maymeanADD,01100101maymeanSUB,etc.
– Directlyunderstoodbythecomputer.
– Notportable;variesfromonemachinetypetoanother.• Programwrittenforonetypeofmachinewillnotrunonanothertypeofmachine.
– Difficulttouseinwritingprograms.
Autumn Semester2019 Programming and DataStructure 20
Contd.
• AssemblyLanguage– Mnemonicformofmachine language.
– Easiertouseascomparedtomachine language.• Forexample,use“ADD” insteadof“10110100”.
– Notportable(likemachinelanguage).
– Requiresatranslatorprogramcalledassembler.
AssemblerAssemblylanguageprogram
Machinelanguageprogram
Autumn Semester2019 Programming and DataStructure 21
Contd.
• Assemblylanguageisalsodifficulttouseinwritingprograms.– Requiresmanyinstructionstosolveaproblem.
• Example:Findtheaverageofthreenumbers.MOV A,X ;A=XADD A,Y ;A=A+YADD A,Z ;A=A+ZDIV A,3 ;A=A/3MOV RES,A ;RES=A
In C,
RES = (X + Y + Z) / 3
Autumn Semester2019 Programming and DataStructure 22
High-LevelLanguage
• Machinelanguageandassemblylanguagearecalledlow-levellanguages.– Theyareclosertothemachine.– Difficulttouse.
• High-levellanguagesareeasiertouse.– Theyareclosertotheprogrammer.– Examples:
• Fortran,C,C++,Java,Python.
– Requiresanelaborateprocessoftranslation.• Usingasoftwarecalledcompiler.
– Theyareportableacrossplatforms.
Autumn Semester2019 Programming and DataStructure 23
Compiler Objectcode Linker
Library
HLLprogram
Executablecode
gcccompilerwillbeusedinthelabclasses
Autumn Semester2019 Programming and DataStructure 24
OperatingSystems
• Makesthecomputereasytouse.– Basicallythecomputerisverydifficulttouse.– Understandsonlymachinelanguage.
• Operatingsystemsmakesthetaskoftheuserseasier.
• Categoriesofoperatingsystems:– Singleuser– Multiuser(Timesharing,Multitasking,Realtime)
Autumn Semester2019 Programming and DataStructure 25
Contd.
• Popularoperatingsystems:– Windows: single-usermultitasking– Unix: multi-user– Linux: afreeversionofUnix
• ThelaboratoryclasseswillbebasedonLinux.
Autumn Semester2019 Programming and DataStructure 26
Contd.
• Question:– Howmanyuserscanworkonthesamecomputer?
• Computersconnectedinanetwork.
• Manyusersmayworkonacomputer.– Overthenetwork.– Atthesametime.– CPUandotherresourcesaresharedamongthedifferentprograms.• Calledtimesharing.• Oneprogramexecutesatatime.
BasicProgrammingConcepts
Autumn Semester2019 Programming and DataStructure 28
SomeTerminologies
• Algorithm/Flowchart/Pseudo-code– Astep-by-stepprocedureforsolvingaparticularproblem.
– Shouldbeindependentoftheprogramminglanguage.
• Program– Atranslationofthealgorithm/flowchart intoaformthatcanbeprocessedbyacomputer.
– Typicallywritteninahigh-levellanguagelikeC,C++,Java,etc.
FirstLookataCProgram
/* Program to compute the area of a circle */#include <stdio.h> /* Compulsory, for library files */
main() /* Function heading */{
float radius, area; /* Declare variables */scanf (ʺ%fʺ, &radius); /* Read radius */area = 3.14159 * radius * radius;printf (ʺArea = %fʺ, area); /* Output to screen */
}
Autumn Semester2019 Programming and DataStructure 29
Input: 10Output: Area = 314.158997
Autumn Semester2019 Programming and DataStructure 30
VariablesandConstants
• Mostimportantconceptforproblemsolvingusingcomputers.
• Alltemporaryresultsarestoredintermsofvariablesandconstants.– Thevalueofavariablecanbechanged.– Thevalueofaconstantdonotchange.
• Wherearetheystored?– Inmainmemory.
Autumn Semester2019 Programming and DataStructure 31
Contd.
• Howdoesmemorylooklike(logically)?– Asalistofstoragelocations,eachhavingauniqueaddress.
– Variablesandconstantsarestoredinthesestoragelocations.
– Variableislikeahouse,andthenameofavariableisliketheaddress ofthehouse.• Differentpeoplemayresideinthehouse,whichislikethecontents ofavariable.
Autumn Semester2019 Programming and DataStructure 32
Memorymap
Address0Address1Address2Address3Address4Address5Address6
AddressN-1
Everyvariableismappedtoaparticularmemoryaddress
Autumn Semester2019 Programming and DataStructure 33
VariablesinMemory
10
20
21
105
MemorylocationallocatedtoavariableX
X=10
X=20
X=X+1
X=X*5
Instructionexecuted
Time
Autumn Semester2019 Programming and DataStructure 34
VariablesinMemory(contd.)
20
20
18
18
Variable
XY
X=20
Y=15
X=Y+3
Y=X/6
Instructionexecuted
?
15
15
3
Time
Datatypes
• Threecommondatatypesused:– Integer ::canstoreonlywholenumbers
Examples:25,-56,1,0
– Floating-point ::canstorenumberswithfractionalvalues.Examples:3.14159,-12345.345,2.65E12,2.35E-25
– Character ::canstoreasinglecharacterExamples:‘A’,‘a’,‘*’,‘3’,‘ ’,‘+’
Autumn Semester2019 Programming and DataStructure 35
DataTypes(contd.)
• Howaretheystoredinmemory?– Integer::
• 16bits• 32bits
– Float::• 32bits• 64bits
– Char::• 8bits(ASCIIcode)• 16bits(UNICODE,usedinJava)
Autumn Semester2019 Programming and DataStructure 36
Actualnumberofbitsvariesfromonecomputertoanother
Autumn Semester2019 Programming and DataStructure 37
Problemsolving(TypicalFlow)
• Step1:– Clearlyspecifytheproblemtobesolved.
• Step2:– Drawflowchartorwritealgorithm.
• Step3:– Convertflowchart(algorithm)intoprogramcode.
• Step4:– Compiletheprogramintoobjectcode.
• Step5:– Executetheprogram.
Autumn Semester2019 Programming and DataStructure 38
Flowchart:basicsymbols
Computation
Input / Output
Decision Box
Start / Stop
Autumn Semester2019 Programming and DataStructure 39
Contd.
Flow of control
Connector
Autumn Semester2019 Programming and DataStructure 40
Example1:Adding threenumbers
READA,B,C
S=A+B+C
OUTPUTS
STOP
START
Autumn Semester2019 Programming and DataStructure 41
Example2:Largeroftwonumbers
START
STOP
READX,Y
OUTPUTY
ISX>Y?
OUTPUTX
STOP
YES NO
Autumn Semester2019 Programming and DataStructure 42
Example3:Largestofthreenumbers
START
READX,Y,Z
ISLAR>Z?
ISX>Y?
LAR=X LAR=Y
OUTPUTLAR OUTPUTZ
STOP STOP
YES
YES
NO
NO
Autumn Semester2019 Programming and DataStructure 43
Example4:SumoffirstNnaturalnumbers
START
READN
SUM=0COUNT=1
SUM=SUM+COUNT
COUNT=COUNT+1
ISCOUNT>N? OUTPUTSUM
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 44
Example5:SUM=12 +22 +32 +N2
START
READN
SUM=0COUNT=1
SUM=SUM+COUNT*COUNT
COUNT=COUNT+1
ISCOUNT>N? OUTPUTSUM
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 45
Example6:SUM=1.2+2.3+3.4+toNterms
START
READN
SUM=0COUNT=1
SUM=SUM+COUNT*(COUNT+1)
COUNT=COUNT+1
ISCOUNT>N? OUTPUTSUM
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 46
Example7:ComputingFactorial
START
READN
PROD=1COUNT=1
PROD=PROD*COUNT
COUNT=COUNT+1
ISCOUNT>N? OUTPUTPROD
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 47
Example8:Computingex seriesuptoNterms
START
READX, N
TERM=1SUM=0
COUNT=1
SUM=SUM+TERMTERM=TERM*X/COUNT
COUNT=COUNT+1
ISCOUNT>N? OUTPUTSUM
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 48
Example9:Computingex seriesupto4decimalplaces
START
READX
TERM=1SUM=0
COUNT=1
SUM=SUM+TERMTERM=TERM*X/COUNT
COUNT=COUNT+1
ISTERM<0.0001? OUTPUTSUM
STOP
YESNO
Autumn Semester2019 Programming and DataStructure 49
Example10:Rootsofaquadraticequation
ax2 +bx+c=0
TRYYOURSELF
Autumn Semester2019 Programming and DataStructure 50
Example11:Gradecomputation
MARKS≥ 90è Ex89≥MARKS≥ 80è A79≥MARKS≥ 70è B69≥MARKS≥ 60è C59≥MARKS≥ 50è D49≥MARKS≥ 35è P34≥MARKSè F
Autumn Semester2019 Programming and DataStructure 51
GradeComputation (contd.)
START
READMARKS
OUTPUT“Ex”
MARKS≥ 90? MARKS≥ 80? MARKS≥ 70?
OUTPUT“A” OUTPUT“B”
STOPSTOPSTOP
A
YESYESYES
NONONO
Autumn Semester2019 Programming and DataStructure 52
MARKS≥ 60?
STOP
OUTPUT“C”
A MARKS≥ 50? MARKS≥ 35?
OUTPUT“D” OUTPUT“P” OUTPUT“F”
STOP STOP STOP
YESYESYES
NONONO
ProgramminginC
Autumn Semester2019 Programming and DataStructure 54
SampleCprogram#1
#include <stdio.h>main()
{printf (ʺ\n Our first look at a C program \nʺ);
}
Autumn Semester2019 Programming and DataStructure 55
SampleCprogram#2
/* Compute the sum of two integers */
#include <stdio.h>main()
{int a, b, c;a = 10;b = 20;c = a + b;printf (ʺ\n The sum of %d and %d is %d\nʺ, a,b,c);
}
Autumn Semester2019 Programming and DataStructure 56
SampleCprogram#3
#include <stdio.h>
/* FIND THE LARGEST OF THREE NUMBERS */
main(){
int a, b, c;scanf (ʺ%d %d %dʺ, &a, &b, &c);if ((a>b) && (a>c)) /* Composite condition check */
printf (ʺ\n Largest is %dʺ, a);else
if (b>c) /* Simple condition check */printf (ʺ\n Largest is %dʺ, b);
elseprintf (ʺ\n Largest is %dʺ, c);
}
SampleCprogram#4
Autumn Semester2019 Programming and DataStructure 57
#include <stdio.h>#define PI 3.1415926
/* Compute the area of a circle */main()
{float radius, area;float myfunc (float radius);
scanf (ʺ%fʺ, &radius);area = myfunc (radius);printf (ʺ\n Area is %f \nʺ, area);
}
float myfunc (float r){
float a;a = PI * r * r;return (a); /* return result */
}
Autumn Semester2019 Programming and DataStructure 58
IntroductiontoC
• Cisageneral-purpose,structuredprogramming language.– Alsocontainsadditionalfeatureswhichallowittobeusedatalower
level.
• Ccanbeusedforapplications programmingaswellasforsystemsprogramming.
• Thereareonly32keywordsanditsstrengthliesinitsbuilt-infunctions.
• Cishighlyportable,sinceitrelegatedmuchcomputer-dependentfeaturestoitslibraryfunctions.
Autumn Semester2019 Programming and DataStructure 59
HistoryofC
• Originallydevelopedinthe1970’sbyDennisRitchieatAT&TBellLaboratories.
• Popularitybecamewidespreadbythemid1980’s,withtheavailabilityofcompilersforvariousplatforms.
• StandardizationhasbeencarriedouttomakethevariousCimplementationscompatible.– AmericanNationalStandards Institute(ANSI)– GNU
Autumn Semester2019 Programming and DataStructure 60
StructureofaCprogram
• EveryCprogramconsistsofoneormorefunctions.– Oneofthefunctionsmustbecalledmain.– Theprogramwillalwaysbeginbyexecutingthemainfunction.
• Eachfunctionmustcontain:– Afunctionheading,whichconsistsofthefunctionname,followedbyanoptionallistofarguments enclosedinparentheses.
– Alistofargumentdeclarations.– Acompoundstatement,whichcomprisestheremainderofthefunction.
Autumn Semester2019 Programming and DataStructure 61
Contd.
• Eachcompoundstatementisenclosedwithinapairofbraces:‘{‘ and‘}’– Thebracesmaycontaincombinations ofelementarystatementsandothercompoundstatements.
• Commentsmayappearanywhereinaprogram,enclosedwithindelimiters‘/*’ and‘*/’.– Example:
a=b+c;/*ADDTWONUMBERS*/
Autumn Semester2019 Programming and DataStructure 62
ExampleofaFunction
/* Compute the sum of two integers */// You can also give comments like this
#include <stdio.h>main()
{int a, b, c;
a = 10;b = 20;c = a + b;printf (ʺ\n The sum of %d and %d is %d\nʺ, a,b,c);
}
Autumn Semester2019 Programming and DataStructure 63
DesirableProgrammingStyle
• Clarity– Theprogramshouldbeclearlywritten.– Itshouldbeeasytofollowtheprogramlogic.
• Meaningfulvariablenames– Makevariable/constantnamesmeaningfultoenhanceprogram
clarity.• ‘area’ insteadof‘a’• ‘radius’ insteadof‘r’
• Programdocumentation– Insertcommentsintheprogramtomakeiteasytounderstand.– Neverusetoomanycomments.
Autumn Semester2019 Programming and DataStructure 64
Contd.
• Programindentation– Useproperindentation.– Structureoftheprogramshouldbeimmediatelyvisible.
Autumn Semester2019 Programming and DataStructure 65
IndentationExample#1::GoodStyle
#include <stdio.h>#define PI 3.1415926/* Compute the area of a circle */
main(){
float radius, area;float myfunc (float radius);
scanf (ʺ%fʺ, &radius);area = myfunc (radius);printf (ʺ\n Area is %f \nʺ, area);
}
float myfunc (float r){
float a;a = PI * r * r;return (a);
/* return result */}
Autumn Semester2019 Programming and DataStructure 66
IndentationExample#1::BadStyle
#include <stdio.h>#define PI 3.1415926/* Compute the area of a circle */main(){float radius, area;float myfunc (float radius);scanf (ʺ%fʺ, &radius);area = myfunc (radius);printf (ʺ\n Area is %f \nʺ, area);}
float myfunc (float r){float a;a = PI * r * r;return (a);
/* return result */}
Autumn Semester2019 Programming and DataStructure 67
IndentationExample#2::GoodStyle
#include <stdio.h>
/* FIND THE LARGEST OF THREE NUMBERS */
main(){
int a, b, c;scanf (ʺ%d %d %dʺ, &a, &b, &c);if ((a>b) && (a>c)) /* Composite condition check */
printf (ʺ\n Largest is %dʺ, a);else
if (b>c) /* Simple condition check */printf (ʺ\n Largest is %dʺ, b);
elseprintf (ʺ\n Largest is %dʺ, c);
}
Autumn Semester2019 Programming and DataStructure 68
IndentationExample#2::BadStyle
#include <stdio.h>/* FIND THE LARGEST OF THREE NUMBERS */main(){int a, b, c;scanf (ʺ%d %d %dʺ, &a, &b, &c);if ((a>b) && (a>c))/* Composite condition check */printf (ʺ\n Largest is %dʺ, a);elseif (b>c)/* Simple condition check */printf (ʺ\n Largest is %dʺ, b);elseprintf (ʺ\n Largest is %dʺ, c);}
Autumn Semester2019 Programming and DataStructure 69
TheCCharacterSet
• TheClanguagealphabet:– Uppercaseletters‘A’ to‘Z’– Lowercaseletters‘a’ to‘z’– Digits‘0’ to‘9’– Certainspecialcharacters:
! # % ^ & * ( )
- _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ? blank
Autumn Semester2019 Programming and DataStructure 70
IdentifiersandKeywords
• Identifiers– Namesgiventovariousprogramelements(variables,constants, functions,etc.)
– Mayconsistofletters,digits andtheunderscore (‘_’)character,withnospacebetween.
– Firstcharactermustbealetter.– Anidentifiercanbearbitrarylong.
• SomeCcompilersrecognizeonlythefirstfewcharactersofthename(16or31).
– Casesensitive• ‘area’,‘AREA’ and‘Area’ arealldifferent.
Autumn Semester2019 Programming and DataStructure 71
Contd.
• Keywords– Reservedwordsthathavestandard,predefinedmeaningsinC.
– Cannotbeusedasidentifiers.– 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
Autumn Semester2019 Programming and DataStructure 72
ValidandInvalidIdentifiers
• ValididentifiersXabcsimple_interesta123LISTstud_nameEmpl_1Empl_2avg_empl_salary
• Invalididentifiers10abcmy-nameʺhelloʺsimple interest(area)%ratedoublefor
Autumn Semester2019 Programming and DataStructure
DataTypesinC
int ::integerquantityTypicallyoccupies4bytes(32bits)inmemory.
char ::singlecharacterTypicallyoccupies1byte(8bits)inmemory.
float ::floating-pointnumber(anumberwithadecimalpoint)
Typicallyoccupies4bytes(32bits)inmemory.
double ::double-precisionfloating-pointnumberTypicallyoccupies8bytes(64bits)inmemory.
73
Autumn Semester2019 Programming and DataStructure 74
Contd.
• Someofthebasicdatatypescanbeaugmentedbyusingcertaindatatypequalifiers:– short– long– signed– unsigned
• Examples:short int flag;long int result;unsigned int count, age;
Autumn Semester2019 Programming and DataStructure 75
SomeExamplesofDataTypes
• int0,25,–156,12345,–99820
• char‘a’,‘A’,‘*’,‘/’,‘ ’
• float23.54,–0.00345,25.02.5E12,1.234e–5
Eoremeans“10tothepowerof”
Autumn Semester2019 Programming and DataStructure 76
Constants
Constants
NumericConstants
CharacterConstants
stringsinglecharacter
floating-pointinteger
Autumn Semester2019 Programming and DataStructure 77
IntegerConstants
• Consistsofasequenceofdigits,withpossiblyaplusoraminussignbeforeit.– Embeddedspaces,commasandnon-digitcharactersarenotpermittedbetweendigits.
• Maximumandminimumvalues(for32-bitrepresentations)
Maximum::+2147483647(231 – 1)Minimum::– 2147483648(– 231)
<For2’scomplementrepresentation>
Autumn Semester2019 Programming and DataStructure 78
Floating-pointConstants
• Cancontainfractionalparts.• Verylargeorverysmallnumberscanberepresented.
23000000canberepresentedas2.3e7
• Twodifferentnotations:1. Decimalnotation
25.0,0.0034,.84,-2.234
2. Exponential (scientific)notation3.45e23,0.123e-12,123E2 emeans“10tothe
powerof”
Autumn Semester2019 Programming and DataStructure 79
SingleCharacterConstants
• Containsasinglecharacterenclosedwithinapairofsinglequotemarks.– Examples::‘2’,‘+’,‘Z’
• Somespecialbackslashcharacters‘\n’ newline‘\t’ horizontaltab‘\’’ singlequote‘\”’ doublequote‘\\’ backslash‘\0’ null
Autumn Semester2019 Programming and DataStructure 80
StringConstants
• Sequenceofcharactersenclosedindoublequotes.– Thecharactersmaybeletters,numbers,specialcharactersandblankspaces.
• Examples:“nice”,“GoodMorning”,“3+6”,“3”,“C”
• Differencesfromcharacterconstants:– ‘C’ and“C” arenotequivalent.– ‘C’ hasanequivalentintegervaluewhile“C” doesnot.
Autumn Semester2019 Programming and DataStructure 81
Variables
• Itisadatanamethatcanbeusedtostoreadatavalue.
• Unlikeconstants,avariablemaytakedifferentvaluesinmemoryduringexecution.
• Variablenamesfollowthesamenamingconventionforidentifiers.
Examples ::temp,speed,name2,current,my_salary
Autumn Semester2019 Programming and DataStructure 82
Example
int a, b, c;char x;
a = 3;b = 50;c = a – b;x = ‘d’;
b = 20;a = a + 1;x = ‘G’;
Autumn Semester2019 Programming and DataStructure 83
DeclarationofVariables
• Therearetwopurposes:– Ittellsthecompilerwhatthevariablenameis.– Itspecifieswhattypeofdatathevariablewillhold.
• Generalsyntax:data-typevariable-list;
• Examples:int velocity, distance;int a, b, c, d;float temp;char flag, option;
Autumn Semester2019 Programming and DataStructure 84
AFirstLookatPointers
• Avariableisassignedaspecificmemorylocation.– Forexample,avariablespeed isassignedmemorylocation1350.
– Alsoassumethatthememorylocationcontainsthedatavalue100.
– Whenweusethenamespeed inanexpression,itreferstothevalue100 storedinthememorylocation.
distance = speed * time;
• Thuseveryvariablehasanaddress inmemory,anditscontents.
Autumn Semester2019 Programming and DataStructure 85
Contd.
• InCterminology,inanexpressionspeed referstothecontents ofthememorylocation.&speedreferstotheaddress ofthememorylocation.
• Examples:printf (ʺ%f %f %fʺ, speed, time, distance);scanf (ʺ%f %fʺ, &speed, &time);
Autumn Semester2019 Programming and DataStructure 86
AnExample
#include <stdio.h>main()
{float speed, time, distance;
scanf (ʺ%f %fʺ, &speed, &time);distance = speed * time;printf (ʺ\n The distance traversed is: %f \nʺ,
distance);}
Autumn Semester2019 Programming and DataStructure 87
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;
Autumn Semester2019 Programming and DataStructure 88
Contd.
• Avaluecanalsobeassignedtoavariableatthetimethevariableisdeclared.
int speed = 30;char flag = ‘y’;
• Severalvariablescanbeassignedthesamevalueusingmultipleassignmentoperators.
a = b = c = 5;flag1 = flag2 = ‘y’;speed = flow = 0.0;
Autumn Semester2019 Programming and DataStructure 89
OperatorsinExpressions
Operators
ArithmeticOperators
RelationalOperators
LogicalOperators
Autumn Semester2019 Programming and DataStructure 90
ArithmeticOperators
• Addition:: +• Subtraction:: –• Division:: /• Multiplication:: *• Modulus:: %
Autumn Semester2019 Programming and DataStructure 91
Examples
distance = rate * time ;
netIncome = income - tax ;
speed = distance / time ;
area = PI * radius * radius;
y = a * x * x + b*x + c;
quotient = dividend / divisor;
remain = dividend % divisor;
Autumn Semester2019 Programming and DataStructure 92
Contd.
• Supposex andy aretwointegervariables,whosevaluesare13 and5 respectively.
x + y 18
x – y 8
x * y 65
x / y 2
x % y 3
Autumn Semester2019 Programming and DataStructure 93
OperatorPrecedence
• Indecreasingorderofpriority1. Parentheses::()2. Unaryminus::–53. Multiplication,Division,andModulus4. AdditionandSubtraction
• Foroperatorsofthesamepriority,evaluationisfromlefttoright astheyappear.
• Parenthesismaybeusedtochangetheprecedenceofoperatorevaluation.
Autumn Semester2019 Programming and DataStructure 94
Examples:Arithmeticexpressions
a+b*c– d/e è a+(b*c)– (d/e)
a*– b+d%e– f è a*(– b)+(d%e)– f
a– b+c+d è (((a– b)+c)+d)
x*y*z è ((x*y)*z)
a+b+c*d*e è (a+b)+((c*d)*e)
Autumn Semester2019 Programming and DataStructure 95
IntegerArithmetic
• Whentheoperandsinanarithmeticexpressionareintegers,theexpressioniscalledintegerexpression,andtheoperationiscalledintegerarithmetic.
• Integerarithmeticalwaysyieldsintegervalues.
• Examples:(12 + 3) / 6 gives the value 2(2 / 3) * 3 gives the value 0(12 * 3) / 7 + 3 * 2 gives the value 11
Autumn Semester2019 Programming and DataStructure 96
RealArithmetic
• Arithmeticoperationsinvolvingonlyrealorfloating-pointoperands.
• Sincefloating-pointvaluesareroundedtothenumberofsignificantdigitspermissible,thefinalvalueisanapproximationofthefinalresult.
1.0/3.0*3.0willhavethevalue0.99999 andnot1.0
• Themodulusoperatorcannotbeusedwithrealoperands.
Autumn Semester2019 Programming and DataStructure 97
Mixed-modeArithmetic
• Whenoneoftheoperandsisintegerandtheotherisreal,theexpressioniscalledamixed-mode arithmeticexpression.
• Ifeitheroperandisoftherealtype,thenonlyrealarithmeticisperformed,andtheresultisarealnumber.
25 / 10 gives the value 225 / 10.0 gives the value 2.5
• Somemoreissueswillbeconsideredlater.
Autumn Semester2019 Programming and DataStructure 98
TypeCasting
• Temporarilyconvertthetypeofavariablebeforebeingusedinanexpression.– Expressedbyspecifyingthedesired typeinparenthesisbeforethevariable/expression.
• Examples:int a = 10, b = 4, c; float x, y;x = (float) a / b; /* x will be 2.5 */y = (float) (a / b); /* y will be 2.0 */c = (int) x * 4; /* c will be 8 */a = (int) (x * 4); /* a will be 10 */
Autumn Semester2019 Programming and DataStructure 99
RelationalOperators
• Usedtocomparetwoquantities.
• Theresultofcomparison is“true” or“false”.– Thevalue0isconsideredas“false”,andanynon-zerovalueas“true”.
< is less than> is greater than<= is less than or equal to>= is greater than or equal to== is equal to!= is not equal to
Autumn Semester2019 Programming and DataStructure 100
Examples
10 > 20 is false25 < 35.5 is true12 > (7 + 5) is false
• Whenarithmeticexpressionsareusedoneithersideofarelationaloperator,thearithmeticexpressionswillbeevaluatedfirstandthentheresultscompared.
a + b > c – d is the same as (a+b) > (c+d)
Autumn Semester2019 Programming and DataStructure 101
Examples
• SamplecodesegmentinC:
if (x > y)printf (ʺ%d is larger\nʺ, x);
elseprintf (ʺ%d is larger\nʺ, y);
if (1) /* will be always true */…………
Autumn Semester2019 Programming and DataStructure 102
LogicalOperators
• TherearetwologicaloperatorsinC(alsocalledlogicalconnectives).
&&è LogicalAND||è LogicalOR
• Whattheydo?– Theyactuponoperandsthatarethemselveslogicalexpressions.
– Theindividual logicalexpressionsgetcombined intomorecomplexconditionsthataretrue orfalse.
Autumn Semester2019 Programming and DataStructure 103
– LogicalAND• Resultistrueifboththeoperandsaretrue.
– LogicalOR• Resultistrueifatleastoneoftheoperandsaretrue.
X Y X&&Y X||Y
FALSE FALSE FALSE FALSE
FALSE TRUE FALSE TRUE
TRUE FALSE FALSE TRUE
TRUE TRUE TRUE TRUE
• Examples:
if ((i > 2) && (i < 10))printf (ʺ\n i lies between 3 and 9ʺ);
if ((flag == ’A’) || (flag == ’a’)printf (ʺ\n Either lower or uppercase Aʺ);
Autumn Semester2019 Programming and DataStructure 104
Autumn Semester2019 Programming and DataStructure 105
Input/Output
• printf– Performsoutputtothestandardoutputdevice(typicallydefinedtobethescreen).
– Itrequiresaformatstringinwhichwecanspecify:• Thetexttobeprintedout.• Specificationsonhowtoprintthevalues.
printf(ʺThenumberis%d.\nʺ,num);• Theformatspecification%d causesthevaluelistedaftertheformatstringtobeembeddedintheoutputasadecimalnumberinplaceof%d.
• Outputwillappearas:Thenumberis125.
Autumn Semester2019 Programming and DataStructure 106
• scanf– Performsinputfromthestandardinputdevice,whichisthekeyboardbydefault.
– Itrequiresaformatstringandalistofvariablesintowhichthevaluereceivedfromtheinputdevicewillbestored.
– Itisrequiredtoputanampersand(&)beforethenamesofthevariables.
scanf("%d",&size);scanf("%c",&nextchar);scanf("%f",&length);scanf(“%d%d”,&a,&b);