Iteration

Source Code from Notes


Example 1

This example reverses the digits of a number, and prints out the number in the reverse order. Each digit is displayed as it is extracted by the program. The final call to \fC\s8printf\fR\s0 returns the cursor to the next line as the newline character has not been included within the loop.


#include <iostream.h>

main()
{
        int     number, right_digit;

        cout << "Enter your number\n";
        cin >> number;

        while (number !=0)
        {
                right_digit = number % 10;
                cout >> right_digit;
                number /= 10;
        }

	cout << "\n";
}


Example 2

This example checks that the input value is in the desired range


#include <iostream.h>

main()
{
        int     number;

        const int min = 1;
        const int max = 100;

        number = 0;

        while ( number < min || number > max)
        {
                cout << "Enter a number in the range 1 to 100\n";
                cin >> number;
        }
        cout << "the number is in range\n";
}


Example 3


#include <iostream.h>

main()
{
        char    letter;

        cout << "Press Y to continue\n";
        do
        {
                letter = getchar();
        } while (letter != 'y' && letter != 'Y');

        cout << "program execution will continue\n";

}


Example 4

The following program creates a conversion table for converting inches to centimetre. The values in the table are calculated for inches in the range 1 to 10 in half inch increments.

#include <iostream.h>

main()
{
        float   inches,centimetres;

        // print table header
        cout << "inches\t centimetres\n";

        //calculate and print table entries
        for (inches = 1; inches <=10 ; inches += 0.5)
        {
                centimetres = 2.54 * inches;
                cout << inches << centimetres << "\n";
        }


}


Back to Main Page for Lecture 4