Wednesday, July 31, 2019

Javascript - Array vs JSON vs Object basics with Examples

Array, JSON, Objects are valid objects used to interact and manipulate data in javascript applications. This post talks about the difference between an array, JSON and objects with examples.

Javascript Object Basics examples

Objects are the main building blocks of Object-oriented programming concepts. Objects can be used to carry the data in applications. There are predefined objects as well as can declared user-defined objects. Document and window are predefined objects in javascript. Objects can contain properties and functions. The object can also be used with an instance or object name Objects can be created in many ways, One way is using new operator and other is using object literal syntax.

Declare, initialize the object using new operator and constructor

The below is an example create an empty object using new operator with Object constructor. new is a keyword and operator to create an instance of an object. We can create an instance of the object using new operator followed by Constructor.
var firstObject = new Object(); 
console.log(firstObject) // {}
The above code creates an object and initializes with an empty object.

Declare, initialize the object using Object literal

An empty object can also be created and initialized with object literals. Object literals are enclosed in curly braces with data
var firstObject = {}; 
console.log(firstObject) // {}
or
object can be created with object literals data
var obj={"kiran":"test"}
This is preferred the way of creating object

declare assign properties to javascript object

javascript object contains properties. each property can be primitive type - Boolean, null, undefined, number, string, and symbol or any object
var firstObject = {}; 
firstObject.id = 1;     
firstObject.name  = "JOHN";
console.log(firstObject) // {id: 1, name: "JOHN"}

access object value using properties

Object data can be retrieved using property name with an object. property syntax.
Following is an example
var obj={id: 1, name: "JOHN"}
console.log(obj.id) // 1
console.log(obj.name) // "JOHN"

Size of an object in javascript 

Object size is a count of properties in an object. Following is an example for finding keys of an object.
var obj={id: 1, name: "JOHN"}
console.log(Object.keys(obj).length) // 2

how to check key exists in an object or not 

key can be checked in an object using hasOwnProperty method
var obj={id: 1, name: "JOHN"}
obj.hasOwnProperty("id"); //true;
obj.hasOwnProperty("id"); //false;

JSON Object examples in javascript

JSON is a javascript object notation used to transfer data between client and server. It contains key and values of javascript data types. This is useful in many programming languages to interact with REST API JSON data contains key and value pairs.
Here is a sample JSON object in javascript
{
"name": "Kiran",
"salary":2000
}

Initialize and Create a JSON object 

There are many ways we can create a JSON object in javascript.
Empty Object Creation
var JsonObject={};
or JSON object can be created using object
var jsonObject=new object();
JSON object always created using curly braces Initialize JSON object with key and values
var jsonObject={"name":"kiran","id":1}
The above object is created with name and key-value pairs like javascript object and easy key and value pair is separated by comma Create JSON Object Arrays Arrays in javascript can be written using square brackets which contain collection of objects
var jsonObject={"name":"kiran","id":1,depts:["dept1":"HR","dept":"admin"]}
The above example JSON object contains depts array of two objects. Convert JSON string to javascript object with examples Json text can be converted to javascript object using JSON.parse() method. parse() method takes json string and returns Javascript object, if invalid json string is passed, returns empty object string how to check key exists in object or not key can be existed in objet using hasOwnProperty method
var jsonString = ‘{ "name":"kiran",salary:1000}’;
var javascriptObject = JSON.parse(jsonString);
console.log(javascriptObject.name)// kiran
console.log(javascriptObject.salary)// 1000
Convert JSON to String using stringify method JSON.stringify() function is used in following cases convert json into String
var obj = { name: "kiran", salary: 2000 };
var json = JSON.stringify(obj);
arrays can also be stringfied using Stringify method
var myarray = [ "Ram", "Fran", "Sai"];
var myjson = JSON.stringify(myarray);
Array in javascript with examples Array are collectino of elements with index order. Declare and initalize array Array can be decla Kiran

Monday, December 24, 2018

