programming and data structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/l1-intro.pdf ·...

106
Programming and Data Structure Prof. Indranil Sen Gupta Department of Computer Science & Engg. Indian Institute of Technology Kharagpur

Upload: others

Post on 14-Mar-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

ProgrammingandDataStructure

Prof.IndranilSenGupta

DepartmentofComputerScience&Engg.IndianInstituteofTechnology

Kharagpur

Page 2: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

SomeGeneralAnnouncements

Page 3: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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%

Page 4: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 4

CourseMaterials

• Theslidesforthelectureswillbemadeavailableontheweb(inPDFform).http://cse.iitkgp.ac.in/~saptarshi/

courses/pdstheory2019a/

• Allimportantannouncementswillbeputuponthewebpage.

Page 5: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 5

ATTENDANCEINTHECLASSESISMANDATORY

Studentshavingpoorattendancewillbepenalizedintermsofthefinalgrade.

Page 6: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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/

Page 7: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Introduction

Page 8: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.

Page 9: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 9

• CPU– Allcomputationstakeplacehereinorderforthecomputertoperformadesignatedtask.

– Ithasanumberofregisterswhichtemporarilystoredataandprograms(instructions).

– Ithascircuitrytocarryoutarithmeticandlogicoperations,takedecisions,etc.

– Itretrievesinstructionsfromthememory(fetch),interprets(decode)them,andperformstherequestedoperation(execute).

Page 10: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.)

Page 11: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 12: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 12

Howdoesacomputerwork?

• Storedprogramconcept.– Maindifferencefromacalculator.

• Whatisaprogram?– Setofinstructionsforcarryingoutaspecifictask.

• Whereareprogramsstored?– Insecondarymemory,whenfirstcreated.– Broughtintomainmemory,duringexecution.

Page 13: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 14: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 14

Contd.

• Adigitalcomputerisbuiltoutoftinyelectronicswitches.– Fromtheviewpointofeaseofmanufacturingandreliability,suchswitchescanbeinoneoftwostates,ONandOFF.

– Aswitchcanrepresentadigitintheso-calledbinarynumbersystem,0and1.

• Acomputerworksbasedonthebinarynumbersystem.

Page 15: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

• Binarynumbersystem– Twodigits::0and1– Everydigitpositionhasaweightwhichisapowerof2.

• Example:1110=1x23 +1x22 +1x21 +0x20

=14(indecimal)

Autumn Semester2019 Programming and DataStructure 15

Page 16: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 16

ConceptofBitsandBytes

• Bit– Asinglebinarydigit(0or1).

• Nibble– Acollectionoffourbits(say,0110).

• Byte– Acollectionofeightbits(say,01000111).

• Word– Dependsonthecomputer.– Typically4or8bytes(thatis,32or64bits).

Page 17: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 17

Contd.

• Ank-digitdecimalnumber– Canexpressunsignedintegersintherange0to10k – 1.

• Fork=3,from0to999.

• Ank-bitbinarynumber– Canexpressunsignedintegersintherange0to2k – 1.

• Fork=8,from0to255.• Fork=10,from0to1023.

Page 18: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 18

ClassificationofSoftware

• Twocategories:1. ApplicationSoftware

• Usedtosolveaparticularproblem.• Editor,financialaccounting,weatherforecasting,

mathematicaltoolbox,etc.

2. SystemSoftware• Helpsinrunningotherprograms.• Compiler,operatingsystem,etc.

Page 19: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 19

ComputerLanguages

• MachineLanguage– Expressedinbinary.

• 10110100maymeanADD,01100101maymeanSUB,etc.

– Directlyunderstoodbythecomputer.

– Notportable;variesfromonemachinetypetoanother.• Programwrittenforonetypeofmachinewillnotrunonanothertypeofmachine.

– Difficulttouseinwritingprograms.

Page 20: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 20

Contd.

• AssemblyLanguage– Mnemonicformofmachine language.

– Easiertouseascomparedtomachine language.• Forexample,use“ADD” insteadof“10110100”.

– Notportable(likemachinelanguage).

– Requiresatranslatorprogramcalledassembler.

AssemblerAssemblylanguageprogram

