61
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Teacher: Sourangshu Bha@acharya [email protected] h@p://cse.iitkgp.ac.in/~sourangshu/ Department of Computer Science and Engineering Indian InsJtute of Technology Kharagpur

CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

CS11001/CS11002ProgrammingandDataStructures

(PDS)(Theory:3-0-0)

Teacher:SourangshuBha@[email protected]

h@p://cse.iitkgp.ac.in/~sourangshu/

DepartmentofComputerScienceandEngineeringIndianInsJtuteofTechnologyKharagpur

Page 2: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

RelaJonalOperators

•  Usedtocomparetwoquan11es.

< 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 3: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

RelaJonalOperatorsint x = 20; int y = 3;

float a=20.3;

if ( x > y ) /* 20 > 3 è True */

printf (“%d is larger\n”, x);

if ( x + x > y * 6 ) /* 20+20 > 3*6 è (20+20)>(3*6) è True */

printf(“Double of %d is larger than 6 times %d”,x,y);

if ( x > a ) /* Type cast??? */

printf(“%d is larger than %f”,x, a);

else

printf(“%d is smaller than %f”,x, a);

Page 4: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

LogicalOperators•  UnaryandBinaryOperators

!èLogicalNOT,logicalnega1on(TrueiftheoperandisFalse.)&&èLogicalAND(TrueifboththeoperandsareTrue.)||èLogicalOR(TrueifeitheroneoftheoperandsisTrue.)

X Y X&&Y X||Y

FALSE FALSE FALSE FALSE

FALSE TRUE FALSE TRUE

TRUE FALSE FALSE TRUE

TRUE TRUE TRUE TRUE

int x = 20; int y=3;float a=20.3;

if((x>y) && (x>a)) /* FALSE */ printf(“X is largest.”);

if((x>y) || (x>a)) /* TRUE */

printf(“X is not smallest.”); if(!(x==y)) /* TRUE */

printf(“X is not same as Y.”); if(x!=y) /* TRUE */

printf(“X is not same as Y.”);

X !X

FALSE TRUE

TRUE FALSE

Page 5: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

ControlStatements

Branching Looping

StatementtakesmorethanonebranchesbaseduponacondiJontestcomprisingofrela1onaland/orlogical(maybearithme1c)operators.

SomesetofstatementsarebeingexecutediteraJvelyun1lacondiJontestcomprisingofrela1onaland/orlogical(maybearithme1c)operatorsarenotbeingsa1sfied.

ControlStatements

Page 6: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

CondiJons

•  Usingrela1onaloperators.– Fourrela1onoperators: <,<=,>,>=– Twoequalityopera1ons: ==,!=

•  Usinglogicaloperators/connec1ves.– Twologicalconnec1ves: &&,||– Unarynega1onoperator: !

Page 7: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

CondiJonTests

if(count <= 100) /* Relational */

if((math+phys+chem)/3 >= 60) /* Arithmetic, Relational */ if((sex==‘M’) && (age>=21)) /* Relational, Logical */

if((marks>=80) && (marks<90) ) /* Relational, Logical */

if((balance>5000) | | (no_of_trans>25)) /* Relational, Logical */

if(! (grade==‘A’)) /* Relational, Logical */

CondiJonEvaluaJon

True(Non-zero,preferably1)

False(Zero)

Page 8: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

OperatorconfusionEquality(==)andAssignment(=)Operators

•  Whatisexpectedincondi1on?

–  Nonzerovaluesaretrue,zerovaluesarefalse–  Anyexpressionthatproducesavaluecanbeusedincontrolstructures

int age=20;

if ( age > 18 ) /* Logical Operator; Evaluated as TRUE */ printf( "You are not a minor!\n" );

if ( age >= 18 ) /* Logical Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age == 20 ) /* Logical Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age = 18 ) /* Arithmetic Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age = 17 ) /* Arithmetic Operator; Evaluated as TRUE */ printf( "You are a minor!\n" );

Page 9: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Be@erisavoid.

Thesestatementsarenotlogicallycorrect!!!

Therewillbenosyntaxerror.