Golang Tutorials - Complex Types Numbers Guide With Examples

In this blog post, You will learn about Complex Numbers types in Go language with examples.

Golang Complex Type Numbers

Golang provides Inbuilt datatypes for numeric strings and other types Numeric strings are int, uint, float, and complex numbers. Complex Numbers contains two parts - real numbers and imaginary numbers, for example, a complex number is 12.8i
In Golang, Complex numbers are represented in two types
complex64 type- this type is used to represent float32 real and imaginary data.
complex128 type - this type is used to represent float64 real and imaginary data

How do we create a Complex number in Golang? 

There are 2 ways to create a Complex number of ways in Golang.
Using Inbuilt function -
    complex Golang Provides Inbuilt Complex function, provides to create real and imaginary data.
Here is a complex function syntax
func complex(real, imaginary FloatType) ComplexType  
This takes real and imaginary floating types - float 32 or float 64. Complex type returns Complex type complex64 and complex128 types These both parameters types should be always same. if real and imaginary numbers of float32 is supplied, retuned Complex32 type, if real and imaginary types are of type float64 is supplied, the function always returns Complex64 type
Using Shorthand assignment Syntax
This is another way to create Complex numbers shorthand assignment syntax
complexData := 1 + 4i  

Golang Complex Number Type example

In the below example, You will learn the following things.
  • Create a Complex number using Inbuilt Complex function
  • Declare and assign Complex Number Variable with shorthand syntax Printing Complex numbers using Println function 
  • Print Imaginary Data part using imag function 
  • Print real Data part using a real function

package main

import (
 "fmt"
)

func main() {
 complex1 := complex(10, 4)
 complex2 := 1 + 4i
 fmt.Println("complex Number 1", complex1)
 fmt.Println("complex Number 2:", complex2)
 fmt.Println("Real Number 1:", real(complex1))
 fmt.Println("Imaginary Number 1:", imag(complex1))
 fmt.Println("Real Number 1:", real(complex2))
 fmt.Println("Imaginary Number 2:", imag(complex2))
}
When above program compiles, Output is
complex Number 1 (10+4i)
complex Number 2: (1+4i)
Real Number 1: 10
Imaginary Number 1: 4
Real Number 1: 10
Imaginary Number 2: 4

Example program - Arithmetic Operations with Complex Numbers 

This is an example for Having arithmetic operations - add, subtract, divide, Multiplication on Complex Numbers When you are doing add operation with complex numbers, Real part adds separately, Imaginary part adds separately. The same it works for other operations Below is an example for add, subtract, multiply, divide operations on complex numbers.
package main
import (
 "fmt"
)

func main() {
 complex1 := complex(10, 4)
 complex2 := 1 + 4i
 fmt.Println("Addition ", complex1+complex2)
 fmt.Println("Substraction:", complex1-complex2)
 fmt.Println("Division ", complex1/complex2)
 fmt.Println("Multiplication:", complex1*complex2)
}
Output is
Addition  (11+8i)
Substraction: (9+0i)
Division  (1.5294117647058822-2.1176470588235294i)
Multiplication: (-6+44i)

Saturday, December 22, 2018

Golang Examples - remove/strp white spaces from a String

In this blog post, You will learn three programs using Strings package builtin functions
  • Delete all whitespaces from a string
  • Delete  leading and trailing spaces of a string
  • Remove duplicate spaces/tabs/newlines from a given string

Example program to strip all whitespaces from a string

This program is to remove the all white or empty spaces from a given string, return the new string Standard inbuilt Strings package provides various utility string functions. Replace is one of the function replace empty spaces from a given string and returns a new string.
Following is a syntax for Replace function
func Replace(s, old, new string, n int) string
return copy of the given string with replaces with an empty string.
Here is an Example for removing empty spaces from a string using Strings replace function
package main

import (
 "fmt"
 "strings"
)

