[go: up one dir, main page]

0% found this document useful (0 votes)
16 views40 pages

Lecture 4

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views40 pages

Lecture 4

Uploaded by

itachiisgenius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
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 4: Conditional Execution and Loops

Autumn 2019 CS101@CSE IIT Bombay


recap
• turtleSim, repeat, forward, left, right, penUp, penDown
• char, int, float, double, bool

• indentation, variable naming, comments


• operators, operator precedence
• variables, assignment, re-assignment, expressions
• repeat, nested repeat
• input, output from screen

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


surprise ungraded quiz
1. int n=12345678, d0, d1, d2;
d0 = n % 10;
d1 = (n / 10) % 10;
d2 = d1 % 3;
cout << d0 << “ “ << d1 << “ “ << d2;

2. char c = ‘a’; // ASCII value of a is 98


cout << c << “ “ << ‘c’;
cout << ‘c’ + 1 << “ “ << c+1;

3. Write a program to convert a character from


lower case to upper case. i.e., a to A.

Get input from screen in lowercase.


All ASCII mappings are sequential.

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


surprise ungraded quiz
1. int n=12345678, d0, d1, d2;
d0 = n % 10;
d1 = (n / 10) % 10;
d2 = d1 % 3;
cout << d0 << “ “ << d1 << “ “ << d2;

2. char c = ‘a’; // ASCII value of a is 98


cout << c << “ “ << ‘c’;
cout << ‘c’ + 1 << “ “ << c+1;

3.

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


shadowing and scope
main_program{
int x=5;
cout << x << endl; // prints 5
repeat (3) {
cout << x << endl; // prints 5
int x = 10;
x *= 2;
cout << x << endl; // prints ____
}
cout << x << endl; // prints ____
}

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


conditional execution and loops
• basic if statement
• if-else statement
• general if statement form

• basic while loop


• switch statement
• general while loop, do-while loop and for loop
• computing logical expressions

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


discount calculator
• write a program to read total cost of items in shopping cart and
compute discount, using following rules

• If total ≤ 1000, then discount = 0


• If total is between 1000 and 2000 then discount = 10% of total
• If income is between 2000 and 5000, then discount = 20% of
total
• If income > 5000, then discount = 500 + 30% of total

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


an even simpler problem
• using the rules given earlier, read in the total print a message
indicating whether any discount will be offered

• what is required?

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


an even simpler problem
• using the rules given earlier, read in the total print a message
indicating whether any discount will be offered

• what is required?
• not a single sequential execution of a program
• only some parts of program/actions on certain inputs/conditions
• conditional execution
• the if, if-else statements

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


basic if statement
• Form:
if (condition) consequent
• condition: boolean expression
• boolean : variable/expression that evaluates to true or false
• consequent: C++ statement, statements, e.g. assignment

• If condition evaluates to true, then the consequent is executed


• If condition evaluates to false, then consequent is ignored

Autumn 2019 CS101@CSE IIT Bombay


conditions

if (condition) consequent
• Simple condition: exp1 relop exp2
• relop : relational operator
< <= == > >= !=
• less than, less than or equal, equal, greater than, greater than or
equal, not equal
• condition is true if exp1 relates to exp2 as per the specified
relational operator

Autumn 2019 CS101@CSE IIT Bombay


flowchart
• pictorial representation of a program
• statements put inside boxes
• If box C will possibly be executed after box B, then put an arrow
from B to C
• specially convenient for showing conditional execution, because
there can be more than one next statements
• diamond shaped boxes are used for condition checks

Autumn 2019 CS101@CSE IIT Bombay


flowchart of the if statement
Previous Statement

True
Condition

Consequent
False

Next Statement

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


discount calculator
• write a program to read total cost of items in shopping cart and
compute discount, using following rules

• If total less than 1000, then discount = 0


• If total is between 1000 and 2000 then discount = 10% of total
• If income is between 2000 and 5000, then discount = 20% of
total
• If income >= 5000, then discount = 500 + 30% of total

• using the rules given earlier, read in the total print a message
indicating whether any discount will be offered

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


examples for conditions
#include <simplecpp>

main_program {
int a=1, b=2, c=3, d=4;

if(a < b) cout << “a is less than b” ;

if(a > b) cout << “a is greater than b” ;

if (b) cout << “b is b”;

if ((b+c) < d) cout << “d is not big enough”;


}

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


the discount program

main_program {
double total, discount;

cin >> total;

if (total < 1000)


cout << No discount << endl;

if (total >= 1000)


cout << Discount coming your way!”<< endl;
}

Autumn 2019 CS101@CSE IIT Bombay


the discount program
main_program {
double total, discount;

cin >> total;

if (total <= 1000)


cout << No discount << endl;

if (total > 1000)


cout << Discount coming your way!”<< endl;
}
• // Always checks both conditions
• // If the first condition is true,
• // then you know second must be false,
• // and vice versa. Cannot be avoided
• // using just the basic if 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 if-else statement
if (condition) consequent else alternate
Previous statement

True False
Condition

Consequent Alternate

Next statement
Autumn 2019 CS101@CSE IIT Bombay
Most General Form of the IF-ELSE Statement
if (condition_1) consequent_1
else if (condition_2) consequent_2

else if (condition_n) consequent_n
else alternate

• Evaluate conditions in order


• Some condition true: execute the corresponding consequent.
Do not evaluate subsequent conditions
• All conditions false: execute alternate

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
• along with discount,

• points to calculated
– if total less than 1000, points = 10
– if total between 1000 to 2000 , points = 20
– if total between 2000 to 5000 , points = 30
– if total greater than equal to 5000 , points = 50

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


the discount + points program
main_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
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
another example (homework)
• rules
– for each cricket match
• Win gets 3 points
• Loss no points
• Draw one point
• Update number of wins, losses and draws of a team for each
match

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


combining conditions
condition1 && condition2 : true only if both true
Boolean AND

condition1 || condition2 : true only if at least one is true


Boolean OR

!condition : true if only if condition is false


Boolean negation

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 28


homework
1. Based on user input, draw a circle or a square or a rectangle

2. Determine if a number is prime


– program should take as input a number
– expect number to be an integer > 1
– Output: Number is prime if it is,
or number is not prime if it is not

– Hints:
• prime numbers are only divisible by 1 and the number itself
• program will need a loop and conditional execution

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


need of a more general loop
Read marks of students from the keyboard and print the average
• number of students not given explicitly
• 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


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 31


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 32


the while statement flowchart

Previous statement in the program

False
Condition

True

Body

Next statement in the Program


Autumn 2019 CS101@CSE IIT Bombay
a program that does not halt

// infinite loop!
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

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 36


while vs. repeat
while can be
expressed as repeat?

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


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 38


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 39


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 40

You might also like