0% found this document useful (0 votes)
0 views

Lecture5

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture5

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CS 101

Computer Programming and


Utilization

Puru
with
CS101 TAs and CSE Staff

Course webpage: https://www.cse.iitb.ac.in/~cs101/

Lecture 5: conditional execution and general loops

Autumn 2019 CS101@CSE IIT Bombay


• Lab3
– conditional execution and loops
– if, if-else, while, break, continue
• Labquiz1
– 20th , 21st , 22nd August (Tue-Wed-Thu) 8.15 pm
• lookup student-lab mapping and schedule

• Bits and Bytes Labs for practice


– Monday - Friday : 9:30 AM - 8:30 PM
Saturday, Sunday, Holiday : 10:00 AM - 5:00 PM

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 2


recap
• conditional execution
– boolean condition
– if
– if-else

• loops
– while
– do-while
– for

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 3


flowchart of the if statement
Previous Statement

True
Condition

Consequent
False

Next Statement

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 4


flowchart of the if-else statement
if (condition) consequent else alternate
Previous statement

True False
Condition

Consequent Alternate

Next statement
Autumn 2019 CS101@CSE IIT Bombay
the slightly improved discount program

main_program {
double total, discount;

cin >> total;

if (total < 1000)


cout << No discount << endl;
else
cout << Discount coming your way!”<< endl;
}

Autumn 2019 CS101@CSE IIT Bombay


flowchart of the general if-else statement
Previous Statement

True False
Condition 1

Consequent 1 True False


Condition 2

Consequent 2 True False


Condition 3

Consequent 3 Alternate

Next Statement
Autumn 2019 CS101@CSE IIT Bombay
the discount program
main_program {
double total, discount;

cin >> total; // get input

if (total < 1000) discount = 0;


else if (total < 2000)
discount = 0.1 * total;
else if (total < 5000)
discount = 0.2 * total;
else discount = 500 + 0.3 * total;

cout << “Total discount = “ << discount << endl;


}

Autumn 2019 CS101@CSE IIT Bombay


the discount + points program
double total, discount;
int points;
cin >> total; // get input

if (total <= 1000) {


discount = 0;
points= 10;
}
else if (total <= 2000) {
discount = 0.1 * total;
points = 20;
}
else if (total <= 5000) {
discount = 0.2 * total;
points = 30;
}
else { discount = 500 + 0.3 * total; points = 50; }

cout << “Total discount = “ << discount << endl;


Autumn 2019 CS101@CSE IIT Bombay
combining conditions
Boolean AND
condition1 && condition2
true only if both true

Boolean OR
condition1 || condition2
true if at least one is true

Boolean negation
!condition
true if only if condition is false

Autumn 2019 CS101@CSE IIT Bombay


examples for combined conditions
if ((total < 1000) || (nitems == 1)) discount = 10;

if ((discount > 500) && (nitems == 1)) discount = 50;

write without combined conditions …

bool flag = (2>3);


if (!flag) cout << “ 2 is really less than 3 \n”;

if (!flag || flag) cout << “why flag? \n”;

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 11


sample multi-condition execution
input a number less than 10
print square of it, if is a even number
else cube of the number, else print error

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 12


sample multi-condition execution
input a number less than 10
print square of it if is a even number else cube of the number,
else print error
#include <simplecpp>