func main() {
 str := "  This is test example "
 fmt.Println("Original String: ", str)
 fmt.Println("Output String: ", strings.Replace(str, " ", "", -1))
}
When the above example code is compiled and executed, Output is as follows
Original String:    This is test example
Output String:  Thisistestexample

Example program to strip leading and trailing spaces from a string 

This program is to remove the Start and end spaces from a given string, return the new string Standard inbuilt Strings package provides various utility string functions. TrimSpace is one of the function replace leading and trailing empty spaces from a given string and returns new string Following is a syntax for Replace function
func TrimSpace(s string) string
return a slice of a given string with all start and ending spaces remove.
Here is an Example for removing leading and trailing empty spaces from a string using Strings TrimSpace function
package main

import (
 "fmt"
 "strings"
)

func main() {
 str := "  This is test example  "
 fmt.Println("Original String: ", str)
 fmt.Println("Output String: ", strings.TrimSpace(str))
}
When the above example code is compiled and executed, Output is as follows
Original String:    This is test example
Output String:  This is test example

Example program 3 to remove duplicate empty spaces from a string

This program removes duplicate spaces( more than one space) from a given string, return a string with single space. This checks spaces for Tab, newline characters. In the below program, Created a regular expression pattern using regex package with MustCompile function.
The pattern is \s+, \s represents single character matches with a tab or new line, + checks for one or more characters finally call ReplaceAllString, which returns a new string with removed duplicate space characters Following is an example for remove duplicate space substrings from a given string ReplaceAllString
package main

import (
 "fmt"
 "regexp"
)

func main() {
 str := "  This is test             example  "
 singleSpacePattern := regexp.MustCompile(`\s+`)

 fmt.Println("Original String: ", str)
 fmt.Println("Output String: ", singleSpacePattern.ReplaceAllString(str, " "))
}
Output is
Original String:    This is test             example
Output String:   This is test example

Friday, December 21, 2018

Golang Tutorials - Comments in Go Language

In any programming language, Comments are useful statements describes code statements. Comments are part of the program contains statements used to place human-readable information. This will be helpful for developers to maintain the code, improves code quality and easier bug fixing.
Golang Comments

In Golang, The comments are used to describe information about variables, control structures, functions or any line of code. Comments are ignored by the compiler when the program is compiled.
Go Language provides the following types of comments
  • Single Line Comments
  • Multi Line Comments - Block comments
  • Documentation comments

Golang Single-line Comments

Single-line Comment always prefixed with two forward slashes, used to comment a single line of the statement. Single LIne comments are used to describe the line of code, can be placed before the line of code or end of the code.
Following is the syntax of Single-line comments
Syntax
// Comments here(Statement of a line are comments)
Golang Compiler ignores any text or statements between // and end of the line.
The below examples places two single line comments,
// Main function - These comments placed before function declaration
// Print Text to console - These comments placed at end of the line of code.
Following is an example of single line comments
package main

import (
 "fmt"
)

// Main function
func main() {
 fmt.Println("Hello World")  // Print Text to console

}

Golang Multi-line comments-  Block Comments

To write multi-line comments using single-line comments, It will be very complex to write as each line starts with // So multi-line comments are useful for clean code. Multi-line comments are used to place comments/statement in multiple lines.
Here is the syntax of multi-line comments
Syntax

/* This 
is a multi line
comments */
Comments are started /* and end with */. Golang compiler ignores statements or text in between /* and */.
Here is an example for Multi-line comments in Golang
package main

/* This program example prints
Hello world text to console
*/
import (
 "fmt"
)

// Main function
func main() {
 // Print Text to console
 fmt.Println("Hello World")

}

Golang Documentation Comments

Documentation comments are used to create Documentation API for Golang code. These comments are used for packages or projects to generate documentation HTML pages, can be used by users for reference. The comments contain HTML markup and texts.
you need to use Godoc tool to create a Go documentation API.
package first

/* This program example prints
Hello world text to console
*/
import (
 "fmt"
)

/* Adding two numbers
return sum of numbers
*/
func sum(number1 int, number2 int) int {
 return number1 + number2
}

