for command display too much info

1 view (last 30 days)
Adam
Adam on 4 Oct 2014
Answered: Image Analyst on 4 Oct 2014
I have been messing with this code for about an hour now and I am really close to being done. My problem is in fprintf I believe. I just want the last line to display. Here is my code.
int = input('Enter a number between 1 and 25: ');
if (int<1)||(int>25)
int = input('Invalid number enter another between 1 and 25: ');
end
fact = 1;
for i=int:-1:2;
fact = fact *i;
fprintf('The factoral of %g is %g\n',int,fact);
end
Also, I know there is a factoral command but my professor does not want us using it.
I have one more small thing that has been bugging me. We are supposed to ask the user if they are done and end the program if the user types y or Y. I'm just not sure how to get the program to identify a capital letter as well as lower case. I thought it would be something like this but it does not work.
done = input('Are you done? Type y for yes. ','s');
while done~='y'||done~='Y'
Thanks for any help everyone!
  1 Comment
Guillaume
Guillaume on 4 Oct 2014
I'm not sure what the title of the question has got to do with your actual question.

Sign in to comment.

Answers (2)

Guillaume
Guillaume on 4 Oct 2014
There are many ways to do this, one possibility:
while true
%your code here
done = input('Are you done? Type y for yes. ','s');
if done == 'y' || done == 'Y'
break %terminate while loop
end
end
If you don't like that while true you could also do:
done = 'N'; %so it goes through the loop at least once.
while done ~= 'y' && done ~= 'Y'
%your code
done = input('Are you done? Type y for yes. ','s');
end

Image Analyst
Image Analyst on 4 Oct 2014
Close, but you need two while loops. One to ask if they want to do it again, and one to keep asking until they enter a valid number that is in the required range. Here, try this:
clc;
% Initialize some things.
int = -1;
done = 'n';
% Loop over asking if they want to continue.
% Enter loop if done is not 'Y' or 'y'
while ~strcmpi(done, 'y')
% Loop over getting a valid (in range) number.
while (int<1)||(int>25)
int = round(input('Enter a number between 1 and 25: '));
if (int<1)||(int>25)
int = input('Invalid number enter another between 1 and 25: ');
end
end
fact = 1;
for k = int : -1 : 2;
fact = fact * k;
end
fprintf('The factorial of %g is %g\n',int,fact);
done = input('Are you done? Type y for yes, or n to continue: ','s');
% Reset int so next time we'll ask again.
int = -1;
end

Products

Community Treasure Hunt

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

Start Hunting!