Setting values while looping

I want to know what's the best way to set values to int or double while looping when you want to change on each loop.So basically I'm having issue when I try to set a value for x in the way I'll show, It will sir the same value for one loop I want to do instead of the others as well.

My issue is I think I have the wrong placement because all I get is:
1
1
1

Instead of:
1
2
3


1
2
3
4
5
6
7
8
9
10
11
int n;
for ( n = 1; n <= 3; n++)
{
  If (n = 1)
    x = 1;
  Else if ( n = 2)
    x = 2;
  Else 
    x = 3;
  cout << x << end;
}
closed account (LA48b7Xj)
If I understand what you are asking...

1
2
3
4
5
6
7
8
9
10
11
12
13
int x;

for(int n = 1; n <= 3; n++)
{
    if(n == 1)
        x = 1;
    else if (n == 2)
        x = 2;
    else
        x = 3;

    cout << x << endl;
}


You were using assignment '=' instead of equality '==' operators
Last edited on
C++ is case sensitive, so the compiler should be throwing errors left and right.
if (n = 1)
A pair of equals signs for equality.
if (n == 1)

cout << x << end;
Spelling error. Consider using "\n" opposed to std::endl.

Why not just do this?
1
2
3
for( int n = 1; n <= 3; n++ ) {
    std::cout << n << "\n";
}
Last edited on
Topic archived. No new replies allowed.