MATLAB: While loops beginner. creating a program but stuck on the concept.

new programmeroctavewhilewhile loopwhile loops

im new to while loops and programming in general and im supposed to create a program where the user will enter their starting balance and they can choose to deposit or withdraw a certain amount of money. With every transaction the program will display their new balance. I will also have to write the program so that if their balance is 0 they will see a message saying they dont have money and if its less than 0 to display they have no money and their overdraft. this is the program i have written so far but im still having a little bit of difficulty understanding the concept behind while loops. so when i run my program the while part doesnt run at all and im not sure if the rest of the program is right either.
balance = input('Enter your starting balance: ');
withdraw = input('withdraw amount: ');
deposit = input('deposit amount: ');
while balance < 0
balance = balance - withdraw
fprintf('You have an outstanding balance of %.2f dollars.', balance);
endwhile
disp('end');

Best Answer

The requirements you set out for us do not have any termination condition. You are supposed to repeatedly ask the user what transaction they want to make, but there is no way stated for the user to indicate that they want to stop. In such a case, where the while loop is to run forever, the condition you give for the while loop should be a condition that is certain to be true. For example,
while true
or
while 1 < 2
or
the_universe_still_exists = true;
while the_universe_still_exists
I would suggest to you that you enhance the options so that the user has a choice to quit as well. For example,
withdrawl = 1;
deposit = 2;
quit = 3;
choice = menu('Choose a transaction', 'Withdrawl', 'Deposit', 'Quit');
while choice == withdrawl || choice == deposit
now do something here
%then
choice = menu('Choose another transaction', 'Withdrawl', 'Deposit', 'Quit');
end
Related Question