how does it work?(im a beginner)

hi to all
please help me(im a beginner)
when we use two for loop without {},
how does it work?
for example:
what is the output of this code?:::


#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i,j;
float sum=0;
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
sum+=i+j;
cout<<sum;
return 0;
}

the output of this code is not understandable..
i think the output must be:
0+1+1+2+2+3+3
but it is not...
Welcome to forums!
I'm fairly new to programming myself, so I may be wrong, but I believe the output would actually be sum. If you wanted to see the values of i and j you could do:
1
2
3
4
5
6
for(i=1;i<=3;i++)
for(j=1;j<=3;i++)
cout << i << endl;
cout << j << endl;
sum+=i+j;
cout<<sum;
Last edited on
I believe that you will find the following example quite enlightening...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;

int main()
{
   int i;

    cout << "loop number 1..." << endl;

    //here the body of the loop consists only of
    //cout << i << ' ';
    
    for (i=0; i<10; i++)
        cout << i << ' ';
    cout << "asdf" << endl;
    
    cout << "loop number 2..." << endl;
    
    //here the body of the loop consists of
    //everything you place inside the brackets {,}
    
    for (i=0; i<10; i++)
    {
        cout << i << ' ';
        cout << "asdf" << endl;
    }

    cout << "hit enter to quit..." << endl;
    cin.get();
    return 0;
}


You might also wanna take a look here: http://cplusplus.com/doc/tutorial/control/
(scroll down until you find the 'for loop' section)
Last edited on
yeah, I guess an example would've been more useful. lol
The simple answer to why you're not getting the desired output is that the code which you want your for loop to run, is not actually inside the for loop.

1
2
3
for (i=o ; i < 3 ; i++)
cout << "This line will run.";
cout << "But not this one.";


Without code blocks, your loop will only read the first line after the actual loop is initialized.

So to fix this, simply add opening and closing braces when you have more than one statement:

1
2
3
4
5
for (i=o ; i < 3 ; i++)
{
      cout << "This line will run.";
      cout << "And this one too.";
}
Last edited on
Topic archived. No new replies allowed.