Click here to Skip to main content
15,890,717 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
12345
234
3

how to this result get in single loop and
which condition and logic used to get result

What I have tried:

for(int i=1;i<=5;i++)
{
console.write(i);
}
for(int j=1;j<=5;j++)
{
if(j==1||j==5)
{
console.write(" ");
}
else
{
console.write(j);
}

}
for(int k=1;k<=5;k++)
{
if(k==3)
console.write(k)
else
console.write(" ");
}
Posted
Updated 29-Jun-16 22:55pm
Comments
Richard MacCutchan 30-Jun-16 4:17am    
This is your homework so you are expected to do it yourself. Try thinking about the steps and conditions necessary for such a question.
JayantaChatterjee 30-Jun-16 4:32am    
Home work not done here....
sorry... :-)

1 solution

First off, that won't work because you need to explicitly say when you have reached the end of a line: call Console.WriteLine between the lines to "break" them in the output.
And remember that C# is case sensitive: console.write is not the same as Console.Write
This is your homework, so I'm not going to give you the code! But a few hints isn;t a problem:
You can't really do that in a "single loop" - you need two loops as a minimum: One to print each line, and one to print the contents of that line. That is, assuming you have to be flexible and allow for other values than 5 as the number of characters wide the lines should be. If not, it's trivial, and you don't need a loop:
C#
Console.WriteLine("12345");
Console.WriteLine(" 234 ");
Console.WriteLine("  3  ");
But submitting that won't get you a good grade! :laugh:
What you actually want to do is have two loops, one inside the other.
The outer loop writes each line:
C#
for (int i = 0; i < numberOfLines; i++)
   {
   ...
   Console.WriteLine();
   }
And inside that you have a second loop which writes the line.
That's actually pretty easy: all you need to do is loop for the number of characters on the line minus the line number, and check the loop index. If it's less than the line number, print a space. Otherwise, print the index value plus one.
Try it: you'll see what I mean!
 
Share this answer
 
Comments
JayantaChatterjee 30-Jun-16 4:56am    
My 5ed..
Best Answer of the Month.. :-D
Member 12611617 30-Jun-16 5:14am    
help me for below output

12345
234
3
OriginalGriff 30-Jun-16 5:23am    
I did - did you try what I suggested?

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