Valueofagewillbe18

Valueofagewillbe17

OperatorconfusionEquality(==)andAssignment(=)Operators

int age=20;

if ( age > 18 ) /* Logical Operator; Evaluated as TRUE */ printf( "You are not a minor!\n" );

if ( age >= 18 ) /* Logical Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age == 20 ) /* Logical Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age = 18 ) /* Arithmetic Operator; Evaluated as TRUE */

printf( "You are not a minor!\n" ); if ( age = 17 ) /* Arithmetic Operator; Evaluated as TRUE */ printf( "You are a minor!\n" );

Page 10: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Equality(==)andAssignment(=)Operators

#include <stdio.h> int main() {

int x,y; scanf(“%d”,&x); y=x%2; /* y will be 1 or zero based on value entered

and stored as x */ if(y=1) { /* y will be assigned with 1, condition will be

evaluated as TRUE */ printf(“Entered number is odd.”); } else { printf(“Entered number is even.”); }

return 0;

}

Operatorconfusion

Page 11: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

UnaryOperator•  Increment(++)Opera1onmeansi=i+1;

–  Prefixopera1on(++i)orPos`ixopera1on(i++)•  Decrement(--)Opera1onmeansi=i-1;

–  Prefixopera1on(--i)orPos`ixopera1on(i--)•  Precedence

–  Prefixopera1on:Firstincrement/decrementandthenusedinevalua1on

–  Pos`ixopera1on:Increment/decrementopera1onaaerbeingusedinevalua1on

•  Example

int t, m=1; t=++m;

int t,m=1; t=m++;

m=2t=2

m=2t=1

Page 12: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

MoreExamplesonUnaryOperator

Ini1alvalues::a=10;b=20 x = 50 + ++a; a=11,x=61Ini1alvalues::a=10;b=20;x = 50 + a++; x=60,a=11Ini1alvalues::a=10;b=20;x = a++ + --b; b=19,x=29,a=11Ini1alvalues::a=10;b=20; x = a++ – ++a; Undefinedvalue(implementa1ondependent)

Page 13: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

ShortcutsinAssignmentStatements

•  A+=C à A=A+C •  A-=B à A=A-B •  A*=D à A=A*D •  A/=E à A=A/E

Page 14: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Inputscanf (“control string”,arg1,arg2, …, argn);

•  Performsinputfromthestandardinputdevice,whichisthekeyboardby

default.•  Itrequiresacontrolstringreferstoastringtypicallycontainingdatatypesof

theargumentstobereadin.•  Andthe(arguments)addressorpointersofthelistofvariablesintowhich

thevaluereceivedfromtheinputdevicewillbestored.•  Theaddressofthevariablesinmemoryarerequiredtomen1on(&before

thevariablename)tostorethedata.•  Thecontrolstringconsistsofindividualgroupsofcharacters(onecharacter

groupforeachinputdataitem).Typically,a‘%’sign,followedbyaconversioncharacter.

int size,a,b; float length; scanf ("%d", &size) ; scanf ("%f", &length) ; scanf (“%d %d”, &a, &b);

Page 15: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

InputConversionCharacter DataItemmeaningc Singlecharcaterd Decimalintegere Floa1ngpointvaluef Floa1ngpointvalueg Floa1ngpointvalueh Shortinti Decimal/hexadecimal/octalintegero Octalintegers Stringu UnsigneddecimalintegerX Hexadecimalinteger

Wecanalsospecifythemaximumfield-widthofadataitem,byspecifyinganumberindica1ngthefieldwidthbeforetheconversioncharacter.

Example:scanf(“%3d%5d”,&a,&b);

Page 16: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Outputprintf (“control string”,arg1,arg2, …, argn);

–  Performsoutputtothestandardoutputdevice(typicallydefinedtobethe

screen).–  Controlstringreferstoastringcontainingformaqnginforma1onanddata

typesoftheargumentstobeoutput;–  Theargumentsarg1,arg2,…representtheindividualoutputdataitems.–  Theconversioncharactersarethesameasinscanf.

int size,a,b; float length; scanf ("%d", &size) ; printf(“%d”,size); scanf ("%f", &length) ; printf(“%f”,length); scanf (“%d %d”, &a, &b); printf(“%d %d”,a,b);

Page 17: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Forma@edOutput

float a=3.0, b=7.0; printf(“%f %f %f %f”,a,b,a+b,sqrt(a+b)); 3.000000 7.000000 10.000000 3.162278 printf(“%4.2f %5.1f\na+b=%3.2f\tSquare Root=%-6.3f”,a,b,a+b,sqrt(a+b)); 3.00 7.0 a+b=10.00 Square Root=3.162

Willbewrisenexactly.

LeaAlign

Tab

TotalSpace

Aaerdecimalplace

Forinteger,characterandstring,nodecimalpoint.

Page 18: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

CharacterI/Ochar ch1; scanf(“%c”,&ch1); /* Reads a character */

printf(“%c”,ch1); /* Prints a character */ ch1=getchar(); /* Reads a character */

putchar(ch1); /* Prints a character */

char name[20];

scanf(“%s”,name); /* Reads a string */ printf(“%s”,name); /* Prints a string */

gets(name); /* Reads a string */

puts(name); /* Prints a string */

Helpforanycommand:$mangets

Page 19: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Problemsolving

•  Step1:–  Clearlyspecifytheproblemtobesolved.

•  Step2:–  Drawflowchartorwritealgorithm.

•  Step3:–  Convertflowchart(algorithm)intoprogramcode.

•  Step4:–  Compiletheprogramintoexecutablefile.

•  Step5:–  Foranycompila1onerror,gobacktostep3fordebugging.

•  Step6:–  Executetheexecutablefile(program).

Page 20: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Flowchart:basicsymbols

Process

FlowLine

Terminal

Decision I/OData

PredefinedProcess

Prepara1on

Connector

Page 21: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example2:findthelargestamongthreenumbers

START

READ X, Y, Z

IS LARGE > Z?

IS X > Y?

LARGE = X LARGE = Y

OUTPUT LARGE OUTPUT Z

STOP STOP

YES

YES

NO

NO

Page 22: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Branching:ifStatement•  Generalsyntax:

if(condiJon){……..}

•  Testthecondi1on,andfollowappropriatepath.

•  ContainsanexpressionthatcanbeTRUEorFALSE.

•  Single-entry/single-exitstructure.•  Ifthereisasinglestatementintheblock,the

bracescanbeomised.

if(basicPay<18000) prin`(“BonusApplicable”);

