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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | static void Main(string[] args) { int n; Console.Write("Number :"); n = Convert.ToInt32(Console.ReadLine()); for (int i = 1; i <= n; i++) { Console.WriteLine(i); } Console.ReadKey(); } |
Output:

Explanation of the Code
- User Input:
- The program prompts the user to enter a number using the statement:
1 2 3 | Console.Write("Number: "); |
- The input is read as a string using
Console.ReadLine()
and converted into an integer usingConvert.ToInt32()
.
The for
Loop:
- A
for
loop is used to iterate from 1 up to the number entered by the user:
1 2 3 | for (int i = 1; i <= n; i++) |
- Initialization (
int i = 1
): The loop starts withi
set to 1. - Condition (
i <= n
): The loop continues as long asi
is less than or equal ton
. - Increment (
i++
): After each iteration,i
is increased by 1.
- Initialization (
Output:
- Inside the loop, the statement
1 2 3 | Console.WriteLine(i); |
- prints the current value of
i
to the console. This ensures all numbers from 1 ton
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.