Loops
Requirements:
Linux Distribution
g++
any text editor
My Setup:
Debian 10
g++ version 6.3.0
pluma
Sometimes you need to repeat a couple functions or statements multiple times.
For this, you would use a looping mechanism. Today i will go over 4 types of
loops. Those include : while, do/while, for, for each.
While :
While loops are simple loops that will repeat until the while condition is
false. You would use this specifically if you are just checking a condition
before going back to the start of the loop and repeating.
int x = 5; while(x < 10){ //execute this code }
Do / While :
Do-while loops are similar to while loops, however the block of code that is
being looped will run atleast once.I modified the first example , and despite
the fact that the while condition immediately returns false, it is still run
atleast once.
int x = 15; do{ //execute this code }while(x < 10);
For:
For loops are used when you need to repeat an action based on an amount of
times rather then checking a condition. This is kind of similar to the
differences between if/else statments to switch statements. The syntax goes:
for ( initialize; check condition; increment).
int arr[20]; for(int i = 0 ; i < 20 ; i++){ arr[i] = i; }
For_each:
For each loops are interesting. They are based off arrays , or pointers to
types. They syntax is for( type x : array/pointer) . This states: For each type
in the array, increment to the next.
int arr[20]; for(int i : arr){ //do stuff with the i variable to manipulate its value in arr }