True

False

condi1on

Statement

if(basicPay<18000){

intbonus;bonus=basicPay*0.30;prin`(“Bonusis%d”,bonus);

}

Page 23: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Branching:if-elseStatement•  Generalsyntax:

if (condition) { …… block 1 ……. } else { …….. block 2 …….. }

•  Alsoasingle-entry/single-exitstructure.•  Allowsustospecifytwoalternateblocksofstatements,oneofwhichisexecuted

dependingontheoutcomeofthecondi1on.•  Ifablockcontainsasinglestatement,thebracescanbeomised.

True

False age<60

Print“GeneralQuota”

Print“SeniorCi1zen”

if(age<60){ prin`(“GeneralQuota”);

}else{prin`(“SeniorCi1zen”);

}

Page 24: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example2:findthelargestamongthreenumbersSTART

READ X, Y, Z

IS LARGE > Z?

IS X > Y?

LARGE = X LARGE = Y

OUTPUT LARGE OUTPUT Z

STOP STOP

YES

YES

NO

NO

#include <stdio.h> int main()

{

int X,Y,Z,Large;

scanf (“%d %d %d”, &X, &Y, &Z);

if (X>Y) {

Large=X;

} else {

Large=Y;

}

if (Large>Z)

printf (“\nThe largest number is: %d”,Large);

else

printf (“\n The largest number is: %d”,Z);

return 0;

}

Page 25: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Nestedbranching

•  Itispossibletonestif-elsestatements,onewithinanother.•  Allifstatementsmaynotbehavingthe“else”part.

–  Confusion??•  Ruletoberemembered:

–  An“else”clauseisassociatedwiththeclosestprecedingunmatched“if”.

•  Example:if(age<60) { if(age<5) { printf(“Kid Quota”); } else if (age<10) { printf(“Child Quota”); } else { printf(“General Quota”); } } else { printf(“Senior Citizen”); }

Page 26: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

DesirableProgrammingStyle•  Clarity

–  Theprogramshouldbeclearlywrisen.–  Itshouldbeeasytofollowtheprogramlogic.

•  Meaningfulvariablenames–  Makevariable/constantnamesmeaningfultoenhanceprogramclarity.

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

•  Programdocumenta1on–  Insertcommentsintheprogramtomakeiteasytounderstand.–  Neverusetoomanycomments.

•  Programindenta1on–  Useproperindenta1on.–  Structureoftheprogramshouldbeimmediatelyvisible.

Page 27: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

IndentaJonExample::GoodStyle/*AprogramtochecktheagebasedquotainIndianRailway1cke1ngsystem*/#include<stdio.h>#defineSENIOR 60 /*DeclaretheageofSeniorCi1zen*/intmain(){

intage;scanf(“%d”,&age);if(age<SENIOR){ if(age<5){ prin`(“KidQuota”); }elseif(age<10){ prin`(“ChildQuota”); }else{ prin`(“GeneralQuota”); }}else{ prin`(“SeniorCi1zen”);}return0;

}

Page 28: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

IndentaJonExample::BadStyle#include<stdio.h>#defineSENIOR 60 intmain(){intage;scanf(“%d”,&age);if(age<SENIOR){ if(age<5){prin`(“KidQuota”);}elseif(age<10){prin`(“ChildQuota”);}else{prin`(“GeneralQuota”);}}else{prin`(“SeniorCi1zen”);}return0;}

#include<stdio.h>#defineSENIOR 60 intmain(){intage;scanf(“%d”,&age);if(age<SENIOR){ if(age<5){prin`(“KidQuota”);}elseif(age<10){prin`(“ChildQuota”);}else{prin`(“GeneralQuota”);}}else{prin`(“SeniorCi1zen”);}return0;}

Page 29: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example3:Gradecomputa2on

MARKS≥90èEx89≥MARKS≥80èA79≥MARKS≥70èB69≥MARKS≥60èC59≥MARKS≥50èD49≥MARKS≥35èP35<MARKSèF

START

READ MARKS

OUTPUT “Ex”

MARKS ≥ 90? MARKS ≥ 80? MARKS ≥ 70?

OUTPUT “A” OUTPUT “B”

STOP STOP STOP

A

YES YES YES

NO NO NO

Page 30: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

MARKS ≥ 60?

STOP

OUTPUT “C”

A MARKS ≥ 50? MARKS ≥ 35?

OUTPUT “D” OUTPUT “P” OUTPUT “F”

STOP STOP STOP

YES YES YES

NO NO NO

Example3:Gradecomputa2on

MARKS≥90èEx89≥MARKS≥80èA79≥MARKS≥70èB69≥MARKS≥60èC59≥MARKS≥50èD49≥MARKS≥35èP35<MARKSèF

Homework:ConverttoaCprogram

Page 31: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

TernarycondiJonaloperator(?:)–  Takesthreearguments(condi1on,valueiftrue,valueiffalse).–  Returnstheevaluatedvalueaccordingly.

age >= 60 ? printf(“Senior Citizen\n”) : printf(“General Quota\n”);

(condition1)? (expr1): (expr2);

Example:bonus = (basicPay<18000) ? basicPay*0.30 : basicPay*0.05;

Returns a value

Page 32: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

switchStatement•  Thiscausesapar1culargroupofstatementstobechosenfromseveralavailablegroups.– Uses“switch”statementand“case”labels.–  Syntaxofthe“switch”statement:

switch (expression) { case expression1: { …….. } case expression2: { …….. } case expressionm: { …….. } default: { ……… } }

Page 33: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

switchexample

switch ( letter ) {

case 'A': printf("First letter\n");

break;

case 'Z':

printf("Last letter\n");

break; default :

printf("Middle letter\n");

break;

}

“break”statementisusedtobreaktheorderofexecu1on.

Page 34: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

ThebreakStatement

•  Usedtoexitfromaswitchorterminatefromaloop.

•  Withrespectto“switch”,the“break”statementcausesatransferofcontroloutoftheen1re“switch”statement,tothefirststatementfollowingthe“switch”statement.

Page 35: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

true

false .

.

.

case a

case a action(s)

break

case b

case b action(s)

break

false

default

default action(s)

break

true

Flowchartforswitchstatement

Page 36: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example:switchbreakswitch (primaryColor = getchar()) {

case ‘R’: printf (“RED \n”); break; case ‘G’: printf (“GREEN \n”); break; case ‘B’: printf (“BLUE \n”); break; default: printf (“Invalid Color \n”); break; /* break is not mandatory here */

}

Page 37: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example5:SumoffirstNnaturalnumbers

START

READ N

SUM = 0 COUNT = 1

SUM = SUM + COUNT

COUNT = COUNT + 1

IS COUNT > N? OUTPUT SUM

STOP

YES

NO

Page 38: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example6:Compu2ngFactorial

START

READ N

FACT = 1 COUNT = 1

FACT = FACT * COUNT

COUNT = COUNT + 1

IS COUNT > N? OUTPUT FACT

STOP

YES NO

Page 39: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Exercise1:FindtheRootsofaquadra2cequa2on

ax2 + bx + c = 0

Coefficients(a,b,c)areyourinput.

Page 40: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

TheEssenJalsofRepeJJon

•  Loop–  Groupofinstruc1onscomputerexecutesrepeatedlywhilesome

condi1onremainstrue

•  Counter-controlledrepe11on

–  Definiterepe11on-knowhowmany1mesloopwillexecute–  Controlvariableusedtocountrepe11ons

•  Sen1nel-controlledrepe11on–  Indefiniterepe11on–  Usedwhennumberofrepe11onsnotknown–  Sen1nelvalueindicates"endofdata"

Page 41: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Counter-ControlledRepeJJon

•  Counter-controlled repetition requires–  nameofacontrolvariable(orloopcounter).–  ini&alvalueofthecontrolvariable.–  condi1onthattestsforthefinalvalueofthecontrolvariable(i.e.,

whetherloopingshouldcon1nue).–  increment (or decrement) by which the control variable is

modifiedeach1methroughtheloop.

int counter =1; /* initialization */ while (counter <= 10) { /* repetition condition */

printf( "%d\n", counter ); ++counter; //increment

}

Page 42: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

RepeJJon:Flowchart

Cond

statement(s)

true

false

Single-entry / single-exit structure

Cond

statement(s)

true

false

int counter =1;

while (counter <= 10) { printf( "%d\n", counter ); ++counter;

}

int counter =1;

do { printf( "%d\n", counter ); ++counter;

} while (counter <= 10) ;

MaynotexecuteatallbasedoncondiJon.

Willbeexecutedatleastonce,whateverbethecondiJon.

Page 43: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

while,do-whileStatement

while (condition) statement_to_repeat;

while (condition) { statement_1; ... statement_N;

}

intweight=75;while(weight>65){

prinn("Go,exercise,");prinn("thencomeback.\n");prinn("Enteryourweight:");scanf("%d",&weight);

}

intdigit=0;while(digit<=9)prinn(“%d\n”,digit++);

weight=75; do{

prinn("Go,exercise,");prinn("thencomeback.\n");prinn("Enteryourweight:");scanf("%d",&weight);

}while(weight>65);Atleastoneroundofexerciseisensured.

do { statement-1; statement-2; …….. statement-n; } while ( condition );

Page 44: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example5:SumoffirstNnaturalnumbers#include<stdio.h>intmain(){

intn,sum,count;prin`(“Enteranaturalnumber:”);scanf(“%d”,&n);count=0;sum=0;while(count<=n){ sum+=count;//sum=sum+count count++;}prin`(“Thesumoffirst%dnaturalnumbersis:%d”, n,sum);return0;

}

Linebreakinastatementisallowedaaeracomma.

START

READ N

SUM = 0 COUNT = 1

SUM = SUM + COUNT

COUNT = COUNT + 1

IS COUNT > N? OUTPUT SUM

STOP

YES

NO

Page 45: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example6:Compu2ngFactorial#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);count=1;fact=1;while(count<=n){ fact=fact*count; count++;}prin`(“Thefactorialof%dis:%d”,n,fact);return0;

}

