Golang Program to print 1 to 100 using recursive function


February 27, 2022, Learn eTutorial
1080

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

Recursive function

A recursion function is a function code that refers to itself for execution. The process may repeat several times, outputting the result at the end of each iteration. The function calls directly or indirectly itself until a suitable condition is met..

How to print 1 to 100 using a recursive function in the GO Program

Here we are showing to print 1 to 100 using a recursive function in the Go language. Here the variable number is first assigned with and call the recursive function. Inside the function check the number num is less than 100 if true print that number and recursively call the function with num+1. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable number assign it with value 1

STEP 4: Call the function as numberPrint(number)

STEP 5:Define the function numberPrint(num int)

STEP 6: Inside the function check if num <= 100

STEP 7: If true, print the variable num using fmt.Println()

STEP 8: Recussively call the function as numberPrint(num + 1)

 

Golang Source Code

                                          package main
import "fmt"

func numberPrint(num int) {
    if num <= 100 {
        fmt.Print(num, "\t")
        numberPrint(num + 1)
    }
}
func main() {

    number := 1
    numberPrint(number)
}
                                      

OUTPUT

1     2    3    4     5    6    7    8     9    10
11  12  13  14  15  16  17  18  19  20
21  22  23  24  25  26  27  28  29  30
31  32  33  34  35  36  37  38  39  40
41  42  43  44  45  46  47  48  49  50
51  52  53  54  55  56  57  58  59  60
61  62  63  64  65  66  67  68  69  70
71  72  73  74  75  76  77  78  79  80
81  82  83  84  85  86  87  88  89  90
91  92  93  94  95  96  97  98  99  100