Machinelanguageprogram

Page 21: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 22: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 22

High-LevelLanguage

• Machinelanguageandassemblylanguagearecalledlow-levellanguages.– Theyareclosertothemachine.– Difficulttouse.

• High-levellanguagesareeasiertouse.– Theyareclosertotheprogrammer.– Examples:

• Fortran,C,C++,Java,Python.

– Requiresanelaborateprocessoftranslation.• Usingasoftwarecalledcompiler.

– Theyareportableacrossplatforms.

Page 23: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 23

Compiler Objectcode Linker

Library

HLLprogram

Executablecode

gcccompilerwillbeusedinthelabclasses

Page 24: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 24

OperatingSystems

• Makesthecomputereasytouse.– Basicallythecomputerisverydifficulttouse.– Understandsonlymachinelanguage.

• Operatingsystemsmakesthetaskoftheuserseasier.

• Categoriesofoperatingsystems:– Singleuser– Multiuser(Timesharing,Multitasking,Realtime)

Page 25: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 25

Contd.

• Popularoperatingsystems:– Windows: single-usermultitasking– Unix: multi-user– Linux: afreeversionofUnix

• ThelaboratoryclasseswillbebasedonLinux.

Page 26: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 26

Contd.

• Question:– Howmanyuserscanworkonthesamecomputer?

• Computersconnectedinanetwork.

• Manyusersmayworkonacomputer.– Overthenetwork.– Atthesametime.– CPUandotherresourcesaresharedamongthedifferentprograms.• Calledtimesharing.• Oneprogramexecutesatatime.

Page 27: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

BasicProgrammingConcepts

Page 28: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 28

SomeTerminologies

• Algorithm/Flowchart/Pseudo-code– Astep-by-stepprocedureforsolvingaparticularproblem.

– Shouldbeindependentoftheprogramminglanguage.

• Program– Atranslationofthealgorithm/flowchart intoaformthatcanbeprocessedbyacomputer.

– Typicallywritteninahigh-levellanguagelikeC,C++,Java,etc.

Page 29: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 30: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 30

VariablesandConstants

• Mostimportantconceptforproblemsolvingusingcomputers.

• Alltemporaryresultsarestoredintermsofvariablesandconstants.– Thevalueofavariablecanbechanged.– Thevalueofaconstantdonotchange.

• Wherearetheystored?– Inmainmemory.

Page 31: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 31

Contd.

• Howdoesmemorylooklike(logically)?– Asalistofstoragelocations,eachhavingauniqueaddress.

– Variablesandconstantsarestoredinthesestoragelocations.

– Variableislikeahouse,andthenameofavariableisliketheaddress ofthehouse.• Differentpeoplemayresideinthehouse,whichislikethecontents ofavariable.

Page 32: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 32

Memorymap

Address0Address1Address2Address3Address4Address5Address6

AddressN-1

Everyvariableismappedtoaparticularmemoryaddress

Page 33: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 33

VariablesinMemory

10

20

21

105

MemorylocationallocatedtoavariableX

X=10

X=20

X=X+1

X=X*5

Instructionexecuted

Time

Page 34: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 35: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 36: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

DataTypes(contd.)

• Howaretheystoredinmemory?– Integer::

• 16bits• 32bits

– Float::• 32bits• 64bits

– Char::• 8bits(ASCIIcode)• 16bits(UNICODE,usedinJava)

Autumn Semester2019 Programming and DataStructure 36

Actualnumberofbitsvariesfromonecomputertoanother

Page 37: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 37

Problemsolving(TypicalFlow)

• Step1:– Clearlyspecifytheproblemtobesolved.

• Step2:– Drawflowchartorwritealgorithm.

• Step3:– Convertflowchart(algorithm)intoprogramcode.

• Step4:– Compiletheprogramintoobjectcode.

• Step5:– Executetheprogram.

Page 38: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 38

Flowchart:basicsymbols

Computation

Input / Output

Decision Box

Start / Stop

Page 39: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 39

Contd.

Flow of control

Connector

Page 40: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 40

Example1:Adding threenumbers

READA,B,C

S=A+B+C

OUTPUTS

STOP

START

Page 41: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 41

