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

03 Expressions Statements Control Flow

Statements control program execution and evaluate expressions. Blocks group statements. Expressions return values. Operators act on operands in expressions. Assignment, math, increment/decrement, logical, and relational operators are used to control program flow. Conditionals like if/else and switch allow branching. Loops like while, do-while, and for iterate statements. Functions are reusable blocks of code that take parameters and return values.

Uploaded by

Paul Bryan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

03 Expressions Statements Control Flow

Statements control program execution and evaluate expressions. Blocks group statements. Expressions return values. Operators act on operands in expressions. Assignment, math, increment/decrement, logical, and relational operators are used to control program flow. Conditionals like if/else and switch allow branching. Loops like while, do-while, and for iterate statements. Functions are reusable blocks of code that take parameters and return values.

Uploaded by

Paul Bryan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Statements, Expressions and Control Flow

What is a statement?

controls the sequence of execution, evaluates an expression, or does nothing (the null statement) Basically all lines of code

Block or compound statements

Any place you can put a single statement, you can put a compound statement, also called a block. Non-strictly speaking, we can say that a block of code acts as one statement.

What is an expression?

Anything that evaluates to a value. Expressions are said to return a value.


3.2 PI SecondsPerMinute x = a + b; return value is x y = x = a + b; return value is y

Operators

a symbol that causes the compiler to take an action Operators act on operands. All operands are expressions.

Assignment operator

=
x = a + b;

lvalue term used for an operand that can be on the left side of an assignment operator rvalue ? Example:

x = 35; 35 = x;

// error, 35 not an lvalue

Mathematical Operators

+, -, *, /, %(modulo) Some notes:

subtraction of unsigned integers that lead to negative values can produce unpredictable results beware of division!

23/4 5 23.0/4 5.75

Notes on assignment and math operators

you can put the same variable on the same side of the assignment operator

myVal = myVal + 2;

you can also use a shorthand notation (called the self-assigned addition operator):

myVal += 2; myVal /= 2;

Increment and decrement


c++; c = c + 1; c +=1; c--;

Note: do not use increment or decrement as subexpressions of a larger expression:

((n+2) * (++n)) + 5;

prefix and postfix


postfix: x++; prefix: ++x; When value is not assigned to another variable no effect.

int x = 6, y = 6; int a = ++x; // a = x = x+1 int b = y++; // b = y; y = y + 1; The value of x and y is of course 7. a = 7, b = 6

Precedence

*, /, % +, =, +=, -=, *=, /=, %= Use parentheses to control precedence

Note on Nesting parentheses


Not-so-good: EffortSpent = (((NumDays NumWeekends)

* 24)*(NumSupervisors + NumEngrs)); Better: ActualDays = NumDays NumWeekends; ActualHours = ActualDays * 24; NumPeople = NumSupervisors + NumEngrs; EffortSpent = ActualHours * NumPeople;

Truth

In C++, zero is considered false, all other values are considered true. Note: there is a data type bool whose value can only be TRUE or FALSE. Program flow is controlled by whether a certain condition is TRUE or FALSE.

Relational operators

used to compare whether two numbers are equal, or if one is greater or less than the other.
equals ==

not equals
greater than greater than or equals less than less than or equals

!=
> >= < <=

Examples
int x = 1, y = 2, z = 2, a = 0; 100 < x; // FALSE x==z; // FALSE y<=z; // TRUE a=z; // TRUE???

you can assign it to a variable type bool:


bool result = x==z; int result = x==z; // 1 if TRUE, 0 if FALSE

More precedence

math operators relational operators assignment operators

Logical operators

when you want to ask more than one relational question at a time: is it true that x > y and y>z?
AND OR
NOT

&& ||
!

(x > y) && (y > z) x>y and y>z (x > y) || (y > z) (x > y) or (y > z) !(x > y) is it NOT true that x > y?

More precedence

NOT Mathematical Relational AND OR Assignment

