cchi
cchi

Reputation: 81

counting until a certain number down and back up with recursion

This is a C-assignment. use void countDownUp(unsigned int k) to write a recursion to count until a certain number down and then immediately back up. For example, if k = 3, the output should be 3 2 1 0 1 2 3. I already wrote a countDown function

void countDown(unsigned int k)
{   
    printf("%d ", k);
    if (k > 0)
        countDown(k-1);
}

and also a countUp function. I used this function in my void countDownUp(unsigned int k)function like this:

void countDownUp(unsigned int k)
{   
    countDown(k);
    static int n=0;
    if(n < k){
        printf("%d ", n+1);
        n++;
        countDownUp(k);
    }
}

The output now is 3 2 1 0 1 3 2 1 0 2 3 2 1 0 3 3 2 1 0I know it doesn't work, but i have no idea how can i adjust it to the right output. Can someone give me some advices? Thank you very much!

Upvotes: 1

Views: 1086

Answers (2)

pmg
pmg

Reputation: 108978

Q: What does CountDownUp() do in the general case?
A: It prints n twice, with the result of CountDownUp(n - 1) in between.

void CountDownUp(int n) {
    printf("%d ", n);
    CountDownUp(n - 1);
    printf("%d ", n);
}

Q: What's the stop condition?
A: When CountDownUp is called with 0.
Q: What do we do then?
A: Print just once and stop recursion.

void CountDownUp(int n) {
    printf("%d ", n);
    if (n == 0) return;
    CountDownUp(n - 1);
    printf("%d ", n);
}

Voila!

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

There is no need to use a static variable. The function can be written simpler.

#include <stdio.h>

void countDownUp( unsigned int n )
{
    printf( "%u ", n );
    if ( n )
    {
        countDownUp( n - 1 );
        printf( "%u ", n );
    }       
}

int main(void) 
{
    countDownUp( 3 );

    return 0;
}

the program output is

3 2 1 0 1 2 3

As for your function implementation

void countDownUp(unsigned int k)
{   
    countDown(k);
    static int n=0;
    if(n < k){
        printf("%d ", n+1);
        n++;
        countDownUp(k);
    }
}

then the call within the function

countDownUp(k);

anew calls countDown(k); with the same value of k that was passed to the current call of the function countDownUp because within the function the value of k is not changing..

Also you need to specify the conversion specifier %u instead of %d because the variable k has the type unsigned int.

Upvotes: 1

Related Questions