Golang Program to Print the Numbers in a Range (1, upper) without Using any Loops

Go ProgrammingServer Side ProgrammingProgramming

Steps

  • Define a recursive function.
  • Define a base case for that function that the number should be greater than zero.
  • If the number is greater than 0, call the function again with the argument as the number minus 1.
  • Print the number.
Enter the upper limit: 5
1
2
3
4
5
Enter the upper limit: 15
1
2
.
.
15

Example

 Live Demo

package main
import (
   "fmt"
)
func printNo(number int){
   if number >= 1{
      printNo(number-1)
      fmt.Println(number)
   }
}
func main(){
   var upper int
   fmt.Print("Enter the upper limit: ")
   fmt.Scanf("%d", &upper)
   printNo(upper)
}

Output

Enter the upper limit: 5
1
2
3
4
5
raja
Published on 31-Jul-2021 15:42:23
Advertisements