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 will 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 programming code 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:

C programming code 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;
}

Comments

Popular posts from this blog

Difference between asterisk and ampersand operators in c

kbhit in c