Print Natural Numbers from 1 to N Using goto Statement in C

This program prints all natural numbers from 1 to a number n entered by the user, using a goto statement to create a loop-like jump.

C Program

#include <stdio.h>

int main() {
    int n, i = 1;

    printf("Enter n: ");
    scanf("%d", &n);

    loop:
        if (i <= n) {
            printf("%d ", i);
            i++;
            goto loop;
        }

    printf("\n");
    return 0;
}

Explanation

  • loop: defines a label that goto can jump back to.
  • The if condition checks whether i is still within range; if so, it prints i, increments it, and jumps back to loop.
  • Once i exceeds n, the condition fails and control falls through, ending the "loop."
  • goto is generally discouraged in modern C because it can make code hard to follow, but it is functionally equivalent to a while loop here — this is exactly why the lab exercise asks you to implement it this way.

Sample Output

Enter n: 5
1 2 3 4 5

Leave a Comment