Lecture5
Lecture5
Puru
with
CS101 TAs and CSE Staff
• loops
– while
– do-while
– for
True
Condition
Consequent
False
Next Statement
True False
Condition
Consequent Alternate
Next statement
Autumn 2019 CS101@CSE IIT Bombay
the slightly improved discount program
main_program {
double total, discount;
True False
Condition 1
Consequent 3 Alternate
Next Statement
Autumn 2019 CS101@CSE IIT Bombay
the discount program
main_program {
double total, discount;
Boolean OR
condition1 || condition2
true if at least one is true
Boolean negation
!condition
true if only if condition is false
main_program {
int num = 0;
cin >> num;
• 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
False
Condition
True
Body of loop
// infinite loop!
#include <simplecpp>
main_program{
int x=10;
while(x > 0){
cout << “Iterating” << endl;
}
}
// Will endlessly keep printing
// Not a good program
#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)!
repeat can be
expressed using while?
while can be
expressed as repeat?
while can be
expressed as repeat?
int n;
cin >> n;
while(n>=0) {
cout << n; // print
cin >> n; // next number
}
while (true){
cin >> nextmark;
if(nextmark > 100)
continue;
if(nextmark < 0)
break;
sum = sum + nextmark;
}
cout << sum << endl;
}
Initialization
Condition False
True
Body
Update
is same as