// Main function - entry point
func main() {
 // Print Text to console
 fmt.Println("Hello World")

}
Godoc provides a web server. Please run the below command to start a web server
godoc -http=:8331
and open localhost:8331 in a browser.

Thursday, December 20, 2018

Golang Example - Convert(cast) Hexadecimal to Decimal Integer Number vice versa

In this blog post, You will learn two programs in Go language, The first program is to convert Hexadecimal to Decimal Integer. Second program to convert Decimal to Hexadecimal Number.

Golang Hexadecimal Number System

Hexadecimal number  is also called hexa number which contains 16 digits ie numbers start from 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. It is based on Base 16 ie Hexa number system. So HexaDecimal contains Decimal Numbers,0-9 (base 10)  and  Extra 6 alphabets - A to F
 In Golang, Hexadecimal number always either prefixed with 0x or 0X or normal numbers, Example Hexadecimal number is 0x12F or 0X34A,23A
Decimal Number are numbers which contain numbers based on base 10. ie numbers starting from 0 to 9, Example decimal Number is 25
 The below programs takes input from a user keyboard console and stored in the corresponding variable.

Example Program to convert from Hexadecimal to Decimal Number

We have 2 ways to cast Hexadecimal to decimal number as follows
  • using strconv ParseInt function
  • Using strconv ParseUint function

strconv ParseInt function example to cast hexa to Decimal Integer

strconv package provides ParseInt function which does the conversion of different types. A parseInt function is used to convert given string in hexa format, convert to a Decimal number. Please note that base supplied to this function is 16.
Given input string is stored variable hexaNumber.

valid hexaNumber values accepts values - 23a,0x23a,0X23a.
if hexaNumber string prefixed with 0x, or 0X, strconv.ParseInt() throws error strconv.ParseInt: parsing "0x23A": invalid syntax
So we have to write a function to replace 0x or 0X with empty string.
Here is a complete function to replace long hexadecimal numbers
func hexaNumberToInteger(hexaString string) string {
 // replace 0x or 0X with empty String
 numberStr := strings.Replace(hexaString, "0x", "", -1)
 numberStr = strings.Replace(numberStr, "0X", "", -1)
 return numberStr
}
 
Here is a complete example for Casting long Hexadecimal number to decimal Integer
package main

import (
 "fmt"
 "math"
 "strconv"
 "strings"
)
func hexaNumberToInteger(hexaString string) string {
 // replace 0x or 0X with empty String
 numberStr := strings.Replace(hexaString, "0x", "", -1)
 numberStr = strings.Replace(numberStr, "0X", "", -1)
 return numberStr
}

func main() {
 var hexaNumber string
 fmt.Print("Enter Hexadecimal Number:")
 fmt.Scanln(&hexaNumber)
 output, err := strconv.ParseInt(hexaNumberToInteger(hexaNumber), 16, 64)
 if err != nil {
  fmt.Println(err)
  return
 }
 fmt.Printf("Output %d", output)
}
When the above program is compiled and executed, Output is
Enter Hexadecimal Number:23a
Output 570
 
For Example, If input number is given as 23a, Output is 570 Output is returned with calculated 2*16*16+3*16+10*16

strconv ParseUint function example to convert Hexadecimal to number 

strconv package provides various functions for signed and unsigned numbers Like ParseInt function, ParseUint function is used to convert unsigned integer ParseInt function is used to convert given string in hexa format, convert to a Decimal number. Please note that base supplied to this function is 16.
Here is an example program convert Hexadecimal to a decimal number of type uint64
package main

import (
 "fmt"
 "strconv"
 "strings"
)

func hexaNumberToInteger(hexaString string) string {
 // replace 0x or 0X with empty String
 numberStr := strings.Replace(hexaString, "0x", "", -1)
 numberStr = strings.Replace(numberStr, "0X", "", -1)
 return numberStr
}

