Fahmy Arsyaad - 1 year ago 37

C++ Question

I have a task from my teacher,like :

x^2 + y^3 = z

x filled only with odd

y filled only with even

`#include <stdio.h>`

#include <string>

#include <iostream>

using namespace std;

int x,y,z;

int main(){

for (x=1;x<=20;x++){

if ((x%2==1)&&(y%2==0)){

for (y=1;y<=20;y++){

if ((x%2==1)&&(y%2==0)){

z = (x*x) + (y*y*y);

cout << "x^2 + y^3 =" <<z <<"\n";

}

}

}

}

}

I try to make my own code like above ,but the only one loop is Y , x stand still with 1.

I want to make x to be looping too. What should i do?

My output expectation would be like :

`1^2 + 2^3 = 9`

3^2 + 4^3 = 71

5^2 + 6^3 = 241

7^2 + 8^3 = 561

9^2 + 10^3 = 1081

11^2 + 12^3 = 1849

13^2 + 14^3 = 2913

15^2 + 16^3 = 4321

17^2 + 18^3 = 6121

19^2 + 20^3 = 8361

PS. Im sorry with my bad english :D

Answer Source

This is what you have:

```
int main(){
for (x=1;x<=20;x++){
if ((x%2==1)&&(y%2==0)){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
}
```

The problem is the first `if ((x%2==1)&&(y%2==0)){`

check.

After the inner for loop is completed, the value of `y`

will be 21. Hence, the above conditional evaluates to `false`

no matter that the value of `x`

is. As a consequence, the inner for loop is executed only once. You need to remove that first `if`

statement.

```
int main(){
for (x=1;x<=20;x++){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
```

**Update, in response to OP's comment**

Looks like you need much simpler code.

```
int main(){
// Start with x = 1 and increment x by 2. It will be always be odd
for ( x = 1; x <= 20; x += 2 ){
// No need to create another loop. y is simply x+1
// Since x is odd, y will be even.
y = x+1;
// Compute the result and print it.
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" << z <<"\n";
}
}
```