user2227862
user2227862

Reputation: 605

Remainder through recursion

I am learning recursion and i encountered a conceptual doubt while solving the problem of calculation of remainder when a positive integer is a is divided by a positive integer b.

My code is:

#include<stdio.h>
#include<stdlib.h>
int x;
int rem(int a,int b)
{
    x=a;
    if(x>=b)
    {
        x=x-b;
        rem(x,b);
    }
    printf("%d\n",x);
    return x;
}
int main()
{
    int a,b;
    printf("Enter a & b\n");
    scanf("%d %d",&a,&b);
    int y =rem(a,b);
    printf("rem is :%d",y);
    return 0;
}

Its working fine. I have learned that for every call a new set of formal parameters and local variables are created.

So i experimented it by printing x on return of every recursive call! But it is printing 1 1 1 1. Why is the value of x corresponding to a particular call not printed. ?

Why only the last modified value printed?.. Is that because i declared 'x' as global?

Upvotes: 1

Views: 5205

Answers (4)

Anushka Tripathi
Anushka Tripathi

Reputation: 1

#include<stdio.h>
#include<conio.h>

int fun(int,int);

int main()
{
    int a,b;
    printf("enter two numbers");
    scanf("%d %d",&a,&b);
    fun(a,b);
    //printf("%d",fun(a,b));

}
int fun(int a,int b)
{

 
   if(a<b)
   printf("%d",a);
   if(a>=b)
   a=fun(a-b,b);
   return a;
}

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 755010

Ignoring issues with checking the return value from scanf() and that the two entered values are both positive, etc, I think you can and should avoid x altogether. You could use:

#include <stdio.h>

static int rem(int a, int b)
{
    if (a >= b)
        a = rem(a-b, b);
    printf("%d\n", a);
    return a;
}

int main(void)
{
    int a, b;
    printf("Enter a & b\n");
    scanf("%d %d", &a, &b);
    int y = rem(a, b);
    printf("rem(%d, %d) is: %d\n", a, b, y);
    return 0;
}

This code captures the return value from rem() at each level of recursion. In this case, because the returned value doesn't change as the recursion unwinds, you could use the global variable x, but there is no need for it, and you should avoid global variables whenever you can.

Upvotes: 2

n3rd4n1
n3rd4n1

Reputation: 371

It is because while x >= b, rem() is repeatedly called before printf()s are called. Only after x < b will the printf()s are called as each call on rem() unwinds.

You might want to make x local to rem() to get the desired result.

Upvotes: 2

Naruil
Naruil

Reputation: 2310

In this case perhaps you need only to move your print up

int rem(int a,int b)
{
    x=a;
    printf("%d\n",x);
    if(x>=b)
    {
        x=x-b;
        rem(x,b);
    }
    return x;
}

But I think you should avoid the use of global variables in a recursive alrotithm. It could make the algorithm very difficult to reason about. Recursive functions are better to be 'pure functions'.

Upvotes: 4

Related Questions