to print following pattern

8 views (last 30 days)
Arpit Jain
Arpit Jain on 22 May 2019
Commented: KALYAN ACHARJYA on 22 May 2019
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

Accepted Answer

Rik
Rik on 22 May 2019
You mean like this?
for k=1:9
a=str2double(char('0'+(1:k)));
b=a*8+k;
fprintf('%d x 8 + %d = %d\n',a,k,b)
end

More Answers (2)

Stephen23
Stephen23 on 22 May 2019
Edited: Stephen23 on 22 May 2019
Three lines, no loop, and only basic numeric operations used:
>> X = 1:9;
>> Y = floor((137174210/1111111111)*10.^X);
>> fprintf('%d x 8 + %d = %d\n',[Y;X;Y.*8+X])
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
  1 Comment
KALYAN ACHARJYA
KALYAN ACHARJYA on 22 May 2019
Auu.. Matlab Master ..Without Loop..Great @Stephan +1

Sign in to comment.


KALYAN ACHARJYA
KALYAN ACHARJYA on 22 May 2019
Edited: KALYAN ACHARJYA on 22 May 2019
Today I lerned this polyval function, thats why I have posted 2nd answer, although the correct answer already given by @Rik
for i=1:9
value=polyval((1:i),10);
result=value*8+i;
fprintf('\n %d x 8 + %d = %d',value,i,result);
end
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321
  2 Comments
Rik
Rik on 22 May 2019
That's nice lateral thinking with polyval. Note that our answers return different answers after 9:
%my answer:
NaN x 8 + 10 = NaN
%polyval:
1234567900 x 8 + 10 = 9876543210
That is caused by my trick with char. If you avoid that, you can also generate this:
12345678910 x 8 + 10 = 98765431290
%replace this:
a=str2double(char('0'+(1:k)));
%with this:
c=cell2mat(cellfun(@num2str,num2cell(1:k),'Uni',0));
a=str2double(c);
KALYAN ACHARJYA
KALYAN ACHARJYA on 22 May 2019
Yes @Rik Thanks

Sign in to comment.

Categories

Find more on Programming 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!