Absolute Beginners C++


Lesson 9 - For statement

9.1 For statement

// ex9-1.cpp - for statement
#include <iostream>
using namespace std;
int main()
{
    cout << "Enter a number : ";
    int ival;
    cin >> ival;
    for (int i=1;i<=5;i=i+1)
        cout << i << "x" << ival 
             << "=" << i*ival << endl;
    return(0);
}
ex9-1
Enter a number : 5
1x5=5
2x5=10
3x5=15
4x5=20
5x5=25
Example ex9-1 introduces a useful shorthand for a common use of the while statement: another looping statement called the 'for' statement.  The for statement has the syntax: 
    for (statement1;condition;statement2) {
        statement;
        statement;
        ...
    }
In terms of the while loop we met in lesson 7, this for statement does just this processing: 
 
    statement1;
    while (condition) {
        statement;
        statement;
        ...
        statement2;
    }
That is statement 1 is executed first, then the condition is evaluated.  Then while it is the case that the condition is true, the block of statements is executed.  Finally, just before the condition is executed again, statement2 is executed.  In the example, the for loop is constructed to execute a block of statements exactly 5 times.  The variable i is set to 1 in the first statement, then it is compared with 5, if the value of i is less than or equal to 5 then the print statement is executed.  Then the value of i is increased by 1 and the condition test repeated.  For loops are used in preference to while loops in circumstances when the number of repetitions is predictable.  The use of a variable (i in the example) to keep count of the number of times the loop is executed is also very common. 

9.2 For statement with function 

// ex9-2.cpp - for statement with function
#include <iostream>
#include <iomanip>
using namespace std;
void factorial(int n)
{
    double dval=1;
    for (int i=2;i<=n;i++) dval = dval * i;
    cout << "factorial(" << i << ")=" 
         << setiosflags(ios::scientific) 
         << dval << endl;
}
int main()
{
    cout << "Enter a number : ";
    int ival;
    cin >> ival;
    for (int i=1;i<=ival;i++) factorial(i);
    return(0);
}
ex9-2
Enter a number : 4
factorial(1)=1
factorial(2)=2
factorial(3)=6
factorial(4)=24
Example ex9-2 uses a function to report the factorial of a number (the factorial of a number is the product of all the integers less than or equal to the number). The function uses a for loop to calculate the factorial, and the main program uses a for loop to call the factorial function for a range of values.  This example also shows how a function that does not return a value can be declared as type void, and that a void function can be called as a statement in its own right.

9.3 For loop with block 

 // ex9-3.cpp - for statement with block
#include <iostream>
using namespace std;
int main()
{
    // get a value to test for primality
    cout << "Enter a number : ";
    int ival;
    cin >> ival;
    // use 'remainder' to keep part left over after division
    int remainder=ival;
    // loop up to square root of number while no exact divisor
    for (int i=2;(i*i<=ival)&&(remainder!=0);i++) {
        // get remainder after division
        remainder = ival - ((ival/i)*i);
        // if zero then print divisor
        if (remainder==0) 
            cout << ival << " can be divided by " << i << endl;
    }
    // remainder will be non-zero if prime
    if (remainder!=0)
        cout << ival << " is prime" << endl;
    else
        cout << ival << " is not prime" << endl;
    return(0);
}
ex9-3
Enter a number : 7
7 is prime
ex9-3
Enter a number : 15
15 can be divided by 3
15 is not prime
Example ex9-3 shows how a for loop can be used with a complex conditional expression.  In this example, an integer is input and then tested to see if it is a prime number (a number is prime if its only factors are 1 and the number itself).  To test for primality, a for loop tests a range of integer values (in the variable i) to see if they divide into the number ival without any remainder, i.e. to test if i is a factor of ival.  The foor loop terminates after either one of two conditions.  Firstly there is a test that i has not grown too big.  We only need to test values of that are smaller or equal to the square root of ival, or to put it another way that i squared is less than or equal to ival.  The second termination condition is when any factor is found, i.e. when any division has a remainder of zero.

9.4 Exercises 

a. Write a program (timestab.cpp) that prints a multiplication table for numbers up to 9 times 9, as in: 
    timestab
       1   2   3   4   5   6   7   8   9
       2   4   6   8  10  12  14  16  18
       3   6   9  12  15  18  21  24  27
    etc
       9  18  27  36  45  54  63  72  81
b. Write a program (ftable.cpp) that prints a table of Fahrenheit to Centigrade conversions as in exercise 8.4a but using a for loop. 

c. Write a program (perfect.cpp) that prints the values of all perfect numbers less than 10000. A perfect number is a number that is numerically equal to the sum of its divisors, i.e. 6 is perfect since the divisors of 6 are 1, 2 & 3. 

    perfect
    6 = 1+2+3
    28 = 1+2+4+7+14
    496 = 1+2+4+8+16+31+62+124+248
    8128 = 1+2+4+8+16+32+64+127+254+508+1016+2032+4064
 


© 1999 Mark Huckvale University College London