Clear Filters
Clear Filters

While loop - Factorial

22 views (last 30 days)
Gyp
Gyp on 31 Jan 2020
Commented: Rik on 31 Jan 2020
The problem I have is that when I write a negative number, I want what I set out to come out. When I do it for the first time it works and I can re-enter a number. But when for the second time I put a negative number (to prove that it works) the program prints an incorrect number, instead of asking again to put a new number (not negative).
Ex. I put -1 and get: "n = input ('The factorial function is defined for non-negative integers only.Enter a non-negative number:').
If I try to put -1 again, the factorial number of -1 is 1.
How can I correct it to keep asking for a new number as long as they put a negative one?
Thanks
Screenshot (331).png
  1 Comment
Rik
Rik on 31 Jan 2020
Next time, post code instead of an image, and add the tag homework if you post homework.

Sign in to comment.

Answers (1)

Rik
Rik on 31 Jan 2020
You need to repeat the exact same code until some condition is true. The easiest way to do that is with a while loop:
n=-1;%set initial input to something invalid to enter the loop
while %check input
%if input is invalid, repeat input
end
%now calculate the factorial
  2 Comments
Rik
Rik on 31 Jan 2020
Comment posted as answer by Gyp:
Hi Rick, i think i'm doing that. I have the "while" code for positive numbers only.
But when a put a negative number, just to verify, this give me a results... I don't want the program to give me a result when a negative number is written. I just want the program to ask for a number again.
Rik
Rik on 31 Jan 2020
You aren't doing that. You should be separating the two tasks (getting the input and calculating the factorial). What you showed in your question is not doing that. Try filling in what I wrote above:
n=-1;%set initial input to something invalid to enter the loop
while %check input
%if input is invalid, repeat input
end
%now calculate the factorial
%%% here the code goes that actually calculates the factorial
That means your final code will contain two while loops.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!