Golang Program to Print the Sum of all the Positive Numbers and Negative Numbers in a List


Steps

  • Read a number of elements to be in a list.
  • Take the elements from the user using a for loop and append to a list.
  • Using a for loop, get the elements one by one from the list and check if it is positive or negative.
  • If it is positive, check if it is odd or even and find the individual sum.
  • Find the individual sum of negative numbers.
  • Print all the sums.
Enter the number of elements to be in the list: 4
Element: -12
Element: 34
Element: 35
Element: 89
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12
Enter the number of elements to be in the list: 5
Element: -45
Element: -23
Element: 56
Element: 23
Element: 7
Sum of all positive even numbers: 56
Sum of all positive odd numbers: 30
Sum of all negative numbers: -68

Example

 Live Demo

package main
import "fmt"
func main() {
   fmt.Printf("Enter the number of elements to be in the list:")
   var size int
   fmt.Scanln(&size)
   var arr = make([]int, size)
   for i:=0; i<size; i++ {
      fmt.Printf("Enter %d element: ", i)
      fmt.Scanf("%d", &arr[i])
   }
   sum1:=0
   sum2:=0
   sum3:=0
   for i:=0; i<size; i++{
      fmt.Println(i)
      if arr[i] > 0{
         if arr[i]%2==0 {
            sum1=sum1+arr[i]
         }else{
            sum2=sum2+arr[i]
         }
      } else {
         sum3=sum3+arr[i]
      }
   }
   fmt.Println("Sum of all positive even numbers:", sum1)
   fmt.Println("Sum of all positive odd numbers:", sum2)
   fmt.Println("Sum of all negative numbers:", sum3)
}

Output

Enter the number of elements to be in the list:4
Enter 0th element: -12
Enter 1 element: 34
Enter 2 element: 35
Enter 3 element: 89
0
1
2
3
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12

Updated on: 31-Jul-2021

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements