Hey
Why doesn't this work:
PHP Code:
#include <iostream.h>
int main() {
int x = 0;
int i;
for (i = 1; i <= 100; i++) {
x += i;
}
cout << x << 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.
Simply means x = x + i
That means your adding the "i" number to the "x" number.
Try removing the +
This time I get '100'
Instead of
1
2
3
4
ect.
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;
(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++.
Is that book outdated? cause new compilers also accept <iostream> as an header.
<iostream.h> is old school
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
2003...lol you might want to change the book you're reading to something up to date
(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!
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;
}