Consideringlargefactorialvalue,youmaydeclarefactasfloat.

START

READ N

FACT = 1 COUNT = 1

FACT = FACT * COUNT

COUNT = COUNT + 1

IS COUNT > N? OUTPUT FACT

STOP

YES NO

Page 46: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example7:Compu2ngFactorial

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);count=n;fact=1;while(count>=1){ fact=fact*count; count--;}prin`(“%d”,fact);return0;

}

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);count=1;fact=1;while(count<=n){ fact=fact*count; count++;}prin`(“%d”,fact);return0;

}

Loopvariablemaydecrement

countmayincrement. countmaydecrement.

Page 47: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Counter-ControlledRepeJJon•  Counter-controlled repetition requires

–  nameofacontrolvariable(orloopcounter).–  ini&alvalueofthecontrolvariable.–  condi1onthattestsforthefinalvalueofthecontrolvariable(i.e.,

whetherloopingshouldcon1nue).–  increment (or decrement) by which the control variable is

modifiedeach1methroughtheloop.

for(ini1al;condi1on;itera1on) statement_to_repeat;

for(ini1al;condi1on;itera1on){

statement_to_repeat; …… statement_to_repeat;

}

Allareexpressions.ini&alàexpr1condi&onàexpr2itera&onàexpr3

