Your code is very hard to read. In the example you posted, you lack a bracket
}
after
return 0;
to end main.
Just a tip:
i = i + 2;
can be written as
i += 2;
writing
twice in a row isn't good.
use
1 2
|
std::cin.clear();
std::cin.ignore(10000, '\n');
|
Your example, spaced out:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include "stdafx.h"
#include <iostream>
int main()
{
using std::cout; using std::cin; using std::endl;
int n, i, P = 1;
cout << "Please give n:" << endl;
cout << "n = ";
cin >> n;
for ( i = 3; i <= n; i += 2 )
{
P = P * i * i;
}
cout << P;
cin.clear();
cin.ignore(10000, '\n');
return 0;
}
|
As far as I understand you want your program to work like this:
Please give n:
n = 5
9, 16, 25
|
Am I right?
Try to think about what happens as the program runs, while looking at the code.
P
is 1 from the beginning, then the program asks the user what is
n
.
If the user enters 5,
n
becomes 5.
Then the
for ( i = 3; i <= n; i += 2 )
loop executes.
Replacing the letters by numbers
P = P * i * i;
becomes
P = 1 * 3 * 3;
so P is 9.
Then the condition
for ( i = 3; i <= n; i += 2 )
is checked again but this time
i
is 5. Since
i
is equal to
n
the loop executes once more.
This time
P = P * i * i;
becomes
P = 9 * 5 * 5;
so
P
is 225.
Then the condition
for ( i = 3; i <= n; i += 2 )
is checked again.
This time
i
is 7, so the loop doesn't execute as it's not less than or equal to
n
.
Then
P
(225) is output on the screen.