Print numbers from 1 to N

Print Numbers from 1 to N

Problem Statement

Write a program to print all numbers from 1 to N, where N is a positive integer provided by the user.

This problem helps beginners understand:

  • Loops

  • User input

  • Basic number iteration

Explanation

To solve this problem:

  1. Take an integer N as input.

  2. Start a loop from 1.

  3. Continue printing numbers until the loop reaches N.

If N = 5, the output will be:

1 2 3 4 5
 

Approach

  • Use a loop (for or while)

  • Initialize the loop with 1

  • End the loop at N

  • Print each number during iteration

Print numbers from 1 to n logic

#include <stdio.h>

int main() {
    int N;
    scanf("%d", &N);

    for(int i = 1; i <= N; i++) {
        printf("%d ", i);
    }
    return 0;
}

#include <iostream>
using namespace std;

int main() {
    int N;
    cin >> N;

    for(int i = 1; i <= N; i++) {
        cout << i << " ";
    }
    return 0;
}

import java.util.Scanner;

public class PrintNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        for (int i = 1; i <= N; i++) {
            System.out.print(i + " ");
        }
    }
}

N = int(input())

for i in range(1, N + 1):
    print(i, end=" ")

Input


5

Output


1 2 3 4 5

Time & Space Complexity

  • Time Complexity: O(N)

  • Space Complexity: O(1)

Constraints

  • 1 ≤ N ≤ 10^5

🧠 Tips for Beginners

  • Use for loop when the number of iterations is known.

  • Always check loop conditions to avoid infinite loops.

  • Practice printing patterns using loops to strengthen logic.

Conclusion :

The Print Numbers from 1 to N problem is a great starting point for learning loops and control structures. Mastering this concept will help you solve more advanced problems involving iteration and logic building.

Keep practicing with EasyHaiCode 🚀
Happy Coding! 😊

0

Subtotal