Swift practice: Guess my number using a “while” loop

This example serves to demonstrate the use of a “while” loop. The code below implements a guessing game where the program chooses a random number between 1 and 10, and repeatedly prompts the user to guess the number until they guess correctly.

var guessedNumber = Int.random(in: 1...10)
var secretNumber = Int.random(in: 1...10)

while guessedNumber != secretNumber {
  guessedNumber = Int.random(in:1...10)
  secretNumber = Int.random(in:1...10)
  print("You guessed \(guessedNumber), and the number was \(secretNumber)" )
}

/* Possible Output
You guessed 7, and the number was 10
You guessed 4, and the number was 1
You guessed 8, and the number was 2
You guessed 3, and the number was 5
You guessed 9, and the number was 8
You guessed 9, and the number was 3
You guessed 10, and the number was 4
You guessed 6, and the number was 2
You guessed 4, and the number was 8
You guessed 10, and the number was 10
*/

Quick notes

The variables

  • The line “var guessedNumber = Int.random(in: 1…10)” initializes the “guessedNumber” variable with a random integer between 1 and 10 using the “random(in:)” function on the “Int” type.
  • The line “var secretNumber = Int.random(in: 1…10)” initializes the “secretNumber” variable with another random integer between 1 and 10.
  • The “while” loop continues to execute as long as “guessedNumber” does not equal “secretNumber”.
  • In other words, the loop will keep running until the user correctly guesses the random number.

The loop

  • Within the loop, the program generates a new random integer for “guessedNumber” and “secretNumber”. This means that the numbers change each time the loop is executed.
  • The program then prints a message telling the user what number they guessed and what the secret number was.
  • The loop continues running until they guess the correct number, and the program generates new random numbers each time they guess.

Leave a Reply

Your email address will not be published. Required fields are marked *