putchar and % (mod)

This is a discussion on putchar and % (mod) within the C Programming forums, part of the General Programming Boards category; I ran this program and got it to work and understand what it is doing : converting base 10 (decimal) ...

  1. #1
    Unregistered
    Guest

    putchar and % (mod)

    I ran this program and got it to work and understand what it is doing : converting base 10 (decimal) input (here : 25) to it's binary equivalent.

    however, I don't get how the code is doing that.
    How does the putchar statement ever run if the line before is the function calling itself? I never did get the IF statement or long bracketed loop statements...esp when there is a break symbol like ' ; ' in the statement. Doesn't that mean "STOP HERE"???

    And please explain why the % modulator is in this function??

    Code:
     
    #include <stdio.h>
    
    void puzzle(int );
    
    main()
    
    {
    
      int n;
      puzzle(25);
      printf("\n");
    }
    
    void puzzle(int n)
    
    {
      printf("%d\n",n);       /* this prints the current values of n */
      if ( n != 0)                 /*  each time function is called   */
        {
          puzzle(n/2);
          putchar('0'+n%2);
        }
    }

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Ok I used the Step-by-Step option on my IDE. Here is whats going on in simpler terms then doubleanti used:

    If the number doesn't equal 0 it makes another call to puzzle() without leveling the current call. This happened 5 times in this case. After it reaches 0 it starts to leave the most recent call and procedes to the putchar().

    The ; is not a break symbol. It is an "end of command" symbol. The command "break" does stop a loop (don't know about if statements) however.

    Hope this helps.

  3. #3
    Unregistered
    Guest

    beginner question here

    (1) what is your IDE, what is that ??? How do I know what mine is and how to do this Step-By-Step??

    (2) the function was called 5 times till it equalled 0
    and then proceeded to the putchar or it was processing
    the putchar command after each instance the function
    called until the function equalled 0???

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The A-Bomb of Board Discussion: --
    By Aran in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 10-21-2001, 10:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21