Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop problem
#1
Hey

Why doesn't this work:
PHP Code:
#include <iostream.h>
int main() {
   
int x 0;
   
int i;
   for (
1<= 100i++)  {
     
+= i;
   }
   
cout << << endl;
   return 
0;


For 'x', I should be getting the same as 'i' (1 going down to 100) but I get 5050.

Does anyone know what the problem is?

P.S - I'm learning from a book, so any mistakes are Jeff Cogswell's fault.
Reply
#2
Code:
x += i;

Simply means x = x + i

That means your adding the "i" number to the "x" number.
Try removing the +
Reply
#3
This time I get '100'

Instead of

1
2
3
4

ect.
Reply
#4
Yes that is because you're declaring the x variable every time new.
To do what you want you'll need an array.

Code:
char[] x;
//then in the loop
x[i] = i;
Reply
#5
(12-15-2009, 02:38 PM)Master of The Universe Wrote: Yes that is because you're declaring the x variable every time new.
To do what you want you'll need an array.

Code:
char[] x;
//then in the loop
x[i] = i;

I'm getting an error on the 'char[] x;', it says it expected primary expression before char.

Where exactley do I put this?

And sorry im pretty new to C++.
Reply
#6
Is that book outdated? cause new compilers also accept <iostream> as an header.
<iostream.h> is old school
Reply
#7
Yeah, i'm using <iostream>, the original post was copied from the old book. But I do have a new compiler. It's just the book that's old.

2003. LOL
Reply
#8
2003...lol you might want to change the book you're reading to something up to date Smile
Reply
#9
(12-15-2009, 02:48 PM)GeneralOJB Wrote: I'm getting an error on the 'char[] x;', it says it expected primary expression before char.
Where exactley do I put this?
And sorry im pretty new to C++.

I'm the one who need to apologize.
I was with my tought in a bit different language! Big Grin

Here Take a look at this code.

Code:
#include <iostream>

using namespace std;

int main(int argc, char argv[]) {
    int i = 0;
    
    int x[101];
    
    cout << "i:" << endl;
    
    for(i; i <= 100; i++) {
        cout << "i = " << i << endl;
        x[i] = i;      
    }
    
    cout << "x:" << endl;
    cin.get();
    
    for(i = 0; i <= 100; i++) {
          cout << "x[" << i << "] = " << x[i] << endl;      
    }
    
    cin.get();
    return 1;
}
Reply
#10
Love you <33
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't this loop work? nevets04 5 1,392 12-11-2009, 03:38 AM
Last Post: Sagittarius

Forum Jump:


Users browsing this thread: 1 Guest(s)