Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

#Day16- #100DaysChallenge- Matlab Loops| Even and Odd details in the given list

#Day16-Even and Odd details in the given list

Task:
Take the lists' end value from the user, starting from 1 till user-entered value find the sum of even numbers, total even numbers, and the sum of odd numbers, total number Odd numbers.

Note: This code can be done using the in-built command. But for the challenge, I am trying to avoid those

Example list1:1,2,3,4,5,6,7,8,9,10

sum_even =


    30

sum_odd =

    25 

n_even =

     5 

n_odd =

     5 
1+3+5+7+9

ans =

    25

2+4+6+8+10

ans =

    30

Matlab Code:
function [sum_even,sum_odd,n_even,n_odd]=even_odd(x)
sum_even=0;
sum_odd=0;
n_even=0;
n_odd=0;
for i=1:1:x
    if mod(i,2)==0
        sum_even=sum_even+i;
       n_even=n_even+1;
    else
                              
    sum_odd=sum_odd+i;
    n_odd=n_odd+1;
    end
    
 end

Sample Input and Output
>> [sum_even,sum_odd,n_even,n_odd]=even_odd(79)

sum_even =

        1560


sum_odd =

        1600


n_even =

    39


n_odd =

    40

>> [sum_even,sum_odd,n_even,n_odd]=even_odd(40)

sum_even =

   420


sum_odd =

   400


n_even =

    20


n_odd =

    20

Click Here for Video Description



Join us on Telegram:https://t.me/matlabirawen
Join us on Facebook Group:https://www.facebook.com/groups/matlabcodes


No comments

Popular Posts

Followers