looping
for loop
// for loop
// for (initialization; condition; increment)
// statement;
// example
int i = 0;
for (i = 1; i <= 5; ++i)
cout << i << endl;
// i only visible in the loop!:
for (int i = 1; i <= 5; ++i){
cout << i << endl;
}
// when using arrays i cant be at maximum the size of the array -1!
// with comma operator
for (int i = 1, j = 1; i <= 5; ++i, j++){
cout << i << endl;
cout << j << endl;
}
range-based for loop
// range-based for loop (Cpp11 or newer, extension!)
// example 1
for (var_type var_name: sequence)
statement; // can use var_name
// example 2
for (var_type var_name: sequence) {
statements; // can use var_name
}
// // example 3
int scores[] = {10, 20, 30};
for (int score : scores)
cout << score << endl;
for (auto score : scores)
cout << score << endl;
// example 4
vector<double> temps = {23.1, 77.1, 90.3, 93.2};
double average_temp = 0;
double running_sum = 0;
for (auto temp: temps)
running_sum += temp;
average_temp = running_sum / temps.size();
while loop
// called pre-test loop
// example 1
i = 1;
while (i <= 5) {
cout << i << endl;
++i; //important!
}
// example 2, get all even numbers from 1 to 10
i = 1;
while (i <= 10) {
if (i % 2 == 0)
cout << i << endl;
++i;
}
// example 3
int scores_2[] = {100, 90, 80};
i = 0;
while (i < 3){
cout << scores_2[i] << endl;
++i;
}
// with boolean flag
// example 4 - input validation - boolean flag
bool done (false);
int number = 0;
while (!done){
cout << "Enter an integer between 1 and 5: ";
cin >> number;
if (number <=1 || number >= 5)
cout << "Out of range, try again" << endl;
else {
cout << "Thanks!" << endl;
done = true;
}
}
do-while loop
// post-test-loop
// do {
// statements;
// } while (expression);
// example 1
int number2 = 0;
do {
cout << "Enter an integer between 1 and 5: ";
cin >> number2;
} while (number2 <= 1 || number2 >=5);
cout << "Thanks" << endl;
// example 2
char selection = ' ';
do {
double width = 0, height = 0;
cout << "Enter width and height separated by a space: ";
cin >> width >> height;
double area = {width * height};
cout << "The area is " << area << endl;
cout << "Calculate another? (Y/N): ";
cin >> selection;
} while (selection == 'Y' || selection == 'y');
cout << "Thanks!" << endl;
continue and break statements
// continue and break statements in the loop
// break - break out from loop completely
// continue - skip rest of the loop/stopping iteration and starting directly into next iteration
// example
vector<int>values = {1,2,-1,3,-1,-99,7,8,10};
for (auto val: values) {
if (val == -99)
break;
else if (val == -1)
continue;
else
cout << val << endl;
}
nested loops
// example - inner loop loops faster
for (int outer_val = 1; outer_val <= 2; ++outer_val)
for (int inner_val = 1; inner_val <= 3; ++inner_val)
cout << outer_val << ", " << inner_val << endl;
// example 2
int grid[5][3] = {};
for (int row = 0; row < 5; ++row ) {
for (int col = 0; col < 3; ++col ) {
grid[row][col] = 1000;
}
}