Loops

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.

[sourcecode language=’cpp’]
int x = 5;
while(x < 10){
//execute this code
}
[/sourcecode]

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.

[sourcecode language=’cpp’]
int x = 15;

do{

//execute this code

}while(x < 10);
[/sourcecode]

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).

[sourcecode language=’cpp’]

int arr[20];

for(int i = 0 ; i < 20 ; i++){
arr[i] = i;
}

[/sourcecode]

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.

[sourcecode language=’cpp’]

int arr[20];

for(int i : arr){
//do stuff with the i variable to manipulate its value in arr
}

[/sourcecode]

 

Leave a Reply