C# Console For Loop Loops / Iteration Statement

Display Numbers Between 1 to N Using For Loop

Loops are essential in programming, allowing you to perform repetitive tasks efficiently. This article discusses how to use a for loop in C# to print numbers from 1 to a user-defined value. This program is an excellent example for beginners learning how to combine user input with looping constructs.


Code Example

Here is the complete C# code for the program:

Output:

For Loop

Explanation of the Code

  1. User Input:
    • The program prompts the user to enter a number using the statement:
  • The input is read as a string using Console.ReadLine() and converted into an integer using Convert.ToInt32().

The for Loop:

  • A for loop is used to iterate from 1 up to the number entered by the user:
    • Initialization (int i = 1): The loop starts with i set to 1.
    • Condition (i <= n): The loop continues as long as i is less than or equal to n.
    • Increment (i++): After each iteration, i is increased by 1.

Output:

  • Inside the loop, the statement
  • prints the current value of i to the console. This ensures all numbers from 1 to n are displayed.

Pause Program:

  • The Console.ReadKey() method at the end pauses the program, allowing the user to view the output before the console window closes.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.