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)

}

Tuesday, December 18, 2018

Golang Example - 3 ways to check Length of a String with output

In this blog post, You will learn three programs
  • First program is Length or count of Character/bytes  of a String
  • Second program is  Length of runes in a String 
  • Third Program  is to find the length of string using pointer
String is sequence of characters which contains one or more words. In Golang, String is read only of arbitary bytes.String length is number of characters in a string, For example, Given input string is "Cloudhadoop", The length of the string is 11.

Example program  - Length or count of Character/bytes  of a String

In this program, Inbuilt len() function is used to calculate length of character of a string.
Here is a syntax of len function
func len(input Type) int
This function accept input parameter of type like array,slice,strings, channel
package main
import (
 "fmt"
)

func main() {
 str1 := "This is test program"
 fmt.Println(len(str1)) //11
}
Output is
20

Example program Length of runes in a String

Package unicode/utf8 provides RuneCountInString function to find out runes count of a string

Here is a Syntax of RuneCountInString function
func RuneCountInString(s string) (n int)
Here is a program to check runes count of a string using RuneCountInString function
package main

import (
 "fmt"
 "unicode/utf8"
)

func main() {
 str := "Cloudhadoop"
 fmt.Println(utf8.RuneCountInString(str)) // 11

}
output is
11 

Example program 3 length of a string using pointer

address of variable can be find using & ambersand symbole
lenght of String using pointer or address can be found using *(star) followed by variable
Here is an example checking string pointer length
package main

import (
 "fmt"
)

func main() {
 str := "cloudhadoop"
 address := &str
 fmt.Println(len(*address))

}
Output is
11

Golang Example - Calculate Sum of digits of a integer number

In this post, You will learn different ways to addition of digits of a number in Golanguage
  • Using Iterative Function
  • Using Recursive Function
Sum of digits of a number is to retrieve each digit of a number and add these numbers to result. For example, if given number is 154, The sum of digits of a number is 1+5+4=10.

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

Example program - Sum of digits of a number using Modulus Operator

In this below program,The intput number is read from the user keyboard console, store this in variable number.

Iterate the each digit of a number using for loop until condition (number!=0) is false i.e number is zero.

Retrieve remainder for the given number using modulus operator and add this to the sumResult. This will be continue execution until division of number with base 10 is zero
Here is a program to calculate add of digits of a integer using for loop
package main

import (
 "fmt"
)

func sumDigits(number int) int {
 remainder := 0
 sumResult := 0
 for number != 0 {
  remainder = number % 10
  sumResult += remainder
  number = number / 10
 }
 return sumResult
}
func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 fmt.Printf("Addition digits of %d = %d\n", number, sumDigits(number))

}
When above program is executed, Output is
Enter Number:2535
Addition digits of 2535 = 15
For example, If given input is entered is 2535 and variable sumResult is zero initially

Loop the number and inside the For loop
2535%10=5  modulus operator % gives remainder
sumResult=sumResult+remainder(0+5), sumResult=5 now
2535/10=235 ie number 235
235%10=5
sumResult=sumResult+5 ie 5+5=10, so sumResult=10 now
235/10=23 ie number 23
23%10=3
sumResult=sumResult+3 ie 10+3=13, so sumResult=13 now
23/10=3 ie number 2
2%10=2
sumResult=sumResult+2 ie 13+2=15, so sumResult=15 now
0/10=0 ie number 0
number is zero, conditional expression in for loop is false, Loop terminates its execution

Example Program 2- Calculates Sum of digits using recursive function

In this program, It takes user input from a keyboard terminal, store it variable number
Declared Recursive function, Recursion is a function which called inside a function.

Initially Recursive funciton called from main function
Here are the steps for recursion steps to calculate digits
For example, if given number is 67845

recursiveSumDigits(67845) - sumResult=0
--recursiveSumDigits(6784) - sumResult=0+5
  --recursiveSumDigits(678) - sumResult=5+4
    --recursiveSumDigits(67) - sumResult=9+8
  --recursiveSumDigits(6) - sumResult=17+7
  --recursiveSumDigits(0) - sumResult=24 +6=30 is returned
  
package main

import (
 "fmt"
)

func recursiveSumDigits(number int) int {
 sumResult := 0
 if number == 0 {
  return 0
 }
 sumResult = number%10 + recursiveSumDigits(number/10)
 return sumResult
}

func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 fmt.Printf("Addition digits of %d = %d\n", number, recursiveSumDigits(number))

}

Output is
Enter Number:67845
Addition digits of 67845 = 30

Golang Example - Find Factorial of a Number

