DEV Community

Cover image for Flow of Control (if, else, while, for)
Saloni Goyal
Saloni Goyal

Posted on • Updated on

Flow of Control (if, else, while, for)

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

Alt Text

  • condition must always have ()
  • statements will run only if condition is true

Code to compare two numbers

Alt Text

Garbage In, Garbage Out

Alt Text

Type rules apply here as well. Giving decimal value confuses the parser and secondNumber is assigned value 0.

else

Alt Text

  • an else can only be used right after an if
  • here else statements run if condition is false, i.e. i >= j.

while

Alt Text

  • 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

Alt Text

Garbage In, Garbage Out

Alt Text

for

Alt Text

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!

Top comments (0)