jkPlayer998
jkPlayer998

Reputation: 13

Can someone please explain why does a piece of code work the same as mine?

I completed an exercise and wrote this code:

  var random = new Random();

    var number = random.Next(1, 10);

    Console.WriteLine(number);

    var control = 0;

    for (int i = 0; i < 4; i++)
    {
        Console.WriteLine("Enter a number: ");
        var guessedNumber = Convert.ToInt32(Console.ReadLine());

        if (guessedNumber == number)
        {
            Console.WriteLine("You won");
            control = 1;
            break;
        }
    }

    if (control == 0)
    {
        Console.WriteLine("You lost");
    }

And the answer is this:

 var number = new Random().Next(1, 10);

        Console.WriteLine("Secret is " + number);
        for (var i = 0; i < 4; i++)
        {
            Console.Write("Guess the secret number: ");
            var guess = Convert.ToInt32(Console.ReadLine());

            if (guess == number)
            {
                Console.WriteLine("You won!");
                return;
            }
        }

        Console.WriteLine("You lost!");

I have added the control variable because if I didn't even if the user guessed the number it would still display "You lost".

Can someone explain what does "return" do in the other code and why if the user guesses the correct number it doesn't display "You lost"?

Upvotes: 0

Views: 78

Answers (2)

b2f
b2f

Reputation: 349

The Code is as I suppose packed in a function or main. This function has a return type. The function here maybe looks like this:

public void NumberGuessing()
{
    .... code here ....
}

With the return statement you jump directly out of this block. As the return type of the function is void, there is no value and a simple return will jump out of the function and everything after the return statement is not executed.

The break just exits the loop, but not the function.

Upvotes: 2

AndersK
AndersK

Reputation: 36082

your function is supposed to stop when you find the correct answer so return seems more logical, it eliminates the need for your extra control variable making the code simpler to read and less error prone (e.g. for changes in the future like find two correct answers).

Upvotes: 1

Related Questions