Beav Petrie wrote:

Sluggers,

I run these codes I copied from a tutorial book.
The print out is 24, correct factorial of 4 (4*3*2*1).

But y is 0 (y < 1) finally and return value of 1 so how is it
24 instead of 1 is printed ?
Please help me understand. Many thanks.

Do not flame me, please. I am a newbie.

Beav


#include <stdio.h>

int factorial(int y)
{
            if ( y < 1){
                 return 1;
            }
            else
            {
                  return (y * factorial(y - 1));
             }
}

int main(void)
{
             printf("Factorial result: %d\n",factorial(4));
             return 0;
}


Hi Beav,

Regarding the above codes, just a note to say some C tutorial books
say that 'y' can have a maximum value of '7'. This means when
you have '8' or greater the result is meaningless or something to that effect.

This means that the PC test platform used in the book is
16-bit (word size = 2 bytes) and int size is 2 bytes. The
integer value is to the maximum of 2 exponent 15 (16-1) or 32,768.

With Pentium PC this has gotten bigger as Pentium PC is 32-bit(word size = 4 bytes). The integer value is to the maximum of 2 exponent 31 (32 -1) or 2,147,483,648.
This means you can have '25' maximum as the value of y.

As you can see the hardware platform and C compiler work hand-in-hand to
determine the behaviour in certain situations. Change the hardware in this situation and there
is a change in behaviour even without changing the codes.

Sizeof function is provided in C to assist in this situation.

Hope this helps.

O Plameras



--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to