This blog post covers two programs to calculate factorial of a number
  • Using Recursion function
  • Using Iterative Function
Factorial of a number n is called n! which is equal to product of all integers less than or equal to number n. This will be always calculated for positive numbers and factorial of negative numbers not exists. Factorial of a number=0 is 1.
For example Factorial of 5 is equal to 5!=5*4*3*2*1. 
Facttorial of n=n!=1*2*3*4*..n
To understand this example, You should have following features in Go language

Example program to find factorial of a number using Iteration Function

In the below program, take the input from user keyboard and store it in number variable using Scanln function
Declared function - IterativeFactorial with input parameter of type and return type is uint64 which calculates factorial of a given number
Inside  IterativeFactorial function, We have used for loop to iterate all the numbers from 1 to number, and product of each iterated numbers is stored in variable result

Here to store the result, used uint64 data type which is unsigned 64 bit integers, values ranging from 0 to 2 power 64-1
This will be used to store the bigger numbers of a factorial calculation result.
The result is returned to main function
Finally result is printed to console using Println function
package main

import (
 "fmt"
)

func IterativeFactorial(number int) uint64 {
 var result uint64 = 1
 if number < 0 {

 } else {
  for i := 1; i <= number; i++ {
   result *= uint64(i)

  }
 }
 return result
}
func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 fmt.Printf("Factorial of %d = %d", number, IterativeFactorial(number))
}

When above program is executed, The output is
Enter Number:5
Factorial of 5 = 120

Enter Number:6
Factorial of 6 = 720

Example Program 2 - Recursive function Calculate Factorial of a number

First, read the number from user console and stored in variable number using Scanln function.
Declared Recurisive function RecursiveFactorial, Recusrive functions are functions which will be called inside a same function.

For Example if input number is supplied is 5, The recursive function works as below

Intially, RecursiveFactorial(5) is called from main function.
Inside a function, 5 is greater than equal to 1, 5 is multiple of RecursiveFactorial(4). This is called in same function called recusrive function
During each recurisive call, number value is decremented by 1  and executes until it reaches 1

When number is 1, It returns 1 without recurisve call
In this line of code  return uint64(number) * RecursiveFactorial(number-1), if int is not converted to uint64(uint64(int)), It throws invalid operation: number * RecursiveFactorial(number - 1) (mismatched types int and uint64)
Here is sequence of steps calculation in recursive function

RecursiveFactorial(5)
--5*RecursiveFactorial(4)
  --5*4*RecursiveFactorial(3)
    --5*4*3*RecursiveFactorial(2)
  --5*4*3*2*RecursiveFactorial(1)
--5*4*3*2*1 = 120
Here is a program to calculate Factorial using recusive function
package main

import (
 "fmt"
)

func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 fmt.Printf("Factorial of %d = %d\n", number, RecursiveFactorial(number))

}
func RecursiveFactorial(number int) uint64 {
 if number >= 1 {
  return uint64(number) * RecursiveFactorial(number-1)
 } else {
  return 1
 }
}
Output is
Enter Number:5
Factorial of 5 = 120

Golang Example - Check if a number/integer is positive or negative

In this Example, you will learn programs to check number is positive or negative, First is using if else statement. Second is using standard library Math Signbit function.

Positive number are whole number which are greater than zero ie 1,2,3...
Negative numbers are number which are lesser than zero , -1,-2
Each positive number  has a corresponding negative number

To understanding the below programs, You have following features understanding in Go Language.

Golang Example - Check if Number is positive or negative using if else statement

The below program read number from an user console, store it in variable number.
Here are steps to check positive or negative number using if else statements
  • if  number is greater than zero, Number is positive
  • if number is less than zero , Number is negative
  • else, number=0 is executed, zero value printed to console
Here is a example program to check positive or negative number
package main
import (
 "fmt"
)

func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 if number < 0 {
  fmt.Printf(" %d is a negative integer.", number)
 } else if number > 0 {
  fmt.Printf("%d  is a positive integer.", number)
 } else {
  fmt.Printf("%d is Zero.", number)
 }
}
output is
Enter Number:4
4  is a positive integer.

Enter Number:-9
 -9 is a negative integer.

Enter Number:0
0 is Zero.

Example Program to check Positive or negative number using standard library functions

The below program uses Math Signbit function. Signbit function return true, if number is negative, return false for positive number.
package main
import (
 "fmt"
 "math"
)

func main() {
 var number float64
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 isPositive := math.Signbit(number)
 if isPositive {
  fmt.Printf("%f  is a negative integer.", number)

 } else {
  fmt.Printf(" %f is a positive integer.", number)

 }
}
Output is
Enter Number:25
25.000000 is a positive integer.

