function-loop-if statment
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
"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 Kommentare
Antworten (1)
Dhanesh R
am 21 Mai 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 Kommentare
Dhanesh R
am 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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!