Print sequence of numbers without using loop

Print sequence of numbers without using loop

Question:

Microsoft: Print a sequence of numbers starting with N, without using loop, in which  A[i+1] = A[i] – 5,  if  A[i]>0, else A[i+1]=A[i] + 5  repeat it until A[i]=N.

Input:
The first line contains an integer T, number of test cases. Then following T lines contains an integer N.

Output:
For each test case, print the pattern in newline with space separated integers.

Explanation:

We basically first reduce 5 one by one until we reach a negative or 0. After we reach 0 or negative, we one by one add 5 until we reach N.

Logic:

  • Get the input elements from the user.
  • The input element is getting by using the goto statement to avoid the loop.
  • Using recursion the first and second half of the pattern is printed by satisfying certain conditions.

Program:

[code lang=”c”]
#include<stdio.h>
void print(int m,int n,int i)
{
if(m>0&&i==0) //prints first half of pattern
{
printf("%d ",m);
m-=5;
print(m,n,0); //calls recursively to print elements
}
else if(m!=n) //prints second half of pattern
{
printf("%d ",m);
m+=5;
print(m,n,1); //calls recusively to print second half
}
}
int main()
{
int a[20],i=0,n;
scanf("%d",&n); //n->no_of_inputs
Input:
if(i<n)
{
scanf("%d",&a[i]);
print(a[i],a[i],0); //calls print function to print pattern
printf("%d\n",a[i]);
i++;
goto Input; //goto is used to get several inputs
}
return 0;
}
[/code]

You might also like:

Program to print dynamic star pattern

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *