Loops

A for loop is used when your loop is to be executed a known number of times. This is most commonly used when you want to naturally count items one at a time. The while loop is similar to a for loop, only that with a while loop, the number of iterations is not fixed. You can construct a while loop to have no executable iterations.

Below is an example of a For loop to print out the counting numbers (up to a user-defined value).
Pascal example of a for loop.

include <iostream>
using namespace std;
int main()
{
   int i, limit;
   cout << "\nPlease enter a limit: ";  // "\n"  same as endl  
   cin >> limit;
   for (i = 1; i <= limit; i++)
         cout << " " <<  i ; 
   return 0;
}

In this sample program, the for loop is executed the same number of times as the value of the variable limit. If I input 5 as the value for limit, the output for the program becomes: 1 2 3 4 5

The same example, now using a while loop.
Pascal example of a while loop

#include <iostream>
using namespace std;
int main()
{
   int i = 1, limit;
   cout << "\nPlease enter a limit: ";
   cin >> limit;
   while (i <= limit) {
         cout << " " <<  i ;
         i++;     // equivalent to i = i + 1
   }
   return 0;
}

This code will give us exactly the same result as in our for loop, but now after executing each iteration of the loop, it checks the new value of i, and compares it to the value defined in limit. The loop is finished when i > limit.

So, if I entered 5 again as the value of limit, the output would be: 1 2 3 4 5

After the 5th iteration, i has a value of 6, which is greater than 5. The while loop will end at this point in the program.


This page has been accessed     times.
Last modified: Friday, 21-Aug-2020 15:28:14 CST
Copyright 2000 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material