main_program {
int num = 0;
cin >> num;

if (num<10 && num%2==0)


cout << num*num;
else if (num<10 && num%3==0)
cout << num*num*num;
else
cout << “Number out of range or not divisible by 2 or 3 !”;
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 13


need of a more general loop
Read marks of students from the keyboard and prints average
• number of students not mentioned/known
• if a negative number is entered as marks, then it is a signal that all
marks have been entered

• Examples
− Input: 98 96 -1, Output: 97
− Input: 90 80 70 60 -1, Output: 75

The repeat statement repeats a fixed number of times. Not useful
• We need a more general statement
• while, do while, or for

Autumn 2019 CS101@CSE IIT Bombay


what is required?

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 15


what is required?
• a loop that keeps iterating till a condition is true
– till all students marks are entered
– till end of a file is reached
– till all columns of a table are added up
–…

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 16


the while statement flowchart
Previous statement in the program

False
Condition

True

Body of loop

Next statement in the Program

Autumn 2019 CS101@CSE IIT Bombay


the while statement

1. Evaluate the condition


If true, execute body. body can be a
single statement or a block, in which
while (condition) case all the statements in the block
body will be executed
2. Go back and execute from step 1
3. If false, execution of while statement
next_statement ends and control goes to the next
statement

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 18


the while statement
• The condition must eventually
become false, otherwise the
program will never halt.
Not halting can be tricky!
while (condition) Infinite loop.
body
• If the condition is true originally,
then the value of some variable
used in condition must change in
the execution of body, so that
eventually condition becomes
false
• Each execution of the body =
iteration

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 19


a program that does not halt

// infinite loop!
#include <simplecpp>
main_program{
int x=10;
while(x > 0){
cout << “Iterating” << endl;
}
}
// Will endlessly keep printing
// Not a good program

Autumn 2019 CS101@CSE IIT Bombay


a program that halts

#include <simplecpp>

main_program{
int x=3;
while(x > 0){
cout << “Iterating” << endl;
x--; // Same as x = x – 1;
}
}
// Will print “Iterating.” 3 times
// Good program (if that is what you want)!

Autumn 2019 CS101@CSE IIT Bombay


while vs. repeat

repeat can be
expressed using while?

while can be
expressed as repeat?

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 22


repeat as while
int n, x=0, sum=0;
cin >> n;
repeat(n) {
cin << x;
sum = sum + x;
}
cout << sum;

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 23


repeat as while
int n, x=0, sum=0;
int i=0, n, x=0, sum=0;
cin >> n;
repeat(n) { cin >> n;
cin << x; while(i<n) {
sum = sum + x; cin << x;
} sum = sum + x;
cout << sum;
i++;
}
cout << sum;

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 24


while vs. repeat

while can be
expressed as repeat?

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 25


while as repeat
// print positive integers

int n;

cin >> n;
while(n>=0) {
cout << n; // print
cin >> n; // next number
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 26


the break statement
• the break keyword is a statement by itself

• break the loop!


• when it is encountered in execution, the
execution of the innermost while statement
which contains it is terminated, and the execution
continues from the next statement following the
while statement

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 27


repeat as while
int n, x=0, sum=0; int i=0, n, x=0, sum=0;
cin >> n; cin >> n;
repeat(n) { while(i<n) {
cin << x; cin << x;
sum = sum + x; sum = sum + x;
}
i++;
cout << sum;
}
int i=0, n, x=0, sum=0;
cout << sum;
cin >> n;
while(true) { //infinite loop
if(i >=n) break;
cin << x;
sum = sum + x;
i++;
}
cout << sum;
02/08/19 Autumn 2019 CS101@CSE IIT Bombay 28
the continue statement
• the continue keyword is a statement by itself

• (skip rest of loop) continue the loop from start!


• when it is encountered in execution, the
execution of the innermost while statement
which contains it is skipped, and the execution
continues from start of the loop

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 29


example for break/continue
main_program{
float nextmark, sum = 0;

while (true){
cin >> nextmark;
if(nextmark > 100)
continue;
if(nextmark < 0)
break;
sum = sum + nextmark;
}
cout << sum << endl;
}

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 30


Example: GCD calculator
• Given two numbers, each greater than 0, calculate
the greatest common divisor
• GCD (HCF) of two numbers is the largest number
that divides both numbers without a remainder
– GCD (10, 2) =
– GCD (8, 3) =
– GCD (54, 48) =
– GCD (126, 84) =

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 31


the GCD solution
• GCD (m, n) = // assume m > n
– n if m%n == 0, else
– GCD (n, m%n)
– repeat till answer
• Example
– GCD (126, 84) = GCD (84, 42) = 42
– GCD (124, 64) = GCD (64, 4) = 4

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 32


the GCD program

02/08/19 Autumn 2019 CS101@CSE IIT Bombay 33


the do-while statement

• not very common

• discussed in the book

Autumn 2019 CS101@CSE IIT Bombay


the for statement: motivation
• Example: Write a program to print a table of cubes of numbers
from 1 to 100
int i = 1;
repeat(100){
cout << i <<‘ ‘<< i*i*i << endl;
i++;
}
• This idiom: do something for every number between x and y,
occurs very commonly
• The for statement makes it easy to express this idiom, as follows:
for(int i=1; i<= 100; i++)
cout << i <<‘ ‘<< i*i*i << endl;

Autumn 2019 CS101@CSE IIT Bombay


the for statement
for(initialization; condition; update)
body

• initialization, update : Typically assignments (without semi-colon)


• condition : boolean expression
• Before the first iteration of the loop the initialization is executed
• Within each iteration the condition is first tested. If it fails, the
loop execution ends. If the condition succeeds, then the body is
executed. After that the update is executed. Then the next
iteration begins

Autumn 2019 CS101@CSE IIT Bombay


flowchart for for Statement
Previous statement in the program

Initialization

Condition False

True
Body

Update

Next statement in the Program

Autumn 2019 CS101@CSE IIT Bombay


definition of repeat
repeat(n)

is same as

for (int _iterator_i = 0, _iterator_limit = n;


_iterator_i < _iterator_limit;
_iterator_i ++)

hence changing n in the loop will have no effect in the number of


iterations

Autumn 2019 CS101@CSE IIT Bombay


determining whether a number is prime
• using a for loop

Autumn 2019 CS101@CSE IIT Bombay


Determining whether a number is prime
main_program{
int n; cin >> n;
bool found = false;

for(int i=2; i < n && !found; i++){


if(n % i == 0){
found = true;
}
}
if(found) cout << "Composite.\n";
else cout << "Prime.\n";
}

Autumn 2019 CS101@CSE IIT Bombay

You might also like