Home > Software design >  How to find sum of integers using recursion(without loops) in Golang?
How to find sum of integers using recursion(without loops) in Golang?

Time:01-05

Program should ask values "number of numbers" and "numbers" for each "number of inputs", answers are sum of squares of these numbers. My code works but it shows answers in wrong order, how to make it work properly?

I think its easier to understand this program by reading inputs and outputs:

Enter the number of inputs // output
2 // input
Enter the number of numbers // output
2 // input
Enter the numbers // output 
1 2 // input (second ans)
Enter the number of numbers // output 
2 // input
Enter the numbers 
2 3 // input (first ans)
ans =  13 // ans = 2^2   3^2
ans =  5 () // ans = 1^2   2^2

MyCode:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin) 
    fmt.Println(`Enter the number of inputs`)
    n, _ := reader.ReadString('\n') 
    n = strings.TrimRight(n, "\r\n") 
    test_cases, err := strconv.Atoi(n) 
    if err != nil {
        fmt.Println(err)
    }
    process_test_case(test_cases, reader)
}

func process_test_case(test_cases int, reader *bufio.Reader) {
    fmt.Println(`Enter the number of numbers`) 
    _, _ = reader.ReadString('\n') 
    fmt.Println(`Enter the numbers`) 
    input, _ := reader.ReadString('\n') 
    input = strings.TrimRight(input, "\r\n") 
    arr := strings.Split(input, " ") 

    test_cases -= 1

    if test_cases != 0 {
        process_test_case(test_cases, reader)
    }
    fmt.Println("ans = ", process_array(arr, 0))
    
}

func process_array(arr []string, result int) int {
    num, _ := strconv.Atoi(arr[0]) 
    if len(arr) > 1 {
        next := arr[1:] 
        if num < 0 {
            num = 0
        }
        result = num*num   process_array(next, result)
        return result
    } else {
        if num >= 0 {
            return num * num
        }
        return 0
    }
}

CodePudding user response:

I have created a sample code for your scenario. You can modify it by using bufio.NewReader(os.Stdin)

func process_array(arr []string) int {

    res := 0
    for _, v := range arr {
        num, err := strconv.Atoi(v)
        if err != nil {
            panic(err)
        }
        fmt.Println("num :", num)

        res  = num * num
    }
    return res
}

func process_test_case() int {
    fmt.Println(`Enter the number of numbers`)
    num := 2
    fmt.Println("number of numbers :", num)

    fmt.Println(`Enter the numbers`)
    input := "1 2"
    fmt.Println("the numbers :", input)
    arr := strings.Split(input, " ")
    res := process_array(arr)
    return res
}

func main() {
    fmt.Println(`Enter the number of inputs`)
    test_cases := 1
    fmt.Println("number of inputs :", test_cases)

    for test_cases >= 1 {
        res := process_test_case()
        fmt.Println(res)
        test_cases -= 1
    }

}

You can run it here : https://go.dev/play/p/zGkAln2ghZp

OR

As commented by @phonaputer you can change the sequence. Return the slice and print it from the end.

CodePudding user response:

I think this code answer your title of the question:

package main

import "fmt"

func SumValues(x int, y ...int) (sum int) {
    q := len(y) - 1
    sum = y[q - x]
    if x < q {
        sum  = SumValues(x   1, y...)
    }
    return sum
}

func main() {
    sum := SumValues(0,1,2,3,4,5)
    fmt.Println("Sum is:", sum)
}
  •  Tags:  
  • Related