Enter Number:-24
-24.000000  is a negative integer.

Golang Example - Print values of Array or slice

In thsi examples, You will learn different ways to print/display array or slice elements to console in Go Language. Following programs are covered
  • Print Array using For Loop with range
  • Display Slice using PrintF function format
  • Array slice console print without Squarebrackets
  • Print Address  or pointer of array
  • Print Slice of bytes in Binary Form
To understand this example, You should have following features in Go language

Example program: Print an Array or slice using For loop with range

In the below program, Declared slice and array with initlized values using shorthand assignment operator.

For loop with range form is used to iterate the elements of an array or slice.
Each iteration has a value and print the values to console using Printf function formatting options( %d for int, %s for strings)
package main
import "fmt"

func main() {

 slice := []int{1, 2, 3}
 array := [5]string{"one", "two", "three", "four", "five"}

 for _, value := range slice {
  fmt.Printf("%d\n", value)
 }
 for _, str := range array {
  fmt.Printf("%s\n", str)
 }
}

The above program output is
1
2
3
one
two
three
four
five

Example program2: Display  elements of an Array or slice using Printf function

In this program, Array or slice is printed to console using fmt Printf function with format strings
Printf Format Strings for Displaying Array or Slice
For example, Array or slice contains {"one", "two", "three"}, We will see different ways of printing values
  • %v -  value in default format ie [one two three]
  • %+v -  Value in default format + Displays sign for numerics - [one two three]
  • %#v -  Data values in Go Styles - []string{"one", "two", "three"}
  • %+q -  For Numerics, Displays ASCII code - ['\x01' '\x02' '\x03' '\x05' '\f'], Others default format  - ["one" "two" "three"]
You can check more printf options 
Here is an example display array or slice values to console

package main
import "fmt"

func main() {
 sliceStrings := []string{"one", "two", "three"}
 arrayInt := [5]int{1, 2, 3, 5, 12}

 // Print slice to console
 fmt.Printf("%v\n", sliceStrings)
 fmt.Printf("%+v\n", sliceStrings)
 fmt.Printf("%#v\n", sliceStrings)
 fmt.Printf("%+q\n", sliceStrings)
 // Print array to console
 fmt.Printf("%v\n", arrayInt)
 fmt.Printf("%+v\n", arrayInt)
 fmt.Printf("%#v\n", arrayInt)
 fmt.Printf("%+q\n", arrayInt)

}
Output is
[one two three]
[one two three]
[]string{"one", "two", "three"}
["one" "two" "three"]
[1 2 3 5 12]
[1 2 3 5 12]
[5]int{1, 2, 3, 5, 12}
['\x01' '\x02' '\x03' '\x05' '\f']

Example Program 3 to Print Array or slices without Squrebrackets

As you seen the above program, Printing array or slice to console contains Squrebrackets.To remove Squarebrackets, We have to use fmt.Sprint function remove squarebrackets and result is trimmed using strings Trim() function
Here is an example program to remove squarebrakcets of array or slice printing
package main
import (
 "fmt"
 "strings"
)

func main() {
 sliceStrings := []string{"one", "two", "three"}
 arrayInt := [5]int{1, 2, 3, 5, 12}

 // Print slice without squrebrackets to console
 fmt.Println(strings.Trim(fmt.Sprint(sliceStrings), "[]"))

 // Print array without squrebrackets to console
 fmt.Println(strings.Trim(fmt.Sprint(arrayInt), "[]"))

}

Output is
one two three
1 2 3 5 12

Example Program 4 Print address or pointer of array/slice

Creatingn Array or slice variable involves location or address in memory.
To check address of array or slice, we have to use &(ampersand) and array/slice variable name
Here is a example program for printing pointer
package main

import (
 "fmt"
)

func main() {
 sliceStrings := []string{"one", "two", "three"}
 arrayInt := [5]int{1, 2, 3, 5, 12}
 fmt.Printf("Pointer or address of slice %p add array %p \n", &sliceStrings, &arrayInt)

}
Output is
Pointer or address of slice 0xc00004a400 add array 0xc000076030

Example Program 5 Print Array or slice bytes in binary bits form

Here is sequence of steps to print binary data from Array or Slice of data

  • Declared Byte slice
  • using for loop Print the binary form using Printf with %08b format

package main
import (
 "fmt"
)

func main() {

 byteArray := []byte{25, 1}
 for _, value := range byteArray {
  fmt.Printf("%08b", value)
 }

}

Output is
0001100100000001