Last active
November 7, 2020 16:17
-
-
Save kunal768/ae16d38f70010ee5606c4218366268ea to your computer and use it in GitHub Desktop.
Go program to print sum of squares of positive integers from given spaced integers without using a 'for' statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
"strconv" | |
"bufio" | |
) | |
func main(){ | |
reader := bufio.NewReader(os.Stdin) | |
testcases, _ := reader.ReadString('\n') | |
testcases = strings.TrimRight(testcases, "\r\n") | |
t, err := strconv.Atoi(testcases) | |
if err != nil { | |
fmt.Println(err) | |
} | |
var final = []int{} | |
solve(t, &final, reader) | |
recursively_print(final) | |
} | |
func solve(testcases int, final *[]int, reader *bufio.Reader) { | |
if testcases == 0 { | |
return | |
} | |
/* procedure */ | |
_, _ = reader.ReadString('\n') | |
input, _ := reader.ReadString('\n') | |
input = strings.TrimRight(input, "\r\n") | |
arr := strings.Split(input, " ") | |
ans := addsquares(arr, 0) | |
*final = append(*final, ans) | |
solve(testcases-1, final, reader) | |
} | |
func addsquares(input []string, ans int) int { | |
num, _ := strconv.Atoi(input[0]) | |
if len(input) > 1 { | |
if num > 0 { | |
return addsquares(input[1:], ans + num*num) | |
} else { | |
return addsquares(input[1:], ans) | |
} | |
} else { | |
if num < 0 { | |
return ans | |
} | |
return ans + num * num | |
} | |
} | |
func recursively_print(input []int){ | |
if(len(input)) > 0 { | |
fmt.Println(input[0]) | |
recursively_print(input[1:]) | |
} else { | |
return | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment