JeremyM
JeremyM

Reputation: 11

How do i get this output? (For loop)

I'm trying to get the end result:

1
2 1
3 2 1
4 3 2 1

This is what I have tried so far and I have the shape but I need the number to decrease. How do I solve this? I understand that I have to subtract somewhere but it compromises the shape.

public static void DrawDiamond(int size)
{
    int i, j;
    for (i = 1; i <= size; i++)
    {
        for (j = 1; j < i; j++)
        {
           Console.Write(j);

        }

        Console.WriteLine();
    }

}

My current results is this:

1
1 2
1 2 3
1 2 3 4

Upvotes: 0

Views: 169

Answers (4)

Enigmativity
Enigmativity

Reputation: 117064

This works too:

Console.WriteLine(String.Join(Environment.NewLine,
    Enumerable
        .Range(1, 4)
        .Select(x => String.Join(" ", Enumerable.Range(1, x).Reverse()))));

I get:

1
2 1
3 2 1
4 3 2 1

Upvotes: 0

Phillip Ngan
Phillip Ngan

Reputation: 16106

Or if you prefer to work with Linq:

Enumerable.Range(1, 5).ToList().ForEach(x =>
{
    Console.WriteLine();
    Enumerable.Range(1, x).Reverse().ToList().ForEach(y => Console.Write(y));
});

which produces:

1
21
321
4321
54321

Upvotes: 0

Mayur Vora
Mayur Vora

Reputation: 962

Hello JeremyM,

Logic

int i, j;
for (i = 1; i <= no_of_row; i++)
{
    for (j = i; j>=1; j--)
    {
       Console.Write(j);

    }
    Console.WriteLine();
}

Solution

using System.IO;
using System;

class Program
{
    static void Main()
    {
       int i, j;
        for (i = 1; i <= no_of_row; i++)
        {
            for (j = i; j>=1; j--)
            {
               Console.Write(j);

            }

            Console.WriteLine();
        }
    }
}

For Example:
no_o_rows = 5 so output,

1
21
321
4321
54321

I hope my answer is helpful.
If any query so comment please.

Upvotes: 1

PRERAK CHOKSI
PRERAK CHOKSI

Reputation: 21

Print value of i-j+1 insted of only j

Upvotes: 0

Related Questions