fact = 1; /* Calculate 10! */ for ( i = 1; i < =10; i++)

fact = fact * i;

Page 48: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

forloop

Single-entry / single-exit structure

expression2

statement(s)

True

False

expression1

expression3

for (initial; condition; iteration) {

statement_1; …… statement_n;

}

•  Howitworks?–  “expression1”isusedtoini&alize

somevariable(calledindex)thatcontrolstheloopingac1on.

–  “expression2”representsacondi&onthatmustbetrueforthelooptocon1nue.

–  “expression3”isusedtoalterthevalueoftheindexini1allyassignedby“expression1”.

Page 49: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example8:Compu2ngFactorial

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);fact=1;for(count=1;count<=n;count++){ fact=fact*count; }prin`(“%d”,fact);return0;

}

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);count=1;fact=1;while(count<=n){ fact=fact*count; count++;}prin`(“%d”,fact);return0;

}

whileloop forloop

Page 50: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example9:Compu2ngFactorial

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);fact=1;for(count=1;count<=N;count++){ fact=fact*count; }prin`(“%d”,fact);return0;

}

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);count=1;fact=1;for(;count<=n;){ fact=fact*count; count++;}prin`(“%d”,fact);return0;

}

forloopworkingaswhile

forloopHomework:Rewritethefactorialusingforloopandbydecremen1ngcount.

