Console.Writeline
Console.Writeline

Reputation: 51

How would I display a For and Reverse For Loop on the same Line C#

I have been trying to get both a For and Reverse For loop to display on a line in this formation Number x Number

Due to the number being an input (people % i==0) is there to find factors of the number that has been given.

                for (int i = 2; i <= people - 1; i++)
                {   
                    if (people % i==0)
                    {
                        Console.Write($"{i}m x ");
                        //Console.WriteLine($"{i} is factors of {input}");
                           

                    }
                }


                for (int j = people - 1; j >= 2; j-- )
                {
                    if (people % j == 0)
                    {
                        Console.WriteLine($"{j}m");
                        
                    }
                    
                }

Upvotes: 1

Views: 134

Answers (3)

TheGeneral
TheGeneral

Reputation: 81503

C# for can use compound assignments/expressions (zero or more statements separated by commas)

int people = 10;

for (int i = 2, j = people - 1; i <= people - 1; i++, j--)
   Console.WriteLine($"i = {i}, j = {j}");

Output

i = 2, j = 9
i = 3, j = 8
i = 4, j = 7
i = 5, j = 6
i = 6, j = 5
i = 7, j = 4
i = 8, j = 3
i = 9, j = 2

Note : this is very common in C/++ however it's less common in C#; we tend to like things declarative, neat and readable.


Or you can calculate it on the fly

int people = 10;
for (int i = 2; i <= people - 1; i++)
    Console.WriteLine($"i = {i}, j = {people-i+1}");

Full Demo Here

Upvotes: 3

Hayden
Hayden

Reputation: 2988

If you're interested in a way to achieve this using Linq, this is achievable using a Zip operation:

int start = 2;
int people = 9;

Enumerable.Range(start, people - start + 1)
    .Zip(Enumerable.Range(start, people - start + 1).Reverse(), (x, y) => $"{x}m x {y}m")
    .ToList()
    .ForEach(Console.WriteLine);

Output

2m x 9m
3m x 8m
4m x 7m
5m x 6m
6m x 5m
7m x 4m
8m x 3m
9m x 2m

Upvotes: 0

Li-Jyu Gao
Li-Jyu Gao

Reputation: 940

Create another index j in the first for loop

for (int i = 2; i <= people - 1; i++)
{   
    if (people % i==0)
    {
        Console.Write($"{i}m x ");
        //Console.WriteLine($"{i} is factors of {input}");
    }
    
    int j = people - i + 1;
    if (people % j == 0)
    {
        Console.WriteLine($"{j}m");
        
    }
}

Upvotes: -1

Related Questions