write a program in c# to display the first 10 natural numbers

write a program in c# to display the first 10 natural numbers
In this article [Show more]

    Introduction

    One of the fundamental tasks in learning any programming language is dealing with basic loops and outputs. In C#, writing a program to display the first 10 natural numbers is a great exercise for beginners to understand loops and console output.

    Understanding Natural Numbers

    Natural numbers are a sequence of numbers starting from 1 and increasing by 1 each time (1, 2, 3, ...). They are the basic counting numbers used in daily life.

    Step-by-Step Guide to Write the Program

    Let’s go through the process of writing a C# program that displays the first 10 natural numbers.

    Step 1: Setup the Development Environment

    Ensure you have a C# development environment set up. You can use Microsoft Visual Studio, Visual Studio Code, or any other IDE that supports C# development.

    Step 2: Create a New Console Application

    • Open your IDE and create a new Console Application project.
    • Name your project, for example, DisplayNaturalNumbers.

    Step 3: Writing the Code

    In the main method of your program, write the following code:

     

    using System;
    
    class Program
    {
        static void Main()
        {
            Console.WriteLine("First 10 natural numbers:");
    
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
    

    Explanation:

    • The using System; statement allows us to use system-level classes like Console.
    • class Program defines the class.
    • static void Main() is the main method where the execution of our program begins.
    • The for loop is set up to repeat 10 times, starting from 1 (int i = 1) and incrementing by 1 each time (i++), until it reaches 10 (i <= 10).
    • Inside the loop, Console.WriteLine(i); prints each number to the console.

    Step 4: Run the Program

    • Build and run your application.
    • The console will display the numbers from 1 to 10, each on a new line.

    Conclusion

    This simple program is a perfect starting point for beginners in C#. It demonstrates the basics of loops, console output, and the fundamental structure of a C# application. Try modifying the program to display a different range of numbers or implement other types of loops for practice.

    Additional Challenge

    As an additional challenge, try modifying the program to display the first 10 natural numbers in reverse order, or sum the first 10 natural numbers and display the result. These variations will help deepen your understanding of C# syntax and control structures.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments