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 thatgotocan jump back to.- The
ifcondition checks whetheriis still within range; if so, it printsi, increments it, and jumps back toloop. - Once
iexceedsn, the condition fails and control falls through, ending the "loop." gotois generally discouraged in modern C because it can make code hard to follow, but it is functionally equivalent to awhileloop 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