1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab Programming

  1. Oct 15, 2014 #1
    1. The problem statement, all variables and given/known data
    Write a program for a simple guessing game. The program should first prompt the user for a
    number between 1 and 100. After each guess the program should inform the user whether the guess was too high or too low. When the user picks the correct number, inform them and let them know how many guesses it took. Also, after the correct number has been picked, ask them if they would like to play again. If they enter 'N' the program should terminate. If they enter 'Y' the program should run again, prompting the user to guess a new random number.

    2. Relevant equations

    3. The attempt at a solution
    I have had no problem doing the first part of the program, this is my code thus far:
    TargetNum = randi(100);
    UserGuess = 0;
    GuessNumber = 0;

    while ((UserGuess ~= TargetNum))
    GuessNumber = GuessNumber + 1;
    UserGuess = input('Guess an integer between 1 and 100 \n');
    if (UserGuess < TargetNum)
    fprintf('The number "%i" is too low \n', UserGuess)
    elseif (UserGuess > TargetNum)
    fprintf('The number "%i" is too high \n', UserGuess)
    fprintf('You guessed the correct number: %i \n',TargetNum)
    fprintf('This required "%i" guesses \n', GuessNumber)

    However, I am having some trouble figuring out how to get the program to run again if the user decides to play again. I have experience using Java, so I am fairly knowledgeable when it comes to programming. However, in JAVA I would probably use a "Boolean" operator to get the program to run again, but I cannot do this in MatLab. I also decided to look up how to compare strings in MatLab using the "TF = strcmpi(string,string)" technique. However, I am unsure if this would work, or even how to go about doing it. Any advice on how to complete this program would be greatly appreciated. Thanks.
  2. jcsd
  3. Oct 15, 2014 #2


    Staff: Mentor

    Can't you use a while loop around your computation that runs if the user says yes? and for the first iteration you set the condition to yes.

    If there's no boolean then use an integer value 0 = false and 1= true.
  4. Oct 15, 2014 #3
    Last edited: Oct 15, 2014
  5. Oct 15, 2014 #4
    Ok I think I understand what you mean...I'm going to try it out and get back to you..
  6. Oct 15, 2014 #5
    Last edited: Oct 15, 2014
  7. Oct 15, 2014 #6
    Ok, I got it too work thanks to your suggestion, thanks :)
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted