function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sneha gowdersneha gowder 

How to calculate the Odd sum in collection in apex ? can some help me with sample code

How to calculate the Odd sum in collection in apex ? can some help me with sample code
Best Answer chosen by sneha gowder
Raj VakatiRaj Vakati
Please refer the below sample code. You can get the odd values by using Math.mod(i, 2) != 0 . 
 
List<Integer> intList = new List<Integer>() ;
intList.add(10);
intList.add(20);
intList.add(30);
intList.add(40);
intList.add(50);
Integer sum =0 ; 
for(Integer i = 0 ; i<intList.size() ;i++){
   if (Math.mod(i, 2) != 0) {
   sum= sum+intList[i];
   }
    
}

System.debug('-->SUm'+sum);



Highlevel Priorioty

 

All Answers

Raj VakatiRaj Vakati
Please refer the below sample code. You can get the odd values by using Math.mod(i, 2) != 0 . 
 
List<Integer> intList = new List<Integer>() ;
intList.add(10);
intList.add(20);
intList.add(30);
intList.add(40);
intList.add(50);
Integer sum =0 ; 
for(Integer i = 0 ; i<intList.size() ;i++){
   if (Math.mod(i, 2) != 0) {
   sum= sum+intList[i];
   }
    
}

System.debug('-->SUm'+sum);



Highlevel Priorioty

 
This was selected as the best answer
Raj VakatiRaj Vakati
List<Integer> intList = new List<Integer>() ;
intList.add(10);
intList.add(20);
intList.add(30);
intList.add(40);
intList.add(50);
Integer sum =0 ; 
for(Integer i = 0 ; i<intList.size() ;i++){
   if (Math.mod(i, 2) != 0) {
   sum= sum+intList[i];
   }
    
}

System.debug('-->SUm'+sum);