hitmill.com
hitmill home

 

The For Loop, C++ Tutorial


 

This C++ for loop tutorial is written for beginning C++ students without previous C++ programming experience. There are C++ questions about the for loop inside the tutorial, for the students to answer and many code examples and explanations about the conditions of a C++ for loop. Some of the for loop examples have an if/else structure within the for loop structure...
 
The format of a for loop is:

for(initializing expressions)
{
   statements; // what the loop will do
}
 

Prior to the for loop, declare a variable, such as an integer. This variable will be used for the
three initializing conditions of the for loop:
· Telling the compiler at which value to begin
· Telling the compiler at which value to stop
· Incrementing or decrementing the loop (makes the loop
   move to the next value for code processing)

 

Counting from 0 to 10
// Beginning Students
// Code Example:
// Counting From 0 To 10
 
#include
using namespace std;
 
void main()
{
  // declare a variable
  int i;
  for(i= 0; i < 11; i++)
    cout << i << endl;
}
/* This opens the comment:
This is the generated output:
0
1
2
3
4
5
6
7
8
9
10

 
*/ This closes the comment

using namespace std; is for the cout statement so you do not have to type std::cout everytime that cout is used in a program.
void main() was used since I am not returning a value.
The letter i is the one I normally use when using an integer in a for loop but any other letter or variable name will work just as well.
The reason that I like to use the i, is just from habit and seeing it most often used in textbooks for the for loop conditions. This makes for easier readability of my code. Using a longer variable name like number, seems a bit awkward in a for loop's condition statements:

for(number = 0; number < 11; number++)
just seems "cluttered with longer variable name". It is still a matter of preference and it would not have been wrong to declare int number instead of int i.
· i= 0 told the compiler you are starting at 0.
· i < 11 told the compiler where to stop the loop
· i++ means i = i + 1 (which increments the loop, moves the loop   to the next i value.

Counting backwards with a for Loop

· Tell the compiler where to start
· Tell the compiler when to stop
· Decrement the loop: j = j - 1 in its shorter form is j--
 

#include
using namespace std;
 
void main()
{
  // declare a variable before starting
  int i;
  for(i=10; i > -1; i--)
  {
    if(i == 0)
      cout << "Blast Off!" << endl;
    else
      cout << i << endl;
  }
  // do not return anything when
  // void main() is used
}

 

The above loop starts counting backwards at 10; loop stops when the i value hits -1;
Each step of the loop is decremented by -1, so after 10 is output, then 9 is output.
If the i value hits 0, instead of printing 0 on the console, you will see the words "Blast Off!" [and end the line] because of the if/else statement.
You can output a string to the console when the integer object has a zero value. It says, if i is 0, then print "Blast Off!", otherwise output i and end the line.
You do not need to use the {} curly braces for the if statement or the else statement when only one statement is used.
The for loop used the {} curly braces because that loop has more than one statement.
 
Don't confuse conditions with the for loop statements. The conditions are inside the parentheses and tell how the loop will run and the statements outside the parentheses tell what the loop will do to the object types, in this case the integer object i

Shortcuts for coding increments and decrements

j = j + 2 can be written j+=2;   (adds 2 to the value of j)
j = j - 2 can be written j-=2;   (substracts 2 from the value of j)
k = k + 1 can be written k++;   (adds 1 to the value of k)
k = k - 1 can be written k--;   (substracts 1 from the value of k
m = m + 5 can be written m+=5   (adds 5 to the value of m)
 
Analyze This Loop:


int k;
for (k = 0; k < 51; k +=10)
  cout << k << endl;

 
Review Exercises

(Refer to the code above in the shaded box..)
· At what value of k does the for loop begin?
· What is last value of k the for loop will output?
· By what value of k does the for loop increment each step?
 
· Write the output of the for loop.
 
- Write the Output of the Following Code:


 
int n;
int stop = 3;
int start = 8;
cout << "start on 8" << endl;
for(n = (start-1); n >= stop; n--)
{
  if(n=stop)
    cout << "stop on " << n << endl;
  else
    cout << "down to " << n << endl;
}

 
Compiler Errors, Infinite Loops

Typical student errors in the for loop structure are not putting in the proper semicolon (;) after the first and second conditions, inside the parentheses or accidentally reversing the < or > symbols When a loop is counting forward, it makes sense that the loop should stop somewhere less than some value, or it will count forever… an infinite loop.
 
For example,

Count from 20 to 45 by 5's:
 
int k = 0;
for(k = 20; k < 50; k+=5)
cout << k << endl;

Each number will be on a separate line because of the endl [end line] statement. cout << endl; is an empty line but cout << k << endl; is the output of the value of k, then a newline. Think of endl; as a line break. Nothing comes after it on that line so any other new output must be on another line.
 
If by accident, a student had coded:

for(k = 20; k > 50; k+=5)

where would the loop stop?
It begins at 20, adds 5 so k=25, and next time k=30, then k=35 and when k=50 the stopping place is k "greater than" 50, so k gets 5 more added to it... forever. (This is called an infinite loop.)
 
The way to stop an infinite loop varies between compilers. When I was using VC++ 6.0 on a Windows 98SE machine, I could stop an infinite loop by pressing the Break or Pause key but not all compilers work the same way to stop an infinite loop. Check with your instructor about your own particular compiler and ask how to stop infinite loops.
 
When a for loop is incrementing (adding), make sure that the middle condition that stops the loop is NOT a > greater than symbol.
 
Now consider a decrementing loop. Count from 50 to 20 by 5's:

int k;
for(k=50; k>19; k--)
cout << k << endl;

 

This code will count from 50 backwards by 5's and stop at 20 because the middle condition is k greater than (>) 19 for where the backwards counting should stop.

So, when a for loop is decrementing (subtracting), make sure that the middle condition which stops the loop has NO < less than symbol, but is a greater than > symbol, so that the loop will stop.


 

 

 

 
Contact Webmaster
 
Updated - 23 Jan 2009

© hitmill.com
All Rights Reserved