don't understand the order of this code lines.

Mairiaux Philippe 21 Reputation points
2021-06-20T09:22:37.46+00:00

Hi

could somebody explain me how this code works?
Suppose number = 123. This code gives '1' '2' and '3'.

I came to the conclusion that the last line (Console.Write(" {0} ", n % 10);) which is 23, is executed once when the return is reached. But how is that possible because the return is in another block of code? What is teh logical order of this code?
Thanks

static void Main()
{
Console.Write(" Give a number: ");
int num = Convert.ToInt32(Console.ReadLine());
Console.Write(" The digit of {0} are: ", num);
cijfers(num);
Console.Write("\n\n");
}

static void cijfers(int n)
{
    if (n < 10)            
    {
        Console.Write("  {0}  ", n);
        return;
    }
    cijfers(n / 10); 
    Console.Write("  {0} ", n % 10);
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,500 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,511 Reputation points
    2021-06-21T03:07:28.32+00:00

    Why with number 123 are the two last lines executed after 'return' and not with number '1'

    This is a recursive method. Don't think of it as one method. When the number is 123, these are three methods.

    107386-1.png

    After the return is executed, as we know, the code after the return statement in this method will not be executed, but this will not affect other methods.

    In this example, return is executed only once in the last method. In the first two methods, the code does not enter the if block.

    It might be easier to understand to translate it into a normal method, it's like(when number is 123):

            static void cijfers(int n)  
            {  
                cijfers1(n / 10);  
                Console.Write("  {0} ", n % 10);  
            }  
            static void cijfers1(int n)  
            {  
                cijfers2(n / 10);  
                Console.Write("  {0} ", n % 10);  
            }  
            static void cijfers2(int n)  
            {  
                Console.Write("  {0}  ", n);  
                return;  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful