function-loop-if statment
1 view (last 30 days)
Show older comments
"Write a function that asks the user to input 10 numbers and calculates the sum of the odd numbers entered (use for loop + if)" I couldn't figure it out at all as functions cannot be added in loops, so im not sure
0 Comments
Answers (1)
Dhanesh R
on 21 May 2024
I didn't get you correctly. Did you mean this?
function addOnlyOddFromFirstTenNumbers(yourNumberArray)
% Specify your input argument
arguments
yourNumberArray (1, 10) uint64 {mustBeNonnegative, mustBeInteger}
end
% Initialize your output
sumOdds = 0;
% Perform condition based addition
for i = 1:max(10, length(yourNumberArray))
if rem(yourNumberArray(i), 2) ~= 0
sumOdds = sumOdds + yourNumberArray(i);
end
end
% Display your output
fprintf('Sum of odd numbers: %i\n', sumOdds);
end
2 Comments
Dhanesh R
on 8 Jul 2024
If you feel the condition placed in the for loop is compliated, you may simply keep it as follows. But then the array must contains 10 elements. If you input less number of elements, MATLAB would throw an error. If you enter more than 10 elements, the function would ignore these extra elements from summing up.
% for i = 1:max(10, length(yourNumberArray))
for i = 1:10
% ...
end
The arguments block can also be ignored if you find it complicated. This block is only to validate the input. You must provide a non-negative integer array.
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!