03 conditions loops

30
Computer Programming Conditions, loops Prof. Dr. Mohammad Haseeb Zafar [email protected]

Transcript of 03 conditions loops

Page 1: 03   conditions loops

Computer Programming

Conditions, loops

Prof. Dr. Mohammad Haseeb [email protected]

Page 2: 03   conditions loops

Today’s lecture

• Introduction to program control– Conditional controls

• if, if … else, ?:, switch-case– Loop controls

• for, while, do … while, if … break, if … continue

• Typesetting of source code• Use of indentation to keep track of nested conditions and loops

• Use of whitespace to group actions together

• Use of comments

• Log books

Page 3: 03   conditions loops

The need for program control

• Not all C++ programs execute from the first line, linearly to the last, – Most involve repetition, skipping and conditional branching

• In most programs, the program control path through the code depends on the values of variables at different points in the program– The values of variables can be changed as the program proceeds

• Conditional statements can be used to selectively execute either:– A single line of code,

• Braces { } not required around the executable statement

– Multiple lines of related code (called a block)• Braces { } REQUIRED around the executable statement

Page 4: 03   conditions loops

Flowchart: Hot drink example(refer to Lecture 1) Start

Kettle waterlevel == 0?

Want milk?

Put teabag in mug

Tea

Drink!

NoExtract teabag

Yes

Add milk

Yes

Heat kettle

Yes

Fill kettle

Yes

Put instant coffee in mug

Coffee

Teabag in mug?

No

Want teaor coffee?

No

Watertemp < 100?

No

If statement

A loop

Test condition for the loop(whether or not to do an

iteration)

A switch

If statement

If statement

Page 5: 03   conditions loops

• The if keyword is used to test a given expression for a value of true or false

– if the result is true, then a specified series of statements is executed• the series of statements is specified within braces after the test

• the execution of these statements is conditional on the result of the test

– otherwise, those conditional statements are skipped

• The else keyword is used with an if statement to specify an alternative path to be executed when the test expression is false

• Syntax:

if (test-expression)

{

code-to-be-executed-when-true;

}

Conditionals: if and if … else

Each statement ends with a semi colon!!

Page 6: 03   conditions loops

Conditional if statement

• Example program section:

int main(int argc, char* argv[])

{

int x=0, y=0;

cin >> x ;

cin >> y ;

if ( x > y )

cout << “true, x > y\n“ ;

return 0;

}

Page 7: 03   conditions loops

Nested if statement

• if statements can be nested inside other if blocks to express multiple tests, e.g. x < y, x == y, x != y

• Indentation applied for nested if blocks to keep track of nested blocks

if (test1_expression)

{

if (test2_expression)

{

test2_true_action;

}

} Indentation

Page 8: 03   conditions loops

if-else statement

• This is called ‘conditional branching’ because the program will choose a certain route depending on the test result.

• The syntax:

if (test-expression){

test_true_action1;

test_true_action2;

test_true_action3;

}

else

test_false_action;

Page 9: 03   conditions loops

if-else statement

• Example:

int main(int argc, char* argv[])

{

int int1;

cin >> int1;

if ( int1 > 1 )

cout << “yes, int1 is > 1\n “ ;

else

cout << “ no, int1 is not > 1\n “;

return 0;

}Indentation

Page 10: 03   conditions loops

The ?: Conditional operator

• Unique to C/C++• The ?: conditional operator provides a quick way to write a

test condition. • Associated actions are performed depending on whether the test_expression evaluates to true or false.

• The operator can be used to replace an equivalent if-else statement.

• Syntax:

test_expression ? true_action : false_action ;

• Using example in previous slide:

(int1 > 1) ? cout << “yes, int1 is > 1\n “ : cout << “ no, int1 is not > 1\n “;

Page 11: 03   conditions loops

switch statement

• Multiple if-else statements

– conditional branching can often be more efficiently programmed by using a switch statement

• switch uses a given integer/string/float… value then finds a matching value among a series of case statements.

