I am working on kaprekars constant homework, and everytime I write a while loop I get error.
Show older comments
The idea behind the code is that when you put numbers in an array it will sort in ascending and decending order, and then subtract until I get kaprekars constant 6174. My code works for one iteration, but as soon as I try to write a while loop it put out an error message. I am at my wits end here. The moment the bolded parts go in, the code will not run. If i define n as a number, the code will run, but will keep n as the number.
n=1;
while (n==6174)
if ~(n==6174)
a=input("enter number a:");
b=input("enter number b: ");
c=input("enter number c: ");
d=input("enter number d: ");
if (a==b)&&(b==c)&&(c==d)
fprintf("error! please enter atleast two different digits ")
end
%puts four digits into an array
arr=[a b c d];
for i=1:1:4
%sorts array in ascending order
B=sort(arr);
%sorts array in descending order
C=sort(arr,'descend');
end
%converts array into string data for ascending order
arr2= [B];
y = 0;
for j = 1:length(arr2)
y = y + (10^(j-1))*arr2(length(arr2)+1-j);
end
%converts array into string for descending order
arr3= [C];
z = 0;
for k = 1:length(arr3)
z = z + (10^(k-1))*arr3(length(arr3)+1-k);
end
n=z-y;
fprintf("%.0d-%.0d=%.0d\n",z,y,n)
arr=(n);
end
break ;
end
Accepted Answer
More Answers (0)
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!