Sign in with
Sign up | Sign in
Your question
Solved

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

Last response: in Applications
Share
February 13, 2014 10:26:15 PM

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-
*
*
*
*
*
*
*
*
*
*

More about : output program

Best solution

February 13, 2014 10:45:04 PM

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
Share
February 13, 2014 11:23:26 PM

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.
m
0
l
!