Machine Problem #2
Deadline: June 28, 2010

IF

enables us to branch to different parts of our code by testing for conditions

if (expression) statement;

note that a block can replace any statement:

if (expression){ statement1; statement2; }

Indentation styles
A if (expression) { statements } B if (expression) { statements } C if (expression) { statements }

ELSE
if (expression){

statement;

}
else { }

statement;

Nested IFs
if (expression1) { if (expression2) statement1; else { if (expression3) statement2; else statement3; } } else statement4;

Beware of using unbraced IFs in nested IFs

It can cause by difficult to debug run-time errors

if (x > 10) if (x > 100) cout << "More than 100" << endl; else cout << "Less than 10" << endl;

ELSE IF
if (expression1)

statement1; else if (expression2) statement2; else if (expression3) statement3; else statement4;

Conditional Operator

the only ternary operator; i.e. only operator with 3 terms.


(expression1) ? (expression2) : (expression3)

this reads: if expression1 is true, return the value of expression2; else, return the value of expression3
absValue = a>b ? a-b : b-a;

Practice exercises

Write a program that outputs High if the value of the variable is greater than 10, and Low if otherwise. The variable is of type int and is inputted by the user. Write a program that obtains input from the user a high_value, a low_value and a value from the user. Your program should inform the user if the value is out of range!; otherwise, output thank you!
Enter high value: 10 Enter low value: 3 Enter your choice: 2 value out of range!

Write a program similar to number 1 except that it will inform the user of the 3 following possibilities: a) number <10, b) 10<number<100, c) number>100

Exercises

Write a program that computes the absolute value of the difference of two user inputted integers.

switch

similar to the IF statement. allows multi-way branches. it is less flexible than IF-ELSE because switch statements use constants.

switch
switch (controlling_expression) {

case constant1: statement_sequence_1; break; case constant2: statement_sequence_2; break; default: default_statement_sequence;

note on break statements in switch

if you forget a break statement, your code will continue until a break statement from another case statement is reached or until the end of the switch statement

case A: case a: cout << Excellent <<You need not take the finals; break;

Looping

each loop is called an iteration


while for do-while

while
while (boolean_expression) { }

statement_1; statement_2;

while

example:

int numOfGreetings; cin >> numOfGreetings; while(numOfGreetings > 0) { cout << Hello ; numOfGreetings--; } cout << endl;

do - while
do {

statement_1; statement_2; } while (boolean_expression);

do - while

example:

int numOfGreetings; cin >> numOfGreetings; do { cout << Hello ; numOfGreetings--; } while(numOfGreetings > 0) ; cout << endl;

for
for (initialization; boolean_expr; update) }

{ statement_1; statement_2; ...

for

example:

int numOfGreetings; cin >> numOfGreetings; for (; numOfGreetings > 0; numOfGreetings-){ cout << Hello ; } cout << endl;

for
int numOfGreetings; cin >> numOfGreetings; for (int i=0; i<numOfGreetings; i++){ } cout << endl;

cout << Hello ;

Infinite loops

when exit conditions are not satisfied, the program continues to loop forever your program will hang

break and continue

used to alter the flows of while, do-while and for statements break

ends the nearest enclosing loop

continue

ends the current loop iteration of the nearest enclosing loop

Practice exercises

Write a program that finds and prints all of the prime numbers between 3 and 100. Write a program which takes a single integer from the user and displays a "pyramid" of this height (between 1-30) made up of of "*" characters on the screen.

6: ** **** ****** ******** ********** ************

Exercises

The LeVan Car Rental Company charges 30PhP/km if the total mileage is less than 100km. If the total mileage is over 100, the company charges 30PhP/km for the first 100 km, then it charges 20PhP for any additional km over 100. The company gives a 500PhP discount for total mileage more than 500km. Write a program so that the clerk has to input the number of kilometers and the program will output the total price

READING ASSIGNMENT

Functions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy