Find the sum of a list of numbers in Perl


In this article , simply create a array (@list) and assign elements into the array(@list).First find the sum of the list and second code is to find sum of odd numbers and even numbers separately of the array(@list) of numbers.


Sum of List Code :
@list = (1,2,3,4,5);
print "List is : ( @list )";
$sum = 0 ;
for $i(@list){
#print $i."\n";
$sum += $i;

}

print "\nSum of List : $sum";
Output of this Code :
List is : ( 1 2 3 4 5 )
Sum of List : 15
Sum of odd numbers and even numbers separately of a given list of numbers :
@list = (1,2,3,4,5);
print "List is : ( @list )";
$sumEven = 0 ;
$sumOdd = 0;
for $i(@list){
if($i%2 == 0){
$sumEven += $i;
}
else{
$sumOdd += $i;
}
}

print "\n Sum of Even numbers in List : $sumEven \n ";
print "\Sum of Even numbers in List : $sumOdd";

Output of this Code :
List is : ( 1 2 3 4 5 )
Sum of Even numbers in List : 6
Sum of Even numbers in List : 9

Post a Comment

Thank you for vising

أحدث أقدم