MATLAB: Having trouble with while loops problem

loopsMATLAB

I'm required to write a program what will accept positive numbers, and calculate both the average of them and the geometric mean(nth root of (x1*x2*x3…*xn). While loops are to be used to get the input numbers, and terminate the inputs that are negative. While loops in general confuse me so can you please tell me what i did wrong.
ttotal=0;
total=0;
cnt=0;
x=1;
y=1;
while x>=0
x=input('Please enter a positive number:');
cnt=cnt+1;
total=(total+x)/cnt;
if x<0
break;
end
while y>=0
y=input('Please enter a positive number:');
cnt=cnt+1;
ttotal=(ttotal*y)^(cnt/2);
if y<0
break;
end
fprintf('The geometric mean is %g',ttotal)
fprintf('The average of the inputed numbers is %g',total)
end
end
fprint('Program-Terminated')

Best Answer

Here are some things that are wrong:
  1. You're entering separate numbers x,y for the arithmetic and geometric means (you should be using x for both).
  2. Initially ttotal is zero, so every time you multiply it by something you get zero (try 1).
  3. If x<0, break, end is redundant (it's going to exit anyway at the top of the loop).
  4. You should save division by cnt to the end (otherwise you're dividing by 1, 2, 3, etc.). Ditto for the power of cnt/2.