func main() {
 var hexaNumber string
 fmt.Print("Enter Hexadecimal Number:")
 fmt.Scanln(&hexaNumber)
 output, err := strconv.ParseUint(hexaNumberToInteger(hexaNumber), 16, 64)
 if err != nil {
  fmt.Println(err)
  return
 }
 fmt.Printf("Output %d", output)
}
The output of the above program is
Enter Hexadecimal Number:0x25
Output 37

Example Program to convert Decimal to HexaDecimal Number

We have 2 ways to convert Decimal to HexaDecimal number in Golang. Below are two ways as follows

  • using strconv FormatInt function 
  • using strconv FormatUint function 

Below program takes decimal input number from keyboard console, stores it in variable decimal.

strconv FormatInt function example to convert Decimal to Hexa Number

Inbuilt Standard package strconv provides FormatInt function used to convert Decimal to Hexa number. Here is an example program for Casting Decimal integer to Hexa number
package main

import (
 "fmt"
 "strconv"
)

func main() {
 var decimal int64
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)
 output := strconv.FormatInt(decimal, 16)
 fmt.Print("Output ", output)

}
Output is
Enter Decimal Number:29
Output 1d

strconv FormatUint function example to convert Decimal to Hexadecimal Number 

strconv package FormatUint function which converts of Uint64 to hexadecimal number Here is an example program for Casting unsigned integer to Hexadecimal number.
package main

import (
 "fmt"
 "strconv"
)

func main() {
 var decimal uint64
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)
 output := strconv.FormatUint(decimal, 16)
 fmt.Print("Output ", output)

}
Output is
Enter Decimal Number:30
Output 1e

Learn Haskell - Tutorial for Beginners

This post is an index page for Complete Haskell beginner Guide.

Haskell Beginner Guide

Haskell is a Strong functional programming language with features like strong static typing and semantics.

Features

  • Pure Functional Programming language
  • The code is compatible on semantics not on syntax
  • Lazy computations 
  • Full type inference
  • First class functions support
  • Opensource

Haskell Tutorials

Installation and Setup


  • Haskell Setup and Configuration on windows

Introduction

Learn Haskell tutorials (Work in Process)

We are working hard to create the est content on Haskell tutorials and examples.
Please subscribe now and you will get tutorials in your inbox.



Golang Example - Convert(cast) Octal to Decimal Number

In this blog post, You will learn two programs in Go language
The first program is to convert Octal to Decimal Number
Second program to convert Decimal to Octal Number.

An Octal number is a number based on the base 8 number system. It contains digits from 0 to 7. In Golang, Octal numbers are always prefixed with zero  Example octal numbers is 0879. Decimal Number are numbers which contain numbers based on base 10.

Example Program to convert Octal to Decimal Number 

We have 2 ways to convert Octal to Decimal Number in Go language. Following are the ways.
  • Using strconv ParseInt function
  • Custom Function using for loop without inbuilt functions
The below program takes Octal number (prefixed with zero or normal number for Declaring Octal numbers) and stored in variable octal.

strconv ParseInt function example to cast Octal to Decimal

strconv package provides ParseInt function.To convert Octal number, ParseInt is provided with number and base=8.
Here is an example program for conversion to Decimal Number
package main

import (
 "fmt"
 "strconv"
)

func main() {
 var octal string
 fmt.Print("Enter Octal Number:")
 fmt.Scanln(&octal)
 output, err := strconv.ParseInt(octal, 8, 64)
 if err != nil {
  fmt.Println(err)
  return
 }

 fmt.Printf("Output %d", output)
}
When the above program is compiled, Output is
Enter Octal Number:045
Output 37

Custom Function without Predefined functions 

Created an user-defined function, inside a custom function, used for loop with Modulus, Division operator and Math pow function.
Here is an example program
package main

import (
 "fmt"
 "math"
)

func convertOctaToDecimal(number int) int {
 decimal := 0
 counter := 0.0
 remainder := 0

 for number != 0 {
  remainder = number % 10
  decimal += remainder * int(math.Pow(8.0, counter))
  number = number / 10
  counter++
 }
 return decimal
}

