-
Notifications
You must be signed in to change notification settings - Fork 153
Control Statements
An executable program consists of a series of statements/instructions that the computer executes in order. That is each line of code is executed from top to bottom sequentially. Control statements define when the default flow of the program should be disrupted. Either by repeating, or skipping instructions:
if(iter >= maxiter){
cout<< " Number of iterations exceeded\n";
exit(2);
}else {
cout << "iter = " << iter << endl;
}switch(val){
case 0:
cout << " Zilch\n";
case 1:
cout << " Uno\n";
case 2:
cout << " Dos\n";
case 3:
cout << " Tres\n;
default:
cout << "A bunch";
break;
}int iter = 0;
int maxiter = 10;
while(iter < maxiter){
x_coord += 2.0;
iter++;
}Note the values of iter and maxiter must be initialized outside the loop. Also note that if iter is not incremented inside the loop body this would result in a infinite loop, since the condition would always be true!
do-while: Similar to while, but the instructions are always evaluated at least one time, since the condition is not checked until the end
do {
x_coord += 2.0;
iter++;
} while(iter < maxiter);for Loop: One of the most common and powerful control statements. Defines and intital state, a condition, and increment. Loop continues incrementing until the condition is no longer true.
Standard for loop:
for(int i = 0; i < max; i++)
{
cout<< " iter = "<< i << endl;
}The for loop also has several c++ only variants involving what are called iterators and are very powerful when used in combination with the Standard template library (stl) containers.
For loop using std::vector<double>::iterator
#include <vector>
std::vector<double> vec = {1.0,2.0,3.0,4.0};
cout << " vec = { ";
for(std::vector<double>::iterator it = vec.begin();
it != vec.end(); ++it){
cout << " " << *it <<" "; \\ it is a pointer to an element of the vector
\\ we use the *operator to get the value pointed to by it
}
cout << " }\n"; Range based for loop. Here is a shorthand for the example above but we will capture the value rather than a pointer by declaring the loop variable as a reference.
#include <vector>
std::vector<double> vec = {1.0,2.0,3.0,4.0};
cout << " vec = { ";
for(double& val: vec}
{
cout << " " << val << " ";
}
cout << " }\n";for(int i = 0; i < max; i++)
{
energy += 2.0;
cout << " iter = " << i << endl;
if(energy > 10.0) break;
}
This for loop will when energy gets larger than 10.0 even if i is less than max!