Why there are different output for the following two same program in C++
Tags:
- Programming Language
-
Apps
- C++
- Turbo+C++
Last response: in Apps General Discussion
arpitsri
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-
*
*
*
*
*
*
*
*
*
*
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
Cons29
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
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
Ijack
February 13, 2014 11:23:26 PM