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

조회 수: 13 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by