Click here to Skip to main content
15,905,316 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So here are 2 programs that our teacher taught us today but can't figure out how to do it.

First:

void main()
{ 
 for(int i=1; i<=5; ++i)
 {
  for(int j=1; j<=1; ++j)
  cout<<j<<"";
  cout<<'\n';
 }
}

So it should print this:
1
12
123
1234
12345

Second:

void main()
{ 
 for(int i=5; i>=1; --i)
 {
  for(int j=1; j<=1; ++j)
  cout<<j<<"";
  cout<<'\n';
 }
}

And this must do:
12345
1234
123
12
1

If you can only explain the first one, it will be great either. I can figure out the second one.
Posted
Updated 23-Sep-15 1:43am
v3
Comments
CHill60 23-Sep-15 7:30am    
If you can figure out the second one then you should be able to figure out the first one! Which bit are you stuck with?
barneyman 23-Sep-15 7:32am    
neither make sense and will do what's posited

the second won't even compile
Onusmoon 23-Sep-15 7:44am    
@CHill60 I meant that if you can explain the 1st code, I can later try to understand the second one. And I am not able to understand anything.
phil.o 23-Sep-15 7:52am    
And what your teacher told you when you asked him for clarifications?
Onusmoon 23-Sep-15 8:04am    
he just repeated everything that he wrote and dummmmmmmmmmm

if i fix them, maybe they'll make more sense?

C++
void main()
{
 for(int i=1; i<=5; ++i)
 {
// was j<=1, should be j<=i
  for(int j=1; j<=i; ++j)
  {
   cout<<j<<"";
  }
  cout<<'\n';
 }
}



C++
void main()
{
 // was i<>=1, should be i!=1
 for(int i=5; i!=1; --i)
 {
  // was j<=1, should be j<=i
  for(int j=1; j<=i; ++j)
  {
    cout<<j<<"";
  }
  cout<<'\n';
 }
}
 
Share this answer
 
Hi,

Your both codes are wrong.

C#
void main()
{
 for(int i=1; i<=5; ++i)
 {
  for(int j=1; j<=i; ++j)
  cout<<j<<"";
  cout<<'\n';
 }
}


In the second for loop the condition should include "i" not "1".

Here the forst loop goes on and in the 2nd loop the values get printed as 1.
In the 2nd iteration the value of i=2.
So it will print 12.
like wise it will go on printing till the outer loop condition satisfies.
If you can able to learn dry run then it would help you in developing logic. its not advisable to get help every time from such forums.

Thanks,
Sisir Patro
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900