How can I end a for-loop when a condition is met?

14 views (last 30 days)
Hey,
I need to write a piece of code that asks the user to input a value for a temperature in degrees Celsius in the command window (number + ‘enter’) and computes the equivalent temperature in degrees Fahrenheit. For that I used the formula tfahr = 9/5 x tcels + 32. The script should keep running until the user presses the keys q + ‘enter’ in the command window.
This is what I have so far. However, the code is stopping after I entered a number but the program is supposed to keep running. Also, how do I implement that the program ends when I enter 'q'?
for value_celcius = input('Enter temperature in Celsius: ');
if isnumeric(value_celcius)
tfahr = 9/5 * value_celcius + 32;
disp(tfahr)
end
disp('End of program. Goodbye!')
end
Thanks for the help!

Answers (2)

Walter Roberson
Walter Roberson on 13 Dec 2020
while true
value_str = input('Enter temperature in Celsius: ', 's');
value_celcius = str2double(value_str);
if isnan(value_celcius)
break;
end
tfahr = 9/5 * value_celcius + 32;
disp(tfahr)
end
disp('End of program. Goodbye!')
You input in string mode in case the user enters non-numeric. You convert the string to double. If the user entered something that is not a valid scalar double, then str2double() returns nan.

Cris LaPierre
Cris LaPierre on 13 Dec 2020
Look into using a while loop instead of a for loop.
  2 Comments
Ari Hauser
Ari Hauser on 13 Dec 2020
Alright, I used a while loop instead, thanks! However, wow can I end the program with the input 'q'?
Cris LaPierre
Cris LaPierre on 13 Dec 2020
value_str = 'a';
while ~strcmpi(value_str,'q')
value_str = input('Enter temperature in Celsius: ', 's');
...

Sign in to comment.

Categories

Find more on MATLAB Mobile in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!