Example2:Largeroftwonumbers

START

STOP

READX,Y

OUTPUTY

ISX>Y?

OUTPUTX

STOP

YES NO

Page 42: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 43: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 43

Example4:SumoffirstNnaturalnumbers

START

READN

SUM=0COUNT=1

SUM=SUM+COUNT

COUNT=COUNT+1

ISCOUNT>N? OUTPUTSUM

STOP

YESNO

Page 44: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 45: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 46: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 46

Example7:ComputingFactorial

START

READN

PROD=1COUNT=1

PROD=PROD*COUNT

COUNT=COUNT+1

ISCOUNT>N? OUTPUTPROD

STOP

YESNO

Page 47: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 48: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 49: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 49

Example10:Rootsofaquadraticequation

ax2 +bx+c=0

TRYYOURSELF

Page 50: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 51: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 52: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 53: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

ProgramminginC

Page 54: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 54

SampleCprogram#1

#include <stdio.h>main()

{printf (ʺ\n Our first look at a C program \nʺ);

}

Page 55: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);

}

Page 56: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);

}

Page 57: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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 */

}

Page 58: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 58

IntroductiontoC

• Cisageneral-purpose,structuredprogramming language.– Alsocontainsadditionalfeatureswhichallowittobeusedatalower

level.

• Ccanbeusedforapplications programmingaswellasforsystemsprogramming.

• Thereareonly32keywordsanditsstrengthliesinitsbuilt-infunctions.

• Cishighlyportable,sinceitrelegatedmuchcomputer-dependentfeaturestoitslibraryfunctions.

Page 59: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 59

HistoryofC

• Originallydevelopedinthe1970’sbyDennisRitchieatAT&TBellLaboratories.

• Popularitybecamewidespreadbythemid1980’s,withtheavailabilityofcompilersforvariousplatforms.

• StandardizationhasbeencarriedouttomakethevariousCimplementationscompatible.– AmericanNationalStandards Institute(ANSI)– GNU

Page 60: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 60

StructureofaCprogram

• EveryCprogramconsistsofoneormorefunctions.– Oneofthefunctionsmustbecalledmain.– Theprogramwillalwaysbeginbyexecutingthemainfunction.

• Eachfunctionmustcontain:– Afunctionheading,whichconsistsofthefunctionname,followedbyanoptionallistofarguments enclosedinparentheses.

– Alistofargumentdeclarations.– Acompoundstatement,whichcomprisestheremainderofthefunction.

Page 61: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 61

Contd.

• Eachcompoundstatementisenclosedwithinapairofbraces:‘{‘ and‘}’– Thebracesmaycontaincombinations ofelementarystatementsandothercompoundstatements.

• Commentsmayappearanywhereinaprogram,enclosedwithindelimiters‘/*’ and‘*/’.– Example:

a=b+c;/*ADDTWONUMBERS*/

Page 62: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);

}

Page 63: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 63

DesirableProgrammingStyle

• Clarity– Theprogramshouldbeclearlywritten.– Itshouldbeeasytofollowtheprogramlogic.

• Meaningfulvariablenames– Makevariable/constantnamesmeaningfultoenhanceprogram

clarity.• ‘area’ insteadof‘a’• ‘radius’ insteadof‘r’

• Programdocumentation– Insertcommentsintheprogramtomakeiteasytounderstand.– Neverusetoomanycomments.

Page 64: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 64

Contd.

• Programindentation– Useproperindentation.– Structureoftheprogramshouldbeimmediatelyvisible.

Page 65: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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 */}

Page 66: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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 */}

Page 67: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);

}

Page 68: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);}

Page 69: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 69

TheCCharacterSet

• TheClanguagealphabet:– Uppercaseletters‘A’ to‘Z’– Lowercaseletters‘a’ to‘z’– Digits‘0’ to‘9’– Certainspecialcharacters:

! # % ^ & * ( )

- _ + = ~ [ ] \

| ; : ‘ “ { } ,

. < > / ? blank

Page 70: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.

Page 71: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 72: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 72

ValidandInvalidIdentifiers

• ValididentifiersXabcsimple_interesta123LISTstud_nameEmpl_1Empl_2avg_empl_salary

