for loop confusion

I want to calculate all ten multiples of a number.. by using a for loop and multiplying the number with the increment, why is the result appearing only the last multiplication ?

int number,j;

int main(){

cout<<"Enter a number"<<endl;
cin>> j;

for (int i=1;i=10;i++) {

number = j * i;

cout<<"number is: "<<number<<endl;
return 0;
for (int i=1;i=10;i++)

for-loop syntax is (set value/increment,...; condition &&/||...; set value/increment,...)

Look at your condition
The return statement is inside the loop. This terminates the program.

Also the for statement is incorrect, it should look something like this:
    for (int i=1; i<=10; i++)
Last edited on
aha.. it's working!! Thanks..!!

but why does it have to be i<=10 and not i=10??
It's a condition; a logical test. = is an assignment, which was actually modifying i and assignments can be evaluated in conditions (0 is false, everything else is true).
for (int i = 1; i =10; i++)

i <= 10 reads i is less than or equal to 10. the first thing you did in the for loop was make i = 1. The compiler tries to read that for loop as;

i equals 1; when 1 = 10; add 1 to i.

1 doesn't equal 10 so i is never added to and the loop doesn't work. Hopefully this is clear enough and 100% correct, I just started learning this also and am probably only a few chapters ahead of you

Aye.. probably.. :-)

So if it was like i==10 instead of i=10, would then the compiler indeed assign the values properly ?
pyoung673 wrote:
1 doesn't equal 10
Not the correct explanation.

If the return 0; statement is moved out of the loop, where it belongs, an infinite loop results.

First i is initialised with the value 1.

Then the expression i=10 is evaluated to see whether it is true or false. First, the assignment operation is performed, so i is set to the value 10. Then the result, 10, becomes the result of the expression. In a boolean test, zero is considered false and any non-zero value is interpreted as true.

After the first pass through the loop, i is incremented via the i++ operation, and the condition is tested again as above, and i is set to 10 again.

Thus the loop is executed over and over again with exactly the same values.
Last edited on
Topic archived. No new replies allowed.