Flow of Control (if, else, while, for)
Saloni Goyal
Posted on November 21, 2020
Branching and loops are at the heart of most calculations and decisions in your program.
Normally code is executed top to bottom. A number of keywords change this:
- (For branching)
- if
- else
- (For looping)
- while
- for
These keywords work with conditions that are logical expressions that can be true or false
(x > 0)
(y - 2 < b)
Here, parenthesis or round brackets are necessary around conditions in C++.
Operators
There are operators to compare two operands -
> >= < <= == !=
Note:
==: two equal signs are used for comparison
=: single equal sign in used for assignment
!: means 'not'
if
- condition must always have ()
- statements will run only if condition is true
Code to compare two numbers
Garbage In, Garbage Out
Type rules apply here as well. Giving decimal value confuses the parser and secondNumber is assigned value 0.
else
- an else can only be used right after an if
- here else statements run if condition is false, i.e. i >= j.
while
- keeps going as long as the condition is true
- curly braces are optional for single line statements but use them anyway
- a while loop may not run at all if the condition is never true
- loop body must change something about the condition, otherwise we may have an infinite loop
Comparing two numbers until user says otherwise
Garbage In, Garbage Out
for
Traditional for loop has three parts separated by semi-colons (not commas) -
- initialiser (typically also declares the variable)
- continue condition
- incrementer
Loop body doesn't have to change anything about the condition if the incrementer does.
Tip: Use a debugger to see which statement in executed.
TO-DO: Write a "Guess the Number" game where you hard code a number into code and then prompt user to guess the number. If the guessed number is lesser/greater than the hard coded number, let the user know. If the user guess correctly, prompt success response and exit.
Code for reference.
Other Flow of Control Keywords
- switch
- range based for - used with Collections
- break - makes a loop stop early
- continue - makes a loop skip some of its processing
- do (almost never used)
- goto (almost never used)
Please leave out comments with anything you don't understand or would like for me to improve upon.
Thanks for reading!
Posted on November 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.