func main() {
 var octal int
 fmt.Print("Enter Octal Number:")
 fmt.Scanln(&octal)

 fmt.Printf("Output %d", convertOctaToDecimal(octal))

}
Output is
Enter Octal Number:25
Output 21

Example Program to convert Decimal to Octal Number 

We have 2 ways to convert Decimal to Octal number in Golang.
Below are two ways

  • using strconv FormatInt function 
  • Without Inbuilt Function 

Below program takes decimal input number from keyboard console, stores it in variable decimal.

strconv FormatInt function example to convert Decimal to Octal 

Inbuilt Standard package strconv provides FormatInt function used to convert Decimal to Octal number.
Here is an example program for Casting Decimal to Octal
package main

import (
 "fmt"
 "math"
 "strconv"
)
func main() {
 var decimal int64
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)
 output := strconv.FormatInt(decimal, 8)
 fmt.Print("Output ", output)

}
The output of the compiled program is
Enter Decimal Number:124
Output 174

Custom function without inbuilt functionality 

The following program uses Golang features For loop, Modulus and division operators.
Here is an example program to do the conversion.
package main

import (
 "fmt"
)

func convertDecimalToOctal(number int) int {
 octal := 0
 counter := 1
 remainder := 0
 for number != 0 {
  remainder = number % 8
  number = number / 8
  octal += remainder * counter
  counter *= 10
 }
 return octal
}

func main() {
 var decimal int
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)
 fmt.Print("Output ", convertDecimalToOctal(decimal))

}
Output is
Enter Decimal Number:145
Output 221

Golang Example - Convert(cast) Binary to Decimal or Decimal to Binary Number

In these posts, You will learn two programs in Go language
The first program is to convert Binary Number to Decimal Number
Second program to convert Decimal Number to Binary Number.

A binary number is a number based on base 2. It contains either zero or one digits. Each digit is called a bit, Example binary numbers are 1011
Decimal Number are numbers which contain numbers based on base 10

To understand this example, You should have following features in Go language.

Example Program to convert Binary to Decimal Number 

There are 2 ways to convert binary number to decimal number
  • Using strconv ParseInt function
  • Write conversion logic manually without using inbuilt functions
The below programs takes input binary number from a user console, store it in variable binary.

strconv ParseInt function example to Cast Binary To decimal 

strconv package provides ParseInt function used to convert binary to decimal numbers Here is an example program
package main

import (
 "fmt"
 "strconv"
)

func main() {
 var binary string
 fmt.Print("Enter Binary Number:")
 fmt.Scanln(&binary)
 output, err := strconv.ParseInt(binary, 2, 64)
 if err != nil {
  fmt.Println(err)
  return
 }

 fmt.Printf("Output %d", output)

}
Output is
Enter Binary Number:1111
Output 15

Manual Custom function to Cast Binary To decimal using for loop

Created an own function, inside a function, used for loop  with Modulus, Division operator and Math pow function
Here is an example program
package main

import (
 "fmt"
 "math"
)

func convertBinaryToDecimal(number int) int {
 decimal := 0
 counter := 0.0
 remainder := 0

 for number != 0 {
  remainder = number % 10
  decimal += remainder * int(math.Pow(2.0, counter))
  number = number / 10
  counter++
 }
 return decimal
}

func main() {
 var binary int
 fmt.Print("Enter Binary Number:")
 fmt.Scanln(&binary)

 fmt.Printf("Output %d", convertBinaryToDecimal(binary))

}
Output is
Enter Binary Number:1001
Output 9

Example Program to convert Decimal to Binary Number 

We have 2 ways to convert Decimal to Binary number in Golang. Following are two ways
  • using strconv FormatInt function 
  • Manually conversion without using Inbuilt function 
Below program takes decimal input number from user console, stores it in variable decimal

