Recursive function that prints all integers from N to 1 and then from 1 to N

Viewed 2754

I just wanted to ask how i can display all integers from N to 1 and again to N with step -+2 and a recursive function, considering that N is given by user. For example, if the user gives 7, then calling the function would print <<7 5 3 1 3 5 7>> or if the parameter is 8, it would print <<8 6 4 2 4 6 8>> I have only figured out to display N to 1 (or N to 2). Here's my code:

    int main()
{
    int a;
    printf("Give a:");
    scanf("%d", &a);
    func(a);
    return 0;
}

int func(int n)
{
    printf("\t%d",n);
    if (n==1 || n==2)
    {
        return 1;
    }
    return func(n-2);
}
7 Answers

Apparently I must be assuming something everyone else isn't. Either that or they just like obtuse code.

void func(int n)
{
    if (n > 2)
    {
        printf("%d ", n);
        f(n-2);
    }
    printf("%d ", n);
}

should be all that is required. Live example below

Code

#include <stdio.h>

void f(int n)
{
    if (n > 2)
    {
        printf("%d ", n);
        f(n-2);
    }
    printf("%d ", n);
}

int main()
{
    for (int i=0; i<=10; ++i)
    {
        f(i);
        fputc('\n', stdout);
    }
}

Output

0 
1 
2 
3 1 3 
4 2 4 
5 3 1 3 5 
6 4 2 4 6 
7 5 3 1 3 5 7 
8 6 4 2 4 6 8 
9 7 5 3 1 3 5 7 9 
10 8 6 4 2 4 6 8 10 

Here's a simple approach (where the step is also configurable). It goes down towards 1, printing the numbers and calling itself (also printing the value smaller than step (the one in the middle, if any) once - the else branch), then when coming back (on the stack) from recursion, it prints the numbers again (the 2nd printf) in reversed order.

The program continues until user enters an invalid (including non positive int) value for n.

code.c:

#include <stdio.h>

#define STEP 2


void func(int n, unsigned int step) {
    if (n > step) {
        printf("%d    ", n);
        func(n - step, step);
        printf("%d    ", n);
    } else if (n >= 1) {
        printf("%d    ", n);
    }
}


int main() {
    int n = 0;
    while (1) {
        printf("\n\nEnter n (invalid, to exit): ");
        if ((!scanf("%d", &n)) || (n <= 0)) {
            break;
        }
        printf("\nResults for %d (with a step of: %d):\n", n, STEP);
        func(n, STEP);
    }
}

Output:

e:\Work\Dev\StackOverflow\q052302083>test.exe


Enter n (invalid, to exit): 6

Results for 6 (with a step of: 2):
6    4    2    4    6

Enter n (invalid, to exit): 7

Results for 7 (with a step of: 2):
7    5    3    1    3    5    7

Enter n (invalid, to exit): 8

Results for 8 (with a step of: 2):
8    6    4    2    4    6    8

Enter n (invalid, to exit): 9

Results for 9 (with a step of: 2):
9    7    5    3    1    3    5    7    9

Enter n (invalid, to exit): 3

Results for 3 (with a step of: 2):
3    1    3

Enter n (invalid, to exit): 2

Results for 2 (with a step of: 2):
2

Enter n (invalid, to exit): 1

Results for 1 (with a step of: 2):
1

Enter n (invalid, to exit): q
#include <stdio.h>


int a;
int forward = 0;

int main() { 
    printf("Give a:");
    scanf("%d", &a);
    func(a);
    return 0; 
}

int func(int n)

{ 
    printf("\t%d \n",n);
    if (forward != 1 ) {
        if (n==1 || n==2)
        {
            //start printing from 1 or 2 to N
            forward = 1;
            func(n+2);
        } else {
            return func(n-2); 
        }
    } else {
       if(n >= a) {
            return;
        }
        return func(n+2);
    }
}

Using static variables.

#include <stdio.h>

void func(int n);

int main()
{
  int a;

  printf("Give a:");    
  scanf("%d", &a);  
  func(a);
  return 0;
}

void func(int n)
{
  static char reverse;
  static char init = 1;
  static int  val;

  if (init)
  {
      val = n;
      init = 0;
  }

  printf("%d\t",n);    

  if (n <=2 ) {
    reverse = 1;
  }   

  n += (reverse) ? 2 : -2;

  if (n > val) return;

  func(n);
}

Output:

7       5       3       1       3       5       7

Here's my solution . I'm sure there's better ones but still ...

void rec(int n) {
    if (n%2==1 &&n==1) { printf("\t1"); return; }
    else if(n%2==0 && n==2)
    {
        printf("\t2");return;
    }
    printf("\t%d",n);
    rec(n-2);
    printf("\t%d",n);
}
int main()
{
    rec(7);
    return 0;
}

Hope it was helpful !

I would have a counter of some sort that you switch "on" when you are going upward. Pass in the counter as well as the original number into func().

I'm not sure of exact syntax, as I'm new to C after working for a year in C++, but this is what I would do.

counter = 0;
int func(int n, int counter, int originalNum)
{
    printf("\t%d",n);

    if(counter == 0)
    {
        if (n==1 || n==2)
        {
            counter = 1;
            return func(n+2, counter, originalNum);
        }
        return func(n-2, counter ,originalNum);
    }
    else
    {

        if (n == originalNum)
        {
            return 1;
        }
        return func(n+2, counter, originalNum);
    }

}

For fun, I thought I would try to improve on @WhozCraig good answer and code a single function to not only print the sequence, but also output the spacing and sentinels as requested, also no trailing space after last number.

7, then calling the function would print <<7 5 3 1 3 5 7>> ...
8, it would print <<8 6 4 2 4 6 8>>

The trick to this is that the function needs to know if it is the first call (to print the "<<%d", ">>" or a re-entrant one. Since OP did not specify behavior for negative values, func() below uses the sign to indicate first or re-entrant call.

#include <stdio.h>

void func(int n) {
  if (n > 0) {
    printf("<<%d", n);
    if (n > 2) {
      func(-(n - 2));
      printf(" %d", n);
    }
    printf(">>\n");
  } else {
    n = -n;
    printf(" %d", n);
    if (n > 2) {
      func(-(n - 2));
      printf(" %d", n);
    }
  }
}

int main(void) {
  for (int a = 1; a<= 10; a++) {
    func(a);
  }
}

Output

<<1>>
<<2>>
<<3 1 3>>
<<4 2 4>>
<<5 3 1 3 5>>
<<6 4 2 4 6>>
<<7 5 3 1 3 5 7>>
<<8 6 4 2 4 6 8>>
<<9 7 5 3 1 3 5 7 9>>
<<10 8 6 4 2 4 6 8 10>>

On a personal note, the code may benefit with some improvements, yet the code as posted is exactly what I typed and compiled the first time. I have never written this many lines of code for a complete program that worked exactly as wanted with no edits: a red letter day.

Related