Page 51: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example10:Compu2ngFactorial

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);for(fact=1,count=1;count<=n;count++){ fact=fact*count; }prin`(“%d”,fact);return0;

}

forloopforloopwithcommaoperator

Thecommaoperator:Wecangiveseveralstatementsseparatedbycommasinplaceof“expression1”,“expression2”,and“expression3”.

#include<stdio.h>intmain(){

intn,fact,count;prin`(“Enteranumber:”);scanf(“%d”,&n);fact=1;for(count=1;count<=n;count++){ fact=fact*count; }prin`(“%d”,fact);return0;

}

Page 52: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Advancedexpressioninforstructure•  Arithme1cexpressions

–  Ini1aliza1on,loop-con1nua1on,andincrementcancontainarithme1cexpressions.

–  e.g.Letx = 2andy = 10 for ( j = x; j <= 4 * x * y; j += y / x ) isequivalentto

for ( j = 2; j <= 80; j += 5 )

"Increment"maybenega1ve(decrement)Ifloopcon1nua1oncondi1onini1allyfalse

BodyofforstructurenotperformedControlproceedswithstatementaaerforstructure

Page 53: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Specifying“InfiniteLoop”

count=1;while(1){

prinn(“Count=%d”,count);count++;

}

count=1;do{

prinn(“Count=%d”,count);count++;

}while(1);

count=1;for(;;){

prinn(“Count=%d”,count);count++;

}

for(count=1;;count++){prinn(“Count=%d”,count);

}

Page 54: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

breakStatement•  Breakoutoftheloop{}

–  canusewith •  while•  dowhile•  for•  switch

–  doesnotworkwith •  if{}•  else{}

•  Causesimmediateexitfromawhile,for,do/whileorswitchstructure

•  Programexecu1oncon1nueswiththefirststatementaaerthestructure

•  Commonusesofthebreakstatement–  Escapeearlyfromaloop–  Skiptheremainderofaswitchstructure

Page 55: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Breakfrom“InfiniteLoop”

count=1;while(1){

prinn(“Count=%d”,count);count++;if(count>100) break;

}

count=1;do{

prinn(“Count=%d”,count);count++;if(count>100) break;

}while(1);

count=1;for(;;){

prinn(“Count=%d”,count);count++;if(count>100) break;

}

for(count=1;;count++){prinn(“Count=%d”,count);if(count>100) break;

}

Page 56: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

con2nueStatement

•  con1nue–  Skipstheremainingstatementsinthebodyofawhile,forordo/whilestructure

•  Proceedswiththenextitera1onoftheloop

–  whileanddo/while•  Loop-con1nua1ontestisevaluatedimmediatelyaaerthecontinuestatementisexecuted

–  forstructure•  Incrementexpressionisexecuted,thentheloop-con1nua1ontestisevaluated.

•  expression3isevaluated,thenexpression2isevaluated.

Page 57: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

AnExamplewithbreakandcon2nue

fact = 1; /* a program to calculate 10 ! */

i = 1; while (1) {

fact = fact * i;

i++ ;

if(i<10) {

continue; /* not done yet! Go to next iteration*/

}

break;

}

Page 58: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example11:PrimalitytesJng#include <stdio.h> int main() { int n, i=2; scanf (“%d”, &n); while (i < n) { if (n % i == 0) { printf (“%d is not a prime \n”, n); break; } i++; } if(i>=n) printf (“%d is a prime \n”, n); return 0;

}

Page 59: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example12:ComputeGCDoftwonumbers#include <stdio.h> int main()

{

int A, B, temp;

scanf (%d %d”, &A, &B);

if (A > B) {

temp = A;

A = B;

B = temp; }

while ((B % A) != 0) {

temp = B % A;

B = A;

A = temp;

}

printf (“The GCD is %d”, A);

return 0;

}

12 ) 45 ( 3

36

9 ) 12 ( 1

9

3 ) 9 ( 3

9

0

Initial: A=12, B=45 Iteration 1: temp=9, B=12,A=9 Iteration 2: temp=3, B=9, A=3 B % A = 0 è GCD is 3

Page 60: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Example13:Findthesumofdigitsofanumber

#include <stdio.h>

int main() {

int n, sum=0;

scanf (“%d”, &n);

while (n != 0) {

sum = sum + (n % 10); n = n / 10;

}

printf (“The sum of digits of the number is %d \n”, sum);

return 0;

}

N=56342;56342%10=2;

56342/10=5634;5634%10=4;

5634/10=563;563%10=3;

563/10=56;56%10=6;

56/10=5;5%10=5;

5/10=0;N=0;

Page 61: CS11001/CS11002 Programming and Data Structures (PDS ...pds/semester/2017s/slides/Presentation2.pdf · h Short int i Decimal/hexadecimal/octal integer o Octal integer s String u Unsigned

Exercise2:

WriteaCprogramthatwillreadadecimalintegerandwillconverttoequivalenttobinarynumber.