• default instructions can be specified for the case of no match being found.

• Each case statement ends with a break instruction

– causes the remaining set of switch statements to be skipped.

Page 12: 03   conditions loops

switch statement

• Syntax

switch (integral_expression)

{

case constant1:

statements1;

break;

case constant2:

statements2;

break;

default:

statements;

}

No need for braces. Statements execute until break is encountered.

Never forget to include break!

If integral_expression is neither constant1 nor constant2, execute the following statements

Page 13: 03   conditions loops

switch statement

• Example: int main(int argc, char* argv[])

{

int int1;

cout << “enter an integer: “;

cin >> int1;

switch (int1)

{ case 1 : cout << “1 found\n “ ; break;

case 2 : cout << “2 found\n “; break;

case 3 : cout << “3 found\n “; break;

default : cout << “ int1 is not 1, 2 or 3\n “;

}

return 0;

}

Try choice of hot drink example, e.g. hot drink dispensing machine

Page 14: 03   conditions loops

Loops

• for, while and do-while loops• The basic difference between a for loop and a while or do-while loop has to do with the “known” number of repetitions– for loops are used whenever the required number of repetitions is

defined• the required number of repetitions could be given by a constant or the

value of a variable

– while and do-while are used for an unknown number of

repetitions. (good for interrupt based codes or code that is invoked on status changes)

Page 15: 03   conditions loops

for loops

• The loop iterates while the tested expression is true, repetitions or iterations stop when the test-expression is found false.

• Syntax: for(initialization_exp; test-exp; operation)

{statements

}• Example:

int i; for(i=0; i < 2; i++)

{cout << “iteration “ << i << endl;

} The operation doesn’t need to be an increment

If i were initially 2, the cout would never be executed

Only execute the statements inside the braces if this condition is satisfied

Each time around the loop, perform this operation

Output:iteration 0iteration 1

Page 16: 03   conditions loops

Nested for-loops example

#include <iostream>using namespace std;

int main(int argc, char* argv[]){ //note: indentation applied to keep track of nested loops int i, j;

for(i = 1; i < 4; i++) { cout << “outer loop iteration” << i << endl; for(j = 1; j < 4; j++) { cout << “\t inner loop iteration” << j << endl; } } return 0;}

Page 17: 03   conditions loops

while loops

• The while keyword is combined with an expression to be tested for a true or false value.

– If the tested expression is true, iteration around the loop will continue,

– If the tested expression is false, iteration will stop.

• The while loop is a pre-test loop just like the for loop,

– the program evaluates the test_expression before entering the statement(s) within the body of the loop.

– Pre-test loops can be executed from zero to many times.

Page 18: 03   conditions loops

while loops

• Syntax: while(test_expression) {statements}• Example:

int i;

i = 0;

while(i < 2)

{

cout << “ iteration “ << i << endl;

i = i + 1;

}

Make sure the test_expression comes to an end to avoid infinite looping

Equivalent to i++;

Output:iteration 0iteration 1This is equivalent to the first for example

Page 19: 03   conditions loops

do-while loops

• The do-while loop differs from the for and while loops in that it is a post-test loop– the loop is at least entered at least once– the loop condition is tested at the end of the 1st iteration.

• do-while loops are best used when there is no doubt the statement(s) within the loop need to be executed at least once– e.g. presenting a menu to the user even if the user wants to exit

immediately after.

Page 20: 03   conditions loops

do-while loops • The do keyword is followed by a statement block within

braces to be executed on each iteration. • Then, the while keyword and an expression to be tested for

a true or false value. – If the tested expression is true the loop will continue, – If the tested expression is false, the loop will be exited.– At least one execution of the statement block will occur.

• Syntax:

do {

statements

} while (test-expression);

Page 21: 03   conditions loops

do-while example

int i;

i = 0;

do

{

cout << “iteration “ << i << endl;

i = i + 1;

} while( i<2 );

As it stands, this produces the same resultas the previous while example

Output:iteration 0iteration 1

