You are here

Print numbers without using loops

C program to print first n natural numbers without using any loop (do-while, for, or while). In the first program, we use recursion to achieve the desired output, and in the second, we use goto statement, i.e., without creating any function other than main.

C program using recursion

#include <stdio.h>

void print(int);

int main()
{
  int n;

  scanf("%d", &n);

  print(n);

  return 0;
}

void print(int n)
{
  static int c = 1;

  if (c == n+1)
    return;

  printf("%d\n", c);
  c++;
  print(n);
}

Download Numbers without loop program.

Output of program:
Numbers without loop c program

C program using goto

#include <stdio.h>

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

  scanf("%d", &n);   // It is assumed that n >= 1

  print:  // label

  printf("%d\n", c);
  c++;

  if (c <= n)
    goto print;

  return 0;
}