function prodby2 with for loop that will give you product of odd integers

1 回表示 (過去 30 日間)
Nabin SUNAM
Nabin SUNAM 2015 年 2 月 6 日
コメント済み: asma sarouji 2018 年 11 月 1 日
I"m having hard time with this question:
Write a function prodby2 that will receive a value of a positive integer n and will calculate and return the product of the odd integers from 1 to n(or from 1 to n-1 if n is even). Use a for loop.
This is what I tried,
unction runprod = prodby2(n)
runprod = 1:2:n;
for i = 1:(ceil(n/2))
temp = runprod
runprod = temp*runprod
end
end
Any help please !!!

回答 (1 件)

Jason Moore
Jason Moore 2015 年 2 月 6 日
The following function should produce what you are looking for
function output = prodby2(n)
if n>0
output = 1;
for i=1:n
%check using modulo if the number is an odd number
if mod(i,2)
output = output*i;
end
end
else
output = 0;
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by