• We hope you have a fantastic holiday season to close out 2025! Thank you all so much for being part of the Tom's Guide community!

Why there are different output for the following two same program in C++

arpitsri

Honorable
Dec 2, 2013
6
0
10,510
I mean that the following codes should have the same output, but a change of line is giving a whole different output. I'm using Turbo C++ compiler, I know that these codes are outdated but in my exams only these are going to come.

Code 1
#include<iostream.h>
#include<conio.h>
void main()
{clrscr();
int i,j;
for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*";
cout<<"\n";
}
getch();}

and this one-

Code-2
#include<iostream.h>
#include<conio.h>
void main()
{clrscr();
int i,j;
for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*"<<"\n";
}
getch();}


Output 1-
*
**
***
****

Output 2-
*
*
*
*
*
*
*
*
*
*

 
Solution
they are not the same

CODE1, the inner for loop will only print the *, i am not 100% sure here but since you dont have { } in the inner for loop, only the line before it will be executed (the * print), the "\n" will execute after the inner loop is done

code2, again no { } in the inner for loop, so it will only execute 1 line after it, but this time, the print is * together with the newline (\n), hence after printin 1 *, new line will be printed after it.


for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*"; <--- this will execute for the inner loop
cout<<"\n"; <--- this will execute for the outer loop (using the i variable), so only a few "new line"
}

for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*"<<"\n"...
they are not the same

CODE1, the inner for loop will only print the *, i am not 100% sure here but since you dont have { } in the inner for loop, only the line before it will be executed (the * print), the "\n" will execute after the inner loop is done

code2, again no { } in the inner for loop, so it will only execute 1 line after it, but this time, the print is * together with the newline (\n), hence after printin 1 *, new line will be printed after it.


for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*"; <--- this will execute for the inner loop
cout<<"\n"; <--- this will execute for the outer loop (using the i variable), so only a few "new line"
}

for(i=1;i<=5;i++)
{for(j=1;j<i;j++)
cout<<"*"<<"\n"; <---- * + newLine will execute, so just 1 * per line
}

hope its clear somehow
 
Solution
You should be 100% sure as your explanation is correct. A C++ "for" statement is followed by either a single statement or by a number of statements grouped with {}. in each of the OP's programs only the statement immediately following the inner "for" is part of the loop.