C#.NET C# Fundamentals

While Loop in C# - Print Natural Numbers and Their Sum

The while loop in C# is a control looping statement that repeatedly executes a block of code as long as a specified condition is true. In this example, the program uses a while loop to print the first n natural numbers and calculate their sum.

Beginner 30 Minutes Monopoly IT Solutions Updated 2026-08-17
.NET 10 class training banner
5.0
5.0
4.6

12 Noon Class

10 AM Class

Overview

What you'll cover

Learning objectives

  • Understand the purpose of the while loop in C#.
  • Learn the syntax of a while loop.
  • Understand loop variable initialization.
  • Understand how a condition controls loop execution.
  • Learn how to increment a loop variable.
  • Print natural numbers using a while loop.
  • Calculate the sum of n natural numbers using a while loop.
  • Understand the purpose of the sum variable.

Prerequisites

  • C# Basics
  • Variables
  • Data Types
  • Operators
  • Console Input and Output

Related topics

  • for Loop
  • do while Loop
  • Break Statement
  • Continue Statement
  • Nested Loops
  • Variables
  • Operators
  • Console Input and Output
Theory

Concept breakdown

Control Looping Statements

Control looping statements are used to execute a block of statements repeatedly based on a condition. The while loop is one of the looping statements available in C#.

while Loop

A while loop repeatedly executes its body as long as the specified condition evaluates to true. The condition is checked before each iteration.

Loop Variable Initialization

The loop variable should be initialized before the while loop. In this example, int i = 1 initializes the variable so that counting starts from the first natural number.

Loop Condition

The condition i <= n checks whether the current value of i is less than or equal to the number entered by the user. The loop continues while this condition is true.

Sum Variable

The variable sum is initialized to 0 and stores the running total of the natural numbers. During every iteration, the current value of i is added using sum += i.

Incrementing the Loop Variable

The statement i++ increases the loop variable by 1 after each iteration. This eventually makes the condition false and prevents the loop from running indefinitely.

Natural Numbers

In this program, natural numbers are generated starting from 1 and continuing up to the value n entered by the user.

Syntax
Hands-on example

Print n Natural Numbers and Sum of n Natural Numbers Using while Loop

Console Output
> "Enter any number :5"
> "1    2    3    4    5"
> "Sum of natural numbers up to 5 is: 15"
Walkthrough

Step by step

  1. 1

    Import Namespaces

    The program imports System and other namespaces before defining the application code.

  2. 2

    Display Input Message

    Console.Write() asks the user to enter a number.

  3. 3

    Read the Number

    Console.ReadLine() reads the user input and Convert.ToInt32() converts it to an integer stored in n.

  4. 4

    Initialize Loop Variable

    The variable i is initialized to 1 because the program starts with the first natural number.

  5. 5

    Initialize Sum

    The variable sum is initialized to 0 to store the total of all natural numbers.

  6. 6

    Check while Condition

    The condition i <= n is checked before every iteration. The loop executes only while i is less than or equal to n.

  7. 7

    Print Current Natural Number

    Console.Write(i + "\t") displays the current value of i followed by a tab space.

  8. 8

    Add to Sum

    The statement sum += i adds the current natural number to the running total.

  9. 9

    Increment Loop Variable

    The statement i++ increases i by 1 so the next natural number is processed.

  10. 10

    Display Final Sum

    After the condition becomes false, Console.WriteLine() displays the sum of natural numbers up to n.

Summary

Key takeaways

Key points

  • A while loop executes repeatedly while its condition is true.
  • The loop variable should be initialized before the loop.
  • The condition is checked before every iteration.
  • The statement sum += i adds each natural number to the total.
  • The statement i++ increments the loop variable.
  • For n = 5, the natural numbers are 1, 2, 3, 4, and 5.
  • For n = 5, the sum is 15.
  • The loop stops when i becomes greater than n.

Advantages

  • Useful when the number of iterations is controlled by a condition.
  • Provides a simple way to repeat statements.
  • Can be used for counting and accumulation operations.
  • The loop condition is easy to understand and control.
  • Suitable for user-driven and condition-based repetition.

Disadvantages

  • An incorrect condition can cause an infinite loop.
  • Forgetting to increment or decrement the loop variable can prevent the loop from ending.
  • The loop may be less suitable when the exact number of iterations is already known and a for loop would be clearer.
  • Incorrect initialization can produce unexpected results.
Real-world use

Calculate Total Daily Sales

A while loop can process sales records one by one and add each sales amount to a running total until all records have been processed. The same accumulation concept is used in this example with natural numbers.

Interview prep

Frequently asked questions

A while loop repeatedly executes a block of code as long as its condition is true.

The condition is checked before each iteration of the loop.

The loop variable must have an initial value before it is used in the loop condition.

It initializes the variable that stores the running total of the natural numbers.

It adds the current value of i to the existing value of sum.

It increases the loop variable so the loop progresses toward its stopping condition.

The condition i <= n becomes false and the while loop stops.

An infinite loop is a loop that never ends because its stopping condition never becomes false.

Test yourself

Quick MCQ practice

1. Which statement is used to repeat a block while a condition is true?

2. When is the condition checked in a while loop?

3. What is the initial value of i in the example?

4. What is the purpose of sum += i?

5. Which statement increments the loop variable by 1?

6. For n = 5, what is the sum of natural numbers from 1 to 5?

7. When does the loop while (i <= n) stop?

8. What can cause an infinite while loop?

Apply it

Practice on your own

Coding exercise

Print Natural Numbers and Calculate Their Sum

Write a C# program that accepts a number n from the user, uses a while loop to print the natural numbers from 1 to n, and calculates their sum.

Assignment

  1. Write a program to print natural numbers from 1 to n using a while loop.
  2. Write a program to calculate the sum of natural numbers from 1 to n.
  3. Modify the program to print natural numbers in reverse order from n to 1.
  4. Write a program to calculate the sum of even numbers from 1 to n using a while loop.
  5. Write a program to calculate the sum of odd numbers from 1 to n using a while loop.

Tags

#csharp#dotnet#while-loop#loops#natural-numbers#sum#control-statements#beginner

References

getintouch

Book for Live Demo!