Wednesday
C++, Programming & DevelopmentAdvanced Control Flow - For Loop
Lets say we wanted to repeat an operation multiple times on a set of data. Do we really want to write the code for it multiple times? Of course not. This is where loops come into play.
The Foor Loop
How would you calculate the factorial of 1-10 without using loops? Below would be one of many solutions.
cout << "!1 = " << factorial << endl;
factorial = factorial * 2;
cout << "!2 = " << factorial << endl;
factorial = factorial * 3;
cout << "!3 = " << factorial << endl;
factorial = factorial * 4;
cout << "!4 = " << factorial << endl;
factorial = factorial * 5;
cout << "!5 = " << factorial << endl;
//Ok! That’s a lot of work!
Would print out
!2 = 2
!3 = 6
!4 = 24
!5 = 120
Imagine doing this simple operation up to 100.
Structure of the for loop
Below is the structure of a for loop.
{
statements to be executed
}
Don’t worry if you don’t understand, below you’ll see an example.
Below is a “for loop” that will perform the same operation and can be easily manipulated to perform the previous operations from 1-10 and even to 100 with simple ease.
int factorial = 1;
for ( int i = 1; i <= number; i++ )
{
//Multiplies the previous factorial value by the index value to calculate the next factorial
factorial = factorial*i;
cout << "!" << i << " = " << factorial << endl;
}
Breaking down the For Loop
Below is a detailed explanation of how the previous code works.
//This variable pertains to this for loop and will reach out of scope once the loop finishes executing. This variable can be though of an index. Since we are finding the values of the factorial in increments of one, its obvious to start with 1.
int i = 1;
//This is the condition in which this loop will execute until it is no longer true. Our number is 10, so while our index value is less than our number, this loop will execute.
i <= number
//This increments our index value by 1 so we can cover all numbers from 1-10. We can also use statements such as (i += 2) , ( i– ) , ( i *= 2 ) , and more.
i++
Let’s break this down, this for loop executes these lines of code.
int i = 1;
factorial = factorial * i; // !1 = 1 * 1 = 1
i++; //i = 2;
factorial = factorial * i;// !2 = 2 * 1 = 2
i++; //i = 3;
factorial = factorial * i;// !3 = 3 * 2 = 6
//and so on…until our condition is met
How to master For Loops
With practice! Write down the steps taken. Try to change the values of the variables to see what happens.
Some examples to try out can be the following.
Example 1: Counting from 1 to 100
Example 2: Counting from 100 to 1
Example 3: The classic Triangle of Stars
***
**
*
*Hint You will need to use two for loops instead of one. Can you figure out how? Need help? Visit the Forums. Registration is free, and you can ask your questions and get answers!

