8. It is possible to check if an integer is divisible by 9 by summing its digits: if the digits add up to 9 the number is divisible by 9. For integers up to 90 only a single application of the rule is required. For larger integers, multiple applications may be required. For example, for 99, the digit sum is 18. Then, because 18 still has multiple digits we sum them again to get 9, confirming that 99 is divisible by 9 (after two steps). In general, for a given starting number, you should repeatedly sum the digits until the result is a single digit number. Write a MATLAB script m-file to read in a single number from the keyboard, and use the rule to determine if it is divisible by 9. An appropriate message should be displayed depending on the result. You can assume that the number will always be less than 10,000. [Hints: • To extract the digits of a number use the function ch=num2str(x,'%d'); ch will be an array containing the digits as characters • To convert a character to a number use x1=str2num(ch1)
Ans
code:-
num=input('Enter number');%input no
ch = num2str(num,'%d');%to array
s=0;%to store sum
while length(ch)~=1 %while digit>1
for i=1:length(ch) %for each digit
x1=ch(i);%
s=s+str2num(x1);%add to s
end
ch=num2str(s,'%d');%to string
s=0;
end
%if digit is 0 or 9 print
if (str2num(ch)==0||str2num(ch)==9)
fprintf('Divisible by 9\n');
else %if not then print
fprintf('Not divisible by 9');
end
.
.
.
If any doubt ask in the comments.
Get Answers For Free
Most questions answered within 1 hours.