I am trying to do a problem without using for/while loops and with recursion. The problem gives you an input in this format:
where "2" is the number of queries and each query contains the length of a list of digits followed by the digits. I need to scan in all the information and print out the sum of the digits(in this case 3 -1 1 14 and 9 6 -53 32 16). I am trying to use recursion to scan in the digits, but I can't seem to scan them in properly. Does any
package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
recur(n)
}
func print_sum(l int, sum int) int {
if l == 0 {
return sum
}
var next_digit int
fmt.Scan(next_digit)
print_sum(l-1, sum next_digit)
return 0
}
func recur(queries int) {
if queries == 0 {
return
}
var next_len int
fmt.Scan(next_len)
print_sum(next_len, 0)
recur(queries - 1)
}
CodePudding user response:
I was able to figure out the solution, here is the code if anyone wants to look at it: https://github.com/allenye66/Recursive-Sum-of-Squares
CodePudding user response:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main (){
var t int
fmt.Printf("number of time : ")
fmt.Scanln(&t)
for i:=0;i<t;i {
ScanAndSum()
}
}
func ScanAndSum(){
var (
n int
li []string
li2 []int
ans int
)
fmt.Scanln(&n)
a,_,_:=bufio.NewReader(os.Stdin).ReadLine()
li= strings.Split(string(a)," ")
for i:=0;i<n ;i {
s,_:=strconv.Atoi(li[i])
li2=append(li2,s)
ans =s
}
fmt.Println("array : ",li2)
fmt.Println("sum : ",ans)
}