Thursday, May 8, 2014

Find the sum of a list of numbers in Perl

Posted By: Achchuthan Yogarajah - 5/08/2014 08:12:00 PM

Share

& Comment


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

About Achchuthan Yogarajah

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Believe in Yourself - Achchuthan Yogarajah ACHCHUTHAN.ORG. Designed by Templateism .