settingsAccountsettings
Menusettings

Q: Printing numbers from 1 to N in C#

+6 votes

I need to write a program that enters from the console a positive integer n and prints all the numbers from 1 to n, on a single line, separated by a space.

Examples:

n

output

3

1 2 3

5

1 2 3 4 5

 

asked in C# category by user andrew

2 Answers

+2 votes

Here is my code - I used for loop:

using System;

class NumbersFromOneToN
{
    static void Main()
    {
        Console.WriteLine("Please write your number: ");
        int n = int.Parse(Console.ReadLine());

        for (int i = 1; i <= n; i++)
        {
            Console.Write("{0} ",i);
        }
        Console.WriteLine();
    }
}

printing numbers from 1 to n in C# by using for loop

answered by user paulcabalit
edited by user golearnweb
+2 votes

With while loop (instead of for loop):


while loop in c sharp

using System;

class Numbers
{
    static void Main()
    {
        {
            Console.WriteLine("Write a number: ");
            int n = int.Parse(Console.ReadLine());
            int i = 1;

            while (i <= n)
            {
                Console.Write("{0} ",i++);
            }
            Console.WriteLine();
        }
    }
}
answered by user andrew
edited by user golearnweb
...