M5- GUIDE
M5- GUIDE
STUDY GUIDE
MODULE 5
CONTROL FLOWS
Control flow:
• Sequencing: order of execution
• Selection (also alternation): generally in the form of if or case statements
• Iteration: loops
• Recursion: expression is defined in terms of (simpler versions of) itself
Expression Evaluation
Precedence, associativity
• C has 15 levels - too many to remember
• Pascal has 3 levels - too few for good semantics
• Fortran has 8
• Ada has 6
• Ada puts and & or at same level
• Lesson: when unsure, use parentheses!
Operators
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
PROGRAM:
public class DemoTest
{ public static void main(String[] args) {
System.out.println(4 + (5 * (6 / 3)));
System.out.println(4 + ((5 * 6) / 3));
System.out.println(1 + 2 - (3 * (4 / 5)));
System.out.println(1 + 2 - ((3 * 4) / 5)); } }
Expression Evaluation
Operator precedence levels in Fortran, Pascal, C, and Ada. The operators from the
figure group most tightly.
INFIX: a op b
for example, in C++, a + b really calls operator+(a,b)
- Operators are written in-between their operands. This is the usual way we write expressions.
An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and
C together, then multiply the result by A, then divide by D to give the final answer."
The expression A + B * C + D can be rewritten as ((A + (B * C)) + D) to show that the
multiplication happens first, followed by the leftmost addition. A + B + C + D can be written as
(((A + B) + C) + D) since the addition operations associate from left to right.
PREFIX: op a b or op(a,b)
Operators are written before their operands. +XY
Example: standard in most we have seen
Example: / * A + B C D
- operators are evaluated left-to-right. Operators act on the two nearest values on the
right. I have again added (totally unnecessary) brackets to make this clear:
(/ (* A (+ B C) ) D)
A * ( B + C ) / D equivalent in Infix
In Lisp: (* (+ 1 3) 2)
POSTFIX: a b op
• XY+
• Operators are written after their operands.
• A B C + * D / the postfix equivalent of the infix A * ( B + C ) / D
• Least common - used in Postscript, Forth, and intermediate code of some compilers
• Also appears in C (and its descendants) and Pascal examples, such as ++value in C and
the pointer dereferencing operator (^) in Pascal
Examples:
(A + B) * (C + D) *+AB+CD AB+CD+*
Expression Evaluation
Model
Program:
*Java Examples
int a = 5; Output:
int b = a;
b += 10; a=5
System.out.println("a = " + a); b = 15
System.out.println("b = " + b);
Obj a = new Obj(); Output:
Obj b = a;
b.change(); true
System.out.println(a == b);
*
Java Examples
String a = "hi ";
String b = a;
b += "world";
System.out.println("a = " + a);
System.out.println("b = " + b);
Output
a = hi
b = hi world
Assignment Shortcuts
ASSIGNMENT
– statement (or expression) executed for its side effect - key to most programming
languages.
– assignment operators (+=, -=, etc)
• Handy shortcuts
• avoid redundant work (or need for optimization)
Assignment
SAMPLE ASSIGNMENT
variable = expression ;
Multiple Assignment
variable = variable = expression ;
Example:
int number, total;
float start_x, start_y;
...
number = total = 0;
start_x = start_y = 100.0;
Shorthand Assignment
Expression Evaluation
Several languages outlaw side effects for functions
• easier to prove things about programs
• closer to Mathematical intuition
• easier to optimize
• (often) easier to understand
But side effects can be nice
• consider rand()
Use of goto is bad programming practice if the same effect can be achieved using different
constructs.
While hotly debated after this, gotos have essentially disappeared from modern programming
language.
• Getting rid of goto was actually fairly easy, since it was usually used in certain ways.
– Goto to jump to end of current subroutine: use return instead
– Goto to escape from the middle of a loop: use exit or break
– Goto to repeat sections of code: loops
Explanation: In the above example, Vote and NoVote are labels. When the input is >= 18, the
goto statement is transferring the control to label – Vote, otherwise it transfers the control to
label-NoVote.
10 X = X + 1
20 PRINT X
30 GOTO 10
10 X = X + 1
20 PRINT X
30 IF X < 10 GOTO 10
Selection
Standard if-then-else statement
if ... then ...
else ...
Multi-way if-then-else statement
if ... then ...
elsif ... then ...
elsif ... then ...
...
else ...
Switch statement
switch ... of
case ...: ...
case ...: ...
Selection
Selection: introduced in Algol 60
– sequential if statements
if ... then ... else
if ... then ... elsif ... else
– Lisp variant:
(cond
(C1) (E1)
(C2) (E2)
...
(Cn) (En)
(T) (Et) )
If condition
• If condition then statement else statement
– Nested if statements have a dangling else problem
• If … then if … then … else …
• Algol 60
– Doesn’t allow “then if”
• Pascal
– Else associates with closest unmatched then
• Perl
– Has a separate elsif keyword (in addition to else and if)
– “else if” will cause an error
Evaluation
Short-Circuit Evaluation of Boolean Expressions
(and a b): If a is false, b has no effect on the value of the whole expression.
(or a b): If a is true, b has no effect on the value of the whole expression.
Selection
Selection: Case/Switch
Code Optimization
do {
item = 10;
value = value + item;
} while(value<100);
In this optimization, the compiler takes in the intermediate code and transforms a part of the
code that does not involve any CPU registers and/or absolute memory locations.
Item = 10;
do {
value = value + item;
} while(value<100);
The given code should not only save the CPU cycles, but can be used on any processor.
Iteration
Loops
• Two (2) kinds of iterative loops
– Enumeration-Controlled Loop
• Executed once for every value in a finite set
– Logically-Controlled Loop
• Execute until some boolean condition
– Depends on value altered in the loop
Enumeration-Controlled Loop
• Early Fortran:
• do 10 i = 1, 50, 2
• ...
• 10: continue
• Equivalent?
• 10: i = 1
• ...
• i=i+2
• if i <= 50 goto 10
Enumeration-Controlled Loop
Iteration
Enumeration-controlled: originated in Fortran
– Pascal or Fortran-style for loops
do i = 1, 10, 2
…
enddo
– Changed to standard for loops later, eg Modula-2
FOR i := first TO last BY step DO
…
END
Recursion
RECURSION
• equally powerful to iteration
• mechanical transformations back and forth
• often more intuitive (sometimes less)
• naïve implementation less efficient
• no special syntax required
• fundamental to functional languages like Scheme
Sample Recursion Program
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result); }
int sum(int num) {
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Execution:
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to
the sum()function. This process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of
integers to the main() function.
Sample Program:
#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n)); return 0; }
long int multiplyNumbers(int n) {
if (n >= 1) return n*multiplyNumbers(n-1);
else return 1;
}
Recursion: Slower?
• Many criticize that recursion is slower and less efficient than iteration, since you have to
alter the stack when calling a function.
• This is a bit inaccurate. Naively written iteration is probably more efficient than naively
written recursion.
• In particular, if the recursion is tail recursion, the execution on the stack for the
recursive call will occupy the exact same spot as the previous method.
Recursion
• TAIL RECURSION
Tail recursion is a special kind of recursion where the recursive call is the very last thing in the
function.
It's a function that does not do anything at all after recursing.
No computation follows recursive call
Recursion
• Even if not initially tail recursive,
simple transformations can often
produce tail-recursive code.
• Known as continuation-passing.