Thread: Weird..?

  1. #1
    Registered User snapshooter's Avatar
    Join Date
    Sep 2004
    Posts
    37

    Weird..?

    Here's this program..could someone explain me where the function (mystery) is declared? i mean where is say that mystery returns a*b???

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int mystery( int a, int b ); /*function prototype*/
    
    /*function main begins program execution*/
    int main()
    {
        int x;/*first integer*/
        int y;/*second integer*/
        
        printf("Enter two integers: ");
        scanf("%d %d", &x, &y);
        
        printf("The result is %d\n", mystery(x,y));
        
        system("pause");
        return 0; /*indicates succesful termination*/
        
    } /*end main*/
    
    /*Parameter b must be a positive integer
      to prevent infinite recursion */
      
    int mystery( int a, int b )
    {
        if ( b==1 )
        {
            return a;
        }
        else /*recursive step*/
        {
            return a + mystery( a, b-1 );
        }
    }/*end function mystery*/
    Thanks in advance!

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    A small excercise in recursion. Think about how multiplication of integers works.
    a * b = a + a + ... + a (a appears in the sum b times)

    If you follow the recursion, that is exactly what mystery does.
    Lets follow a small example (and call mystery f)
    f(4, 3) = 4 + f(4, 2)
    f(4, 2) = 4 + f(4, 1)
    f(4, 1) = 4 (the terminating case)

    Substituting back in, we have:
    f(4, 2) = 4 + 4
    f(4, 3) = 4 + (4 + 4) = 12 = 4 * 3

    This result can be proven to work by induction whenever b >= 1
    Note that if you let b < 1, then bad things happen
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. weird things with my linked list of queue
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 11-22-2008, 11:23 PM
  2. weird
    By kiz in forum C Programming
    Replies: 8
    Last Post: 09-24-2007, 01:16 AM
  3. Weird Characters With GetDlgItemText
    By execute in forum Windows Programming
    Replies: 4
    Last Post: 05-04-2006, 04:53 PM
  4. weird error
    By gandalf_bar in forum Linux Programming
    Replies: 2
    Last Post: 07-17-2005, 07:32 AM
  5. Getting weird characters in Strings
    By steve8820 in forum C Programming
    Replies: 3
    Last Post: 09-18-2001, 02:49 AM