I've started the exercise but there is something wrong. What I am supposed to do is to
ex1:
Calculate the estimated production of: the squares of single digit natural numbers between 3 and n, if it's known the value of the variable n. The result is not as it should be. Where is the problem ?

 ``1234567891011121314151617`` `````` #include "stdafx.h" #include using namespace std; int main() {int n,i,P=1; cout<<"Please give n"; cout<<"n= "; cin>>n; for(i=3;i<=n;i=i+2) P=P*i*i; cout<

ex 2
g=∑(j=1(j≠3,4,5))^n+{1/2j+3} in power j/3
ex3
z={x/2 + 3∏(2i+1) where i=1 and goes till n, for 2x>m
x/3-2∑(k+x) where k=1 k≠3,4 for 2x≤m
Last edited on
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
 ``12`` ``````cin.get(); cin.get();``````
twice in a row isn't good.
use
 ``12`` ``````std::cin.clear(); std::cin.ignore(10000, '\n');``````

 ``12345678910111213141516171819202122232425`` ``````#include "stdafx.h" #include 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.
Last edited on
@Vidminas

Isn't the use of #include "stdafx.h" necessary in microsoft's visual studio? I'm not sure it was absolutely necessary, but if I recall correctly, I had to include stdafx.h in order to get MSVC to compile at all...
@Bourgond Aries

It wasn't so for me, but I updated the example anyway and I added a step-by-step walkthrough of what happens when the program executes.
Topic archived. No new replies allowed.