strconv FormatInt function example to cast Decimal to Binary 

Inbuilt Standard package strconv provides FormatInt function used to convert Decimal to Binary number.
Here is an example program
package main

import (
 "fmt"
 "strconv"
)
func main() {
 var decimal int64
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)
 output := strconv.FormatInt(decimal, 2)
 fmt.Print("Output ", output)

}
Output is
Enter Decimal Number:15
Output 1111

Cast Decimal to binary for loop without inbuilt function

The following program uses Golang features For loop, Modulus and division operators.
Here is an example program to do the conversion.
package main

import (
 "fmt"
)

func convertDecimalToBinary(number int) int {
 binary := 0
 counter := 1
 remainder := 0

 for number != 0 {
  remainder = number % 2
  number = number / 2
  binary += remainder * counter
  counter *= 10

 }
 return binary
}

func main() {
 var decimal int
 fmt.Print("Enter Decimal Number:")
 fmt.Scanln(&decimal)

 fmt.Printf("Output %d", convertDecimalToBinary(decimal))

}
Output is
Enter Decimal Number:15
Output 1111

Wednesday, December 19, 2018

Golang Example - Calculate power or exponents of a Number

In this posts, You will learn Three programs to calculate a power of a number
  • First program is to calculate power of a number
  • Second program to find exponent of a number using Math pow function
  • Third program is to find power of a number using recursive function

Power of m with exponent n is also called m n which is product of number n with m times.
For example, 4 3 is called as 4 to a power of 3
Exponent is 3
Base is 5
Power of 3 base 5 is equal to 5*5*5=125

Power of a number always returns positive number.
The below two programs takes base and exponent input numbers from user using Scanln function, Store this numbers in variables - exponent and base

To understand this example, You should have following features in Go language

Example program to calculate power of a number using for loop

In this program, Iterated the exponent number using condition exponent != 0
Inside for loop, exponent is multipled with base times and stored the result in variable output
Finally Output is printed to console.
Here is a program to check exponent of a number

package main

import (
 "fmt"
)

func main() {
 var exponent, base int
 fmt.Print("Enter Base:")
 fmt.Scanln(&base)
 fmt.Print("Enter exponent:")
 fmt.Scanln(&exponent)

 output := 1
 for exponent != 0 {
  output *= base
  exponent -= 1
 }
 fmt.Printf("Output of power calculation is %d", output)

}

Output is
Enter Base:4
Enter exponent:3
Output of power calculation is 64
The above program works only integer numbers of base.
Alternativelly , we can use math pow() function which works with any numbers

Example program to find exponent of a number using Math pow function

Package math provides mathematical functions. pow() function is used to calcuclate the power of a given exponent and base

Here is the syntax of pow function
func Pow(x, y float64) float64
Here is a math pow function example to find power of a number
package main
import (
 "fmt"
 "math"
)

func main() {
 var exponent, base float64
 fmt.Print("Enter Base:")
 fmt.Scanln(&base)
 fmt.Print("Enter exponent:")
 fmt.Scanln(&exponent)

 output := math.Pow(base, exponent)

 fmt.Printf("Output of power calculation is %f", output)

}
Output is
Enter Base:5
Enter exponent:3
Output of power calculation is 125.000000

Example program recursive function to calcualte power of a number

Recursive function is a function which call inside a recursive function.
Initally RecurisveFunction is called from a main function for first time
Inside a function It calls until exponent is zero and result is returned from a function
Here is a Recursion function for power of a number

package main

import (
 "fmt"
)

func RecursivePower(base int, exponent int) int {
 if exponent != 0 {
  return (base * RecursivePower(base, exponent-1))
 } else {
  return 1
 }
}

func main() {
 var exponent, base int
 fmt.Print("Enter Base:")
 fmt.Scanln(&base)
 fmt.Print("Enter exponent:")
 fmt.Scanln(&exponent)

 output := RecursivePower(base, exponent)

 fmt.Printf("Output of power calculation is %d", output)

}