Clear Filters
Clear Filters

function-loop-if statment

2 views (last 30 days)
Raghad
Raghad on 21 May 2024
Commented: Dhanesh R on 8 Jul 2024
"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

Answers (1)

Dhanesh R
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
Raghad
Raghad on 21 May 2024
Thank you! Yes this seems to be the answer, however it does seem a little too complicated for the course level we took, is there no other simplier method to solve this?
Dhanesh R
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.

Sign in to comment.

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!