Kamis, 12 Januari 2012

Repetition Statement: The For Loop in c++



To understand this you must first go through The While loop in c++.
The below program, Program 1 does the same thing that the Program 1 of previous chapter The While Loop does. An integer i is declared and then three expression of the loop: initializer, loop-test and counting expression, all are passed as parameters in for loop. The variable i is initialized to 0 then it will test the condition whether the value of i is less than 10. If the condition is true, the body of loop will execute. The incrementation statement will be last statement to be executed by the for loop.
// Program 1

#include

using namespace std;

int main ()
{
int i;

    for (i=0; i<10; i++)
{
cout << i << endl;
}

    return 0;
}

If you are just going to use the variable within the body of loop, then better declare it in the for loop itself. This will make your program more reliable. The below programs declare variable in the for loop.


// Program 2

#include

using namespace std;

int main ()
{
for (int i=8; i<=80; i+=8)
cout << i << endl;

    return 0;
}


// Program 3

#include

using namespace std;

int main ()
{
for (int i=1; i<=20; i++)
{
if (i%2==0)
cout << i << "is an even number." << endl;

        else
cout << i << "is an odd number." << endl;
}

    return 0;
}

The operator "%" is called the remainder/modulo operator as already been described in Mathematical Operators. The statement i%2==0 simply means that the remainder of i divided by 2 equals to 0.


// Program 4

#include
#include

using namespace std;

int main ()
{
cout << "Number " << "Square " << "Cube" << endl;

    for (long i=1; i<=10; i++)
{
cout << setw (2) << i << setw (8)
<< i*i << setw (8) << i*i*i << endl;
}

    return 0;
}


// Program 5

#include
#include

using namespace std;

int main ()
{
int number;

    cout << "Enter a number to get its multiplication table: ";
cin >> number;
cout << endl;
cout << "-------------" << endl;

    for (int i=1; i<=10; i++)
{
cout << number << " x " << setw (2) << i << " = "
<< setw (3) << number*i << endl;
cout << "-------------" << endl;
}

    return 0;
}


Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


View the original article here



Peliculas Online

0 komentar:

Posting Komentar