I have to find the sum of number after performing square operation in the given input the negative numbers need to be ignored. The input Format is, first line is number of test cases followed by N as number of test inputs in new line followed by N space seperated numbers. The task need to be done using golang without using for loop. Output need to be print in new line for each test case.
3
4
3 -1 1 14
5
9 6 -53 32 16
6
3 -4 12 2 5 7
Below is my attempt to achieve the task using recurrsion.
package main
import "fmt"
func findSquareSum(x int, a []int, iteration int) {
var num int
if x > 0 {
fmt.Scanf("%d", &num)
if num > 0 {
a[iteration-1] += num * num
}
findSquareSum(x-1, a, iteration)
}
}
func readTest(x int, a []int){
var input int
if x > 0{
fmt.Scanf("%d", &input)
findSquareSum(input,a,x)
readTest(x-1,a)
}
}
func printResult(x int, a []int){
if (x > 0){
fmt.Println(a[x-1])
printResult(x-1,a)
}
}
func main() {
var test int
fmt.Scanf("%d", &test)
a := make([]int, test)
readTest(test,a)
printResult(test,a)
}
My question is as there is no base case in the recursive function. How the programm is working as per expectations?
1 Answer 1
There is a base case... it's the line if x > 0 {
compare to the for loop version
for x=input: x>0: x=x-1 {
findSquareSum(input,a,x)
sets x=input
if x > 0 {
is the condition check
findSquareSum(x-1, a, iteration)
decrements x
also consider the modified fucntion
func findSquareSum(x int, a []int, iteration int) {
var num int
if x <= 0 { return }
fmt.Scanf("%d", &num)
if num > 0 {
a[iteration-1] += num * num
}
findSquareSum(x-1, a, iteration)
}
now it should look more like the base cases we are to seeing. It should also be clear that this is equivalent to the askers version (unless my go syntax is wrong!)
similarly
func readTest(x int, a []int){
var input int
if x <= 0 { return }
fmt.Scanf("%d", &input)
findSquareSum(input,a,x)
readTest(x-1,a)
}