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)
- (For looping)
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++.
There are operators to compare two operands -
> >= < <= == !=
==: two equal signs are used for comparison
=: single equal sign in used for assignment
!: means 'not'
- condition must always have ()
- statements will run only if condition is true
Type rules apply here as well. Giving decimal value confuses the parser and secondNumber is assigned value 0.
- an else can only be used right after an if
- here else statements run if condition is false, i.e. i >= j.
- 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
Traditional for loop has three parts separated by semi-colons (not commas) -
- initialiser (typically also declares the variable)
- continue condition
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.
- 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!