• Invalididentifiers10abcmy-nameʺhelloʺsimple interest(area)%ratedoublefor

Page 73: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 74: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 74

Contd.

• Someofthebasicdatatypescanbeaugmentedbyusingcertaindatatypequalifiers:– short– long– signed– unsigned

• Examples:short int flag;long int result;unsigned int count, age;

Page 75: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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”

Page 76: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 76

Constants

Constants

NumericConstants

CharacterConstants

stringsinglecharacter

floating-pointinteger

Page 77: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 77

IntegerConstants

• Consistsofasequenceofdigits,withpossiblyaplusoraminussignbeforeit.– Embeddedspaces,commasandnon-digitcharactersarenotpermittedbetweendigits.

• Maximumandminimumvalues(for32-bitrepresentations)

Maximum::+2147483647(231 – 1)Minimum::– 2147483648(– 231)

<For2’scomplementrepresentation>

Page 78: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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”

Page 79: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 79

SingleCharacterConstants

• Containsasinglecharacterenclosedwithinapairofsinglequotemarks.– Examples::‘2’,‘+’,‘Z’

• Somespecialbackslashcharacters‘\n’ newline‘\t’ horizontaltab‘\’’ singlequote‘\”’ doublequote‘\\’ backslash‘\0’ null

Page 80: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.

Page 81: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 81

Variables

• Itisadatanamethatcanbeusedtostoreadatavalue.

• Unlikeconstants,avariablemaytakedifferentvaluesinmemoryduringexecution.

• Variablenamesfollowthesamenamingconventionforidentifiers.

Examples ::temp,speed,name2,current,my_salary

Page 82: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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’;

Page 83: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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;

Page 84: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 84

AFirstLookatPointers

• Avariableisassignedaspecificmemorylocation.– Forexample,avariablespeed isassignedmemorylocation1350.

– Alsoassumethatthememorylocationcontainsthedatavalue100.

– Whenweusethenamespeed inanexpression,itreferstothevalue100 storedinthememorylocation.

distance = speed * time;

• Thuseveryvariablehasanaddress inmemory,anditscontents.

Page 85: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);

Page 86: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);}

Page 87: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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;

Page 88: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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;

Page 89: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 89

OperatorsinExpressions

Operators

ArithmeticOperators

RelationalOperators

LogicalOperators

Page 90: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 90

ArithmeticOperators

• Addition:: +• Subtraction:: –• Division:: /• Multiplication:: *• Modulus:: %

Page 91: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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;

Page 92: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 93: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 93

OperatorPrecedence

• Indecreasingorderofpriority1. Parentheses::()2. Unaryminus::–53. Multiplication,Division,andModulus4. AdditionandSubtraction

• Foroperatorsofthesamepriority,evaluationisfromlefttoright astheyappear.

• Parenthesismaybeusedtochangetheprecedenceofoperatorevaluation.

Page 94: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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)

Page 95: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 96: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 96

RealArithmetic

• Arithmeticoperationsinvolvingonlyrealorfloating-pointoperands.

• Sincefloating-pointvaluesareroundedtothenumberofsignificantdigitspermissible,thefinalvalueisanapproximationofthefinalresult.

1.0/3.0*3.0willhavethevalue0.99999 andnot1.0

• Themodulusoperatorcannotbeusedwithrealoperands.

Page 97: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.

Page 98: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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 */

Page 99: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 100: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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)

Page 101: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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 */…………

Page 102: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

Autumn Semester2019 Programming and DataStructure 102

LogicalOperators

• TherearetwologicaloperatorsinC(alsocalledlogicalconnectives).

&&è LogicalAND||è LogicalOR

• Whattheydo?– Theyactuponoperandsthatarethemselveslogicalexpressions.

– Theindividual logicalexpressionsgetcombined intomorecomplexconditionsthataretrue orfalse.

Page 103: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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

Page 104: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

• 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

Page 105: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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.

Page 106: Programming and Data Structurecse.iitkgp.ac.in/~saptarshi/courses/pdstheory2019a/L1-Intro.pdf · Autumn Semester 2019 Programming and Data Structure 9 • CPU – All computations

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);