how can I print out using 2 inputs from user and print out the numbers which is taken from user?

Viewed 21

like 10 and 20 is taken. I,ll to print out even user give me 20 and 10. I mean to print out in both way negative and positive!

Console.WriteLine("Enter a number for looping!"); int input = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter a number for looping!");
        int input1 = Convert.ToInt32(Console.ReadLine());

        for (int i = input; i <= input1; i++)
        {              
            Console.WriteLine(i);
        }
    }
1 Answers

From what I understand, this is what you want:

If user inputs 10 and 20, you want program to print out 10, 11, 12, ... , 20

If user inputs 20 and 10, you want program to print out 20, 19, 18, ... , 10

So the trick is to determine the "correct" for loop condition and increment for the 2 cases:

  1. input1 > input (ie, if user inputs 10 and then 20)
  2. input1 <= input (ie, if user inputs 20 and then 10)

To achieve that, you can do something like this:

Console.Write("Enter the starting number: ");
int input = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the ending number: ");
int input1 = Convert.ToInt32(Console.ReadLine());

// new loop condition and increment
Func<int, bool> loopCondition = (i) => (input1 > input) ? i <= input1 : i >= input1;
int loopIncrement = (input1 > input) ? +1 : -1;

for (int i = input; loopCondition(i); i += loopIncrement)
{
    Console.WriteLine(i);
}

where the only new idea is:

// new loop condition and increment
Func<int, bool> loopCondition = (i) => (input1 > input) ? i <= input1 : i >= input1;
int loopIncrement = (input1 > input) ? +1 : -1;
Related