Change for loop to while loop.
3 views (last 30 days)
Show older comments
I need to convert this code from the for loop to while loop but when I tried to do so, it always comes out as error. Please help :(
n = input ("Input a number: ");
fprintf("\nOdd number: ");
for i = 1:2:n
fprintf("%d ",i);
end
fprintf("\nEven number: ");
for i = 2:2:n
fprintf("%d ",i);
end
fprintf("\nSum of Even numbers: ");
sum = 0;
for i = 2:2:n
sum = sum + i;
end
fprintf("%d",sum);
prod = 1;
fprintf("\nProduct of Odd numbers: ");
for i = 1:2:n
prod = prod*i;
end
fprintf("%d",prod);
5 Comments
DGM
on 24 Apr 2022
Again:
fprintf('\nProduct of odd numbers: ')
x = 1;
odd_product = 1; % need to initialize to something nonzero
while x <= n % less than or equal to
odd_product = odd_product * x;
fprintf(' %d',odd_product) % not x
x = x+2; % increment x
end
Answers (2)
Dyuman Joshi
on 24 Apr 2022
%n = input ("Input an integer: ");
n=11;
fprintf('Odd numbers: ')
x=1;o=1;
while x<=n
fprintf(' %d',x)
o=o*x;
x=x+2;
end
fprintf('\nEven numbers:')
y=0;e=0;
while y<=n
fprintf(' %d',y)
e=e+y;
y=y+2;
end
fprintf('\nSum of even numbers: %d', e)
fprintf('\nProduct of odd numbers: %d', o)
0 Comments
DGM
on 24 Apr 2022
If you want to make things more complicated, you can:
n = 5; %input ("Input a number: ");
fprintf("\nOdd number: ");
i = 1;
while i <= n
fprintf("%d ",i);
i = i+2;
end
% and so on
0 Comments
See Also
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!