i is initially 0

No test on whether or not to enter the do block

Execute the cout

First time through, i=1 so do the do block again

Second time through, i<2 is false so do not do the do block again

Page 22: 03   conditions loops

do-while example

int i;

i = 2;

do

{

cout << “iteration “ << i << endl;

i = i + 1;

} while( i<2 );

• If i were initially 2 in the previous while example, the cout would not have been executed

• In the do-while example above, however, the statements inside the braces are executed at least once

• The test is applied only afterwards Output:iteration 0

i is initially 2

Page 23: 03   conditions loops

if-break statement

• The break keyword was used to exit case statements inside a switch. It can also be used to break out of a loop.

• A break statement can be used inside any loop statement block, combined with a conditional test. – When the test is found to be true the loop terminates (no more

iterations).• Example/syntax: int i = 0; while( i < 4 )

{ i = i + 1; cout << “ iteration “ << i;

if(i > 2) break; cout << “go to the next\n“ ;

} cout << “Go on through the program\n”;

Outputiteration 1 go to the nextiteration 2 go to the nextiteration 3Go on through the program

When i>2, the program jumps out of the loop

• go to the next is not written

Page 24: 03   conditions loops

if-continue statement• continue is used to go immediately to the start of the next iteration • continue can be used inside any type of loop, combined with a

conditional test. – When the test result is true

• current iteration is immediately terminated and the next iteration begins.

– Be careful to avoid infinite loops. • It must be possible for the test result to be false

int i = 0;

while( i < 4 ) {

i = i + 1;

if(i == 2) continue;

cout << “ iteration “ << i;

cout << “go to the next\n“ ;

}

cout << “Go on through the program\n”;

Outputiteration 1 go to the nextiteration 3 go to the nextGo on through the program

Page 25: 03   conditions loops

Review of syntax - 1 •if (test-expression) {

code-to-be-executed-when-true }

•if (test-expression) {

do-this-if-true } else {

do-this }

•(test-expression)? if-true-do-this : if-false-do-this ;

Page 26: 03   conditions loops

Review of syntax - 2 •switch (a) {

case a1 : s1; break; case a2 : s2; break; case a3 : s3; break; default : s4; }•for(initializer; test-expression; operation)

{

statements

}

•while(test-expression) {statements} •do{statements} while (test-expression); •if(test) break ;•if(test) continue;

Page 27: 03   conditions loops

Review of syntax - 3 •while(test-expression)

{

statements

}

•do {

statements

} while (test-expression);

•if(test) break ;

•if(test) continue;

Page 28: 03   conditions loops

++,-- operators

• The ++ increment operator and -- decrement operator change the given value by 1– commonly used to count iterations in loops.

• Postfix increment operator, e.g. a++, uses the value of the variable in an expression first and then increments its value.

• Prefix increment operator, e.g. ++a, increments the value of the variable first and then uses the value in an expression.

• Examples:int i=3, j, k=0;• k = ++i; //i=4, k=4• k = i++; //i=4, k=3• i = j = k--; //i=0, j=0, k=-1• TAKE CARE!

Page 29: 03   conditions loops

Whitespace, comments, endl, \n, indentation• Some lines left blank, called whitespace, make it easier to

read your program, – separate sections of code into related statements (grouping actions

together)

• The double-slash // comment is a C++ style comment– tells the compiler to ignore everything that follows the slashes until

the end of the line.

• The c-style slash-star /* comment mark – tells the compiler to ignore everything that follows until it finds a star-

slash */ comment mark

• \n indicates the newline escape sequence, – endl is a C++ alternative to \n

• Use indentation to keep track of nested loops or conditions

Page 30: 03   conditions loops

Log books

• You must keep a log book– The log book should be handed in once each semester– 10% of the final marks will be based on your log book

• What should go in a log book?– print outs of working source code you have written for

each lab– notes of results of testing of code in each lab– evidence of your own reflection on programming, e.g.

• annotation of source code to note important points• aide memoires to yourself