Sunday, December 16, 2018

Golang example - Program to calculate Sum of natural numbers

This post we will cover three programs to find the sum of natural numbers
  • Sum of first n natural numbers entered by the user
  • Sum of first n natural numbers using for loop
  • Sum of first n natural numbers Recursive function
Natural numbers are positive integers or whole numbers which starts from 0,1, 2 .... n. These also called nonpositive numbers. This post is about calculating the sum of natural numbers from 1 to n where n is read from console by the user. 

To understand this programs, You should have an understanding of following golang features.

Example program 1- Sum of first n natural numbers Entered by user

The below program takes an input number from command line console from a user and calculates the sum of natural numbers up to a given number

package main

import (
 "fmt"
)

func main() {
 //reading an multiple input string
 var number int
 fmt.Print("Please enter number:")
 fmt.Scanln(&number)
 sumResult := 0
 for i := 0; i <= number; i++ {
  sumResult += i
 }
 fmt.Printf("Sum of  %d numbers is  %d", number, sumResult)
}

Output is
Please enter number:10
Sum of  10 numbers is  55

The above program read an input from the user using the Scanln function, store the number in a variable number.
Using for loop, iterate and calculates the values from 0 up to n
Finally, a sum is printed to console

Example program 2- Sum of natural numbers using for loop

In this program, Instead of taking input from the user, the variable value is fixed, Like an above program, for loop is used to calculate up to a given number.
Finally printed value to the console
package main

import (
 "fmt"
)

func main() {
 max := 10
 sumResult := 0
 for i := 0; i <= max; i++ {
  sumResult += i
 }
 fmt.Printf("Sum of  %d numbers is  %d", max, sumResult)
}

Output is
Sum of  10 numbers is  55

Example program 3- Recursion function Sum of natural numbers

package main

import (
 "fmt"
)

func sumNatural(numb int) int {
 if numb != 0 {
  return numb + sumNatural(numb-1)
 } else {
  return numb
 }
}

func main() {
 number := 10
 fmt.Printf("Sum of  %d numbers is  %d", number, sumNatural(number))
}
Output is

Sum of  10 numbers is  55

In the above program, sumNatural recursive function is declared. This will be called in the main function initially at first using sumNatural(10) function.
the number 10 is added the result of sumNatural(9). next function call will be fired from sumNatural which again calls sumNatural(8) and add this result. This sequence of the process will continue until numb is equal to 0.

recursive call execution will be stopped When numb is zero and finally returned the result to the main function

Friday, December 14, 2018

Golang Program - Print value by reading user input from console

In this blog post, input data can be read from the console in the may ways in Go language
  • read input values using the scan function
  • read multiple input values from console
  • read user input line by line using stdin stream

Example to read user input using the scan function

package main
import (
 "fmt"
)

func main() {
 //reading an string
 var name string
 fmt.Print("What is your Name? ")
 fmt.Scan(&name)
 fmt.Println("Entered Name is :", name)

}
Output is
What is your Name? kiran babu
Entered Name is : kiran
In the above example, a String variable is declared.
package fmt has a Scan function, fmt package is imported into the program
Function Scan is used to read the user input from the standard input ie console. input values are stored with separation of space into successive parameters.
You can check more about scan function. Scan function store the address or pointer of the variable.
What is your Name? prompt is displayed to the user to take input from user
fmt.Scan(&name) function read all values separated in spaces until newline(\n or enter keyword). Each word separated in spaces are stored in variable name.
As we declared only one variable - name, text "kiran babu" will be treat as two variable in space separated format, the first value is stored in the variable name
Finally, printing entered a value into the console

The only disadvantages with this is entered text is saved in multiple variables, not complete line.

Here is an example for reading multiple input values
package main
import (
 "fmt"
)

func main() {
 //reading an multiple input string
 var fname string
 var lname string
 fmt.Print("What is your Name? ")
 fmt.Scanln(&fname, &lname)
 fmt.Printf("Entered Name is %s %s", fname, lname)
}
Output is
What is your Name? Cloud Hadoop
Entered Name is Cloud Hadoop
Next example is to read user input line by line using the stdin stream

Example program to read user input line using stdin stream

Bufio package provides to read/write from any stream.
bufio package has Scanner class to read line by line from input console
bufio.NewScanner which accepts io.Reader to scan line by line from a given stream.

bufio.NewScanner(os.Stdin) read data from keyword line by line  from command line console
Finally scanner.text() stores the user text and print it to console
Following is read input line by line from command line console using stdin stream
package main
import (
 "bufio"
 "fmt"
 "log"
 "os"
)

func main() {
 fmt.Println("Pleae enter text")
 scanner := bufio.NewScanner(os.Stdin)
 for scanner.Scan() {
  fmt.Println("Entered Text is ", scanner.Text())
 }
 // Error handling
 if err := scanner.Err(); err != nil {
  log.Println(err)
 }

}
Output is
What is your Name? Kiran
Entered Name is Kiran

Golang Example - Program to check Leap year or not

In this blog post, We will write a program to check a given a year  is a leap year or not
Leap year is a year which meets following conditions
  1. if the year is divisible by 4, check step 2, else go to step 5
  2. if the year is divisible by 100, check step 3 else go to step 4
  3. if the year is divisible by 400, check step 4, else go to step 5
  4. Then the year is lear year which has 366 days
  5. This is not leap year  which has 365 days

Example program  to check given year is a leap year or not

The following features are used in go language
Following is example code

package main

import (
 "fmt"
)

func isLeapYear(year int) bool {
 leapFlag := false
 if year%4 == 0 {
  if year%100 == 0 {
   if year%400 == 0 {
    leapFlag = true
   } else {
    leapFlag = false
   }
  } else {
   leapFlag = true
  }
 } else {
  leapFlag = false
 }
 return leapFlag
}
func main() {
 bool := isLeapYear(1980)
 bool1 := isLeapYear(2001)
 fmt.Println(" 1980 leap year?:", bool)
 fmt.Println(" 2001 leap year?:", bool1)

}

Above program is compiled and output is
1980 leap year?: true
2001 leap year?: false
In the above program, Created a function isLeapYear which accepts parameter year of type int and returns true if it is a leap year, else false - if not leap year
Since 1980 is divisible by 4 and not divisible 100, so 1980 is a leap year
But 2011 is not divisible by 4, so 2001 is not leap year
Finally ,display the boolean value to console using Println() function

Golang Example - Check alphabet is Vowel or consonant

In this example, We will learn below programs. how to check alphabet is vowel or consonant using if-else and switch case examples and Count of vowels in a String.
the vowel is called for a character if Character contains any of a, e, i, o, u characters

Please have a look of below golang features before understanding this programs

Example program to check alphabet is Vowel or consonant using if else statement

package main

import (
 "fmt"
)

func isVowel(character rune) {
 if character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u' {
  fmt.Printf(" %c is vowel\n", character)
 } else {
  fmt.Printf(" %c is consonant\n", character)
 }

}
func main() {
 isVowel('a') // vowel
 isVowel('b') // consonant
}
Output is
a is vowel
b is consonant
In the above example, Character is stored as rune type. to check variable character to vowel or consonant, if character contains any one (a,e,i,o,u) using if else statement.

Example program to check alphabet is Vowel or consonant using a switch case

package main

import (
 "fmt"
)

func isVowel(character rune) {
 switch character {
 case 'a', 'e', 'i', 'o', 'u':
  fmt.Printf(" %c is vowel\n", character)
 default:
  fmt.Printf(" %c is consonant\n", character)
 }
}
func main() {
 isVowel('e') // vowel
 isVowel('g') // consonant
}
Output is
e is vowel
g is consonant
Instead of an if-else statement, Switch case is used. if the character is matched with any of characters (a,e,i,o,u), the case is printed with a vowel to console. default case consonant is printed to console

Example Calculate for vowels count in a String

package main

import (
 "fmt"
)

func main() {
 str := "kiran"
 count := 0
 for _, ch := range str {
  switch ch {
  case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
   count++
  }
 }
 fmt.Printf(" %s string contains vowels count: %d\n", str, count)

}
Output is
kiran string contains vowels count: 2

Thursday, December 13, 2018

Golang Example - 2 ways to find swap two numbers/variables

In this post, This convers 2 ways to swap two numbers or variables in Golang.
First one is to swap variables in temporary variable, another one is not using temporary variable.

Example 1: Swap two values/numbers using a temporary variable

package main

import (
 "fmt"
)

func main() {
 number1, number2 := 12, 30
 fmt.Println("Before Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)

 // number1 is assigned to temporary variable
 temporary := number1
 // number1 is assigned to number2 variable
 number1 = number2
 //  temporary  is assigned to number2
 number2 = temporary

 fmt.Println("After Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
}
The above program is compiled and executed, Output is
Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12
In the above, Two variables number1 and number 2 are declared, and assigned with 12 and 30 values respectively.
Here is a swapping process
  • First, the number1 variable value is assigned to a temporary variable
  • Next is, nthe umber2 variable value is assigned to the number1 variable
  • Finallyl, temporary (intiall number1 variable value) value is assigned to number2 variable value 

Here temporary variable is declared and used to store the number1 value before doing swapping. number1 and number2 variable values are printed to console before and after swapping process using Println function

Example 2 swap numbers without a temporary variable

 In this program, Numbers are swapped without using a temporary variable. Here tuple assignments are used to swap the numbers Swapped numbers areprinted to console using println function Here is an program swap number using tuple assignment
package main

import (
 "fmt"
)

func main() {
 number1, number2 := 12, 30
 fmt.Println("Before Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
 number1, number2 = number2, number1

 fmt.Println("After Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
}
Output is
Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12

Go Example - Program to check string contains Alphabetic,numeric and special characters

Golang String characters

The string is a group of characters enclosed in double quotes.

alphabetic characters - each character contains a letter from lowercase - a to z and uppercase - A to Z.
alphanumeric characters - contain alphabetic and numeric characters.
Special characters - a character are like %,# ..etc with excluding alphabetic and numeric characters.

This post, You will learn the following things in GoLang
  • check String contains alphabetic
  • check String contains alphabetic using a regular expression
  • check String contains alphanumeric and special characters

Example 1: How to check if a string contains alphabetic characters 

String characters are iterated using for each loop. Check each character for lowercase and uppercase values and return true for Alphabetic and false - not alphabetic
package main

import (
 "fmt"
)

func checkStringAlphabet(str string) bool {
 for _, charVariable := range str {
  if (charVariable < 'a' || charVariable > 'z') && (charVariable < 'A' || charVariable > 'Z') {
   return false
  }
 }
 return true
}

func main() {
 fmt.Println(checkStringAlphabet("Kiran")) // true
 fmt.Println(checkStringAlphabet("123"))   // false

}
Output is
true
false

Example 2: How to check if a string contains alphabetic characters using regular Expression

Regular expressions support avialable in Golang using regex standard inbuilt package. This includes regular expressions and pattern matching First regular expression pattern is compiled using MustCompile function and returns object. with this object, MatchString is used to check matched string Regular Expression used as regexp.MustCompile(`^[a-zA-Z]+$`)
^ - Beginning of a string
[ - Character group starting
a-z - lower case letter
A-Z - upper case letter
] - Character group end
$ - String ending
+ - one or more characters
Here is a Program to check String contains Alphabetic using a regular expression
package main

import (
 "fmt"
 "regexp"
)

var isStringAlphabetic = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString

func main() {
 fmt.Println(isStringAlphabetic("kiran")) // true
 fmt.Println(isStringAlphabetic("a1a"))   // false
}
Output is
true
false

Example 3- Check String contains Alphanumeric characters or special characters

Regular expression patter used is ^[a-zA-Z0-9_]*$. which returns true for alphabetic, numeric and underscore characters, return false - for special characters Here is a program to check a string for Alphabetic and special characters
package main

import (
 "fmt"
 "regexp"
)

var isStringAlphabetic = regexp.MustCompile(`^[a-zA-Z0-9_]*$`).MatchString

func main() {
 fmt.Println(isStringAlphabetic("cloudhadoop")) // true
 fmt.Println(isStringAlphabetic("abc123"))      // true
 fmt.Println(isStringAlphabetic("abc_"))        // true
 fmt.Println(isStringAlphabetic("abc|}"))       // false
 fmt.Println(isStringAlphabetic("%^&abc"))      // false

}
When you compiled and executed, the output is
true
true
true
false
false

Golang Example program to find quotient and remainder of a integers

In this example program, We will find quotient and remainder from the given numerator(dividend) and denominator(divisor)  using modulus and division operator in Golang.
The quotient is a result of the division operator in mathematics. In golang division operator / is used and applied to integers.
the remainder is a result of modulus operator in mathematics. % symbol is defined in Golang.

Example: Find Quotient and Remainder

The below example explains about golang arithmetic operators 
  • Division operator - Divide the numerator with the denominator
  • Modulus operator - Output remainder for the result of the division operator
Following is an example of Division and modulus operator in Golang
package main

import (
 "fmt"
)

func main() {
 numerator := 40
 denominator := 20
 /*quotient := numerator / denominator
 remainder := numerator % denominator */

 // above commented code can be replaced with single line as below
 quotient, remainder := numerator/denominator, numerator%denominator

 fmt.Println("quotient result:", quotient)
 fmt.Print("remainder result:", remainder)

}
The output of the above program is
quotient result: 2
remainder result:0
In the above example, Two integer numbers 40(numerator) and 20(denominator) are stored in a variable - numerator, and denominator.
40 is divided by 20 using / Operator. and result is stored in the quotient variable. the remainder of 40/20 is 0, stored in remainder variable.
 Both quotient and remainder variables values are printed to console using fmt println function.

Golang Example - Program to check Character is alphabetic or not

In this Example, You will learn programs  how to check whether the character is alphabetic or not in go language  using if else statement and switch case statement

     Alphabetic characters are characters English letters in lower and upper case. Special characters are not allowed. Characters in go language are represented in rune data type which contains ASCII code value from 0 to 127.

Please have a look of below golang features to have an understanding of this program better

Example Golang program to check Character/rune is an alphabet or not

In the below program, the character is store in rune data type. rune represents characters in ASCII code from 0 to 127 We have used if else statement to check lowercase alphabets from a to z and upper case alphabets from A to Z Finally print the character is an alphabet or not to the console.
package main

import (
 "fmt"
)

func checkAlphaChar(charVariable rune) {
 if (charVariable >= 'a' && charVariable <= 'z') || (charVariable >= 'A' && charVariable <= 'Z') {
  fmt.Printf("%s is an alphabet\n", string(charVariable))
 } else {
  fmt.Printf("%s is not an alphabet\n", string(charVariable))
 }

}
func main() {
 checkAlphaChar('a')
 checkAlphaChar('_')
 checkAlphaChar('Z')
 checkAlphaChar('*')

}
Output is
a is an alphabet
_ is not an alphabet
Z is an alphabet
* is not an alphabet

Example Golang program to check ASCII alphabet using a switch case statement 

In Golang, each character is represented in ASCII code from 0 to 127 ASCII values for Lowercase alphabet values are 97 to 122 and upper case alphabets are from 65 to 90 We have used a switch case statement to check ASCII for alphabet check
package main

import (
 "fmt"
)

func asciiAlphaCheck(r rune) {
 switch {
 case 97 <= r && r <= 122:
  fmt.Printf("%s is an alphabet\n", string(r))

 case 65 <= r && r <= 90:
  fmt.Printf("%s is an alphabet\n", string(r))
 default:
  fmt.Printf("%s is not an alphabet\n", string(r))
 }
}
func main() {
 asciiAlphaCheck('c')
 asciiAlphaCheck('|')
 asciiAlphaCheck('d')
 asciiAlphaCheck('$')

}
Output is
c is an alphabet
| is not an alphabet
d is an alphabet
$ is not an alphabet

Golang Example - Program to Check ASCII Value of a character

 In this example, you will learn below two programs in go language
  • How to display ASCII value of a character in Go language. 
  • Convert/cast Character to/from ASCII in golang
ASCII is a code which contains 128 characters with integer values from 0 to 127. It can be stored in 8-bit types ie byte In Go languages, There is no character type, but it can be represented in rune data type. Each character contains integer code which is called ASCII code.

Example Find ASCII value of a character

package main


import (
 "fmt"
)

func main() {
 charVariable := 'T' // This is infered as rune data type
 asciiCode := int(charVariable)
 fmt.Printf("%s ASCII code is : %d", string(charVariable), asciiCode)
}
The output of the above program code is as follows
T  ASCII code is :  84
In the above code, Character is declared and assigned using short assignment operator in charVariable. charVariable type is inferred from right-hand side value. Right-hand side value is a character which is enclosed in single quote. Please note that strings are enclosed in double quotes. To get ASCII value of charVariable, create integer with character assign to integer, and compiler converts the character value to ASCII code. We just converted a variable from one type to other types. This is an example for Converting Character to ASCII 
   Finally Print the character and ASCII code using the Println function

Example Convert/cast ASCII to/from a character in Golang 

ASCII and character are different types, We have to write a casting code. The below program explains about following things convert character to ASCII using int() constructor Cast ASCII to a character using string() constructor
package main

import (
 "fmt"
)

func main() {
 // Character to ASCII Code Conversion
 charVariable := 'T' // This is infered as rune data type
 asciiCode := int(charVariable)
 fmt.Printf("%s ASCII code is : %d\n", string(charVariable), asciiCode)
 // ASCII Code  to Character  Conversion
 asciiCode1 := 84
 charVariable1 := string(asciiCode1)
 fmt.Printf("%d character is : %s", asciiCode1, charVariable1)

}
When the above code is compiled and executed, the output is
T ASCII code is : 84
84 character is : T

Golang example - program to multiply two numbers

 In this blog post, you are going to learn below things

  • Multiply two integers 
  • Multiply two floating numbers
  • Multiply integer and floating numbers 

Example1 program to Multiply two integers

package main

import (
 "fmt"
)

func main() {
 var number1, number2 int
 number1 = 5
 number2 = 6
 result := number1 * number2
 fmt.Printf("Multiply result is  %d\n", result)

}

Output is
Multiply result is  30

Example2 program to Multiply two floating numbers

package main

import (
 "fmt"
)

func main() {
 var number1, number2 float64
 number1 = 5.1
 number2 = 6.3
 result := number1 * number2
 fmt.Printf("Multiply floating numbers result is  %f\n", result)

}
Output is
Multiply floating numbers result is  32.130000

Example2 program to Multiply integer and floating numbers

When you are doing multiply with different types (int and float),you got error invalid operation: number1 * number2 (mismatched types int and float64) The following program gives error
package main

import (
 "fmt"
)

func main() {
 var number1 int
 var number2 float64
 number1 = 5
 number2 = 6.3
 result := number1 * number2
 fmt.Printf("Multiply float and int numbers result is  %f\n", result)

}
Output is
# command-line-arguments
Test.go:12:20: invalid operation: number1 * number2 (mismatched types int and float64)
When you are multiply with float, The other number must be float. So int type need to convert to float using float64(intvalue)
Here is a working code
package main

import (
 "fmt"
)

func main() {
 var number1 int
 var number2 float64
 number1 = 5
 number2 = 6.3
 result := float64(number1) * number2
 fmt.Printf("Multiply float and int numbers result is  %f\n", result)

}
Output is
Multiply float and int numbers result is  31.500000

Golang example - Program to Calculate average using Array/slice of numbers

In this blog post, You will learn two programs for finding average of array/slice numbers.
  • First program to find avrage of fixed array of numbers
  • The second program to read the input of values from a user via command line calculates the average.
Following are golang features are required to under this programs

Example program to check average of an array of numbers

First Array or integers is declared with inline assignment of the values
Iterated array using for loop with range form
Find the length of the array using len function
Finally Divide the total by length to get average
package main

import "fmt"

func main() {
 var numbs = []int{51, 4, 5, 6, 24}
 total := 0
 for _, number := range numbs {
  total = total + number
 }
 average := total / len(numbs) // len  function return array size
 fmt.Printf("Average of array %d", average)

}
Output of the above program
Average of array 18

Example program to check average of numbers entered by user console 

In this program, User gives the numbers input via command line using fmt.Scanln function.
Here is an program code to read numbers from the command line and return average of it
package main

import "fmt"

func main() {
 var array [50]int
 var total, count int
 fmt.Print("How many numbers you want to enter: ")
 fmt.Scanln(&count)
 for i := 0; i < count; i++ {
  fmt.Print("Enter value : ")
  fmt.Scanln(&array[i])
  total += array[i]
 }

 average := total / count
 fmt.Printf("Average is  %d", average)

}
Output of the above program is
How many numbers you want to enter: 5
Enter value : 1
Enter value : 2
Enter value : 3
Enter value : 4
Enter value : 5
Average is  3

golang example - program to check number/integer even or odd

In this blog post, we will learn  two programs
The first program is how to check input number is even or odd.the second program is how to check given array or slice of number for even or odd numbers.
Even number is a number divisible to 2 is zero that means the number is even if operation modulus operator divisible by 2 is remainder=0

Example to check Number is even or odd

In the below program. Scanlin function is used to take the input number from user console ie command line. user entered a number is stored in number variable

Now checking number is even or odd, we used modulus operator % and check remainder is zero with divisible by 2. conditional structure if else statement  is used. the if the number is divisible by 2, then it is even number, an else odd number
package main

import (
 "fmt"
)

func main() {
 fmt.Print("Please enter first number: ")
 var number int
 fmt.Scanln(&number) // take input from user
 if number%2 == 0 {
  fmt.Printf("%v is a Even Number", number)
 } else {
  fmt.Printf("%v is a Odd Number", number)
 }
}
When you compile and run the program, the output will be:
Please enter first number: 23
23 is a Odd Number
Please enter first number: 54
54 is a Even Number

Example to check array or slices of Number are even or odd 

First array/slice is created with initialized with values. You can learn more about slice
Iterate the slice using for loop and for loop with range form  . Each number is checked for an odd or even number and printed the result to the console
package main

import (
 "fmt"
)

func main() {
 var numbs = []int{51, 4, 5, 6, 24, 11}
 for _, number := range numbs {
  if number%2 == 0 {
   fmt.Printf("%v is a Even Number\n", number)
  } else {
   fmt.Printf("%v is a Odd Number\n", number)
  }
 }
}
Output of the above program is
51 is a Odd Number
4 is a Even Number
5 is a Odd Number
6 is a Even Number
24 is a Even Number
11 is a Odd Number

Wednesday, December 12, 2018

Golang Example programs

Go is a Static typed popular programming language. To learn a new programming language, We must write a practical example by making use of features. This is an index page for all golang features like control statements -loops, if else, datatypes, data structures, classes, and objects.

All the programs and examples are compiled and tested and given output.
if you are new to go language, want to learn golang before working on this program, then have a look Golang Tutorials.

Golang Programs

Golang examples - Program to add/sum of two numbers or integers

In this program,  we have two programs to add two numbers. The First program, We will store the numbers and the addition of two numbers. The second program, take the two numbers from the user and return the sum of two numbers.

Example: Sum of two numbers 

In this program, variables are declared and did inline assignment statements. This is one way of declaring multiple variables of the same type in golang 
The same way can be rewritten using short assignment operator as below n1, n2, result := 10, 3, 0 .
The variable types can be inferred from right hand values
package main

import (
 "fmt"
)

func main() {
 var n1, n2, result = 10, 3, 0 // Declare variable and assign values
 result = n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Sum of two numbers:  13 

Scanln function example -Sum numbers taken input from the standard console  

 In this program, numbers are taken from the standard console. Scanln function is used to stop the control until user is entered the number And sum of this two numbers are returned to console
package main

import (
 "fmt"
)

func main() {
 fmt.Print("Please enter first number: ")
 var n1 int
 fmt.Scanln(&n1) // take input from user
 fmt.Print("Please enter Second number: ")
 var n2 int
 fmt.Scanln(&n2) // take input from user
 result := n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Please enter first number: 12
Please enter Second number: 34
Sum of two numbers:  46

Golang Example - Convert(Cast) String to Float and Float to String

This post covers how to convert(cast) String type to float type or float type to String with an example.

Golang strconv package

The string is a group of characters referenced by a variable. A float is a numeric number that stores set of all IEEE-754 64-bit floating-point numbers. Both are of different types, Automatic conversions will not occur. The developer needs to write a code to handle this. Golang provides standard inbuilt package strconv to do string conversions to other types. It is a common task of the developer to convert String to float or float to String.

Convert String to float example

strconv package provides ParseFloat function to convert to float numeric types. You can check more about this function here 
Here is syntax
func ParseFloat(s string, bitSize int) (float64, error)
arguments are
The string is an input string. if given string is not numeric, It gives error strconv.ParseFloat: parsing "abc": invalid syntax
bisize is of int type with values 32 or 64.
Here is a strconv  ParseFloat function example program
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatString := "587.23"
 floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 if n1, err := strconv.ParseFloat(floatString, 32); err == nil {
  fmt.Printf("%T, %v\n", n1, n1)
 }
 if n2, err := strconv.ParseFloat(floatString, 64); err == nil {
  fmt.Printf("%T, %v\n", n2, n2)
 }

}
An output of the above program
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax
float64, 587.22998046875
float64, 587.23

Convert float number to String example

There are two ways to convert float type to String type
one is using fmt.Sprintf() function, other is using strconv.FormatFloat function

fmt Sprintf function example

fmt package provides Sprintf is used to convert to string
Here is a syntax
func Sprintf(format string, a ...interface{}) string 

the format is a string
%f - Decimal format
%e - scientific notation format
%.5f- the precision with 5 format
%g - exponent format

and parameter a is of the vardiac interface which accepts any type of value

Here is a fmt Sprintf function example program 
package main

import (
 "fmt"
 "reflect"
)

func main() {
 str := fmt.Sprintf("%f", 45.1) //45.100000
 fmt.Println(reflect.TypeOf(str))
 fmt.Println(str)
 str1 := fmt.Sprintf("%e", 45.1) //4.510000e+01
 fmt.Println(reflect.TypeOf(str1))
 fmt.Println(str1)
 str2 := fmt.Sprintf("%.5f", 45.1) //45.10000
 fmt.Println(reflect.TypeOf(str2))
 fmt.Println(str2)
 str3 := fmt.Sprintf("%g", 45.1) //45.1
 fmt.Println(reflect.TypeOf(str3))
 fmt.Println(str3)
}
Output is
string
45.100000
string
4.510000e+01
string
45.10000
string
45.1

strconv FormatFloat function example 

strconv package has FormatFloat function is to convert the floating number to string with a given format and precision Here is a syntax of this function
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
Arguments are

floating number converted to a string
fmt is of byte contains values b -binary exponent, e or E - Decimal exponent, F - no exponent, g or G - large exponents
prec  is of int precision value
bitSize is of int type which contains 32 and 64 values Here is an strconv FormatFloat function example program
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatNumb := 5.789455
 str := strconv.FormatFloat(floatNumb, 'f', 5, 64)
 fmt.Println(reflect.TypeOf(str))
 fmt.Println(str)
 str1 := strconv.FormatFloat(floatNumb, 'e', 5, 64)
 fmt.Println(reflect.TypeOf(str1))
 fmt.Println(str1)
 str2 := strconv.FormatFloat(floatNumb, 'g', 5, 64)
 fmt.Println(reflect.TypeOf(str2))
 fmt.Println(str2)
}

Output is
string
5.78946
string
5.78946e+00
string
5.7895 

Tuesday, December 11, 2018

Golang Recursion - Recursive function with examples

In this blog post, we are going to learn Recursive functions in golang with examples.

golang recursive function

Recursion is general programming code process in which method or function calls itself continuously. Go Language support recursion using functions. In Golang, function call itself is called recursive function. Using this technique, It allows code simple but complex to understand the code.

 Important key points of recursion function.
  • Function called inside the same function
  • It is always good to specify an exit condition in the recursive function
  • It reduces unnecessary function calls and code lines 
  • Disadvantages with recursion is code is logical and difficult to debug and inspect the code

Syntax

// function declaration
func recursefunction(){
//Code statements
recursefunction();//function call itself
}
func main(){
recursefunction() // Initialize first normal call
}
In the above syntax, the recursive function is being called inside the same function. Recursion process continues execution until the condition is met. otherwise, function executions in infinite recursion We can prevent infinite recursion using if else statements, if block executes recursive calls, else block will break the recursive call

Golang Recursion function Example: Infinite times 

function recursivefunction is declared. This will be called inside the main function during a normal first call. recursivefunction() is called inside same function. This will be executed infinite times. We have to issue a manual CTRL +C keyword to exit from the program execution
package main

import (
 "fmt"
)

func recursivefunction() {
 fmt.Println("welcome")
 recursivefunction()
}

func main() {
 recursivefunction()
}
Output is
welcome
welcome
welcome
.....
infite times

Golang Recursion function Example: finite times

In the below example recursive function is declared and called inside the main function at first during the normal first function call. the same function is called recursively inside the same function. This recursive call executes 10 times and exit from the recursive function. if statement is used to exit from the function.
package main

import (
 "fmt"
)

var count = 0

func recursivemethod() {
 count++
 if count <= 10 {
  fmt.Println(count)
  recursivemethod()
 }
}

func main() {
 recursivemethod()
}
Output is
1
2
3
4
5
6
7
8
9
10

Recursion function Example generates Factorial Number 

A recursive function is declared to calculate a factorial. This return factorial of a number here is a program code for calculating the factorial number.
package main

import "fmt"

func factorial(numb int) int {
 if numb == 0 {
  return 1
 }
 return numb * factorial(numb-1)
}

func main() {
 result := factorial(5)
 fmt.Print("Output for Factorial of 5 :", result)
}
Output is
Output for Factorial of 5 :120

Recursion example for calculating Fibonacci series 

The following program calculates and returns the Fibonacci series for a given input number using a recursive function
package main

import "fmt"

func fibonacci(value int) int {
 if value == 0 || value == 1 {
  return value
 }
 return fibonacci(value-2) + fibonacci(value-1)
}
func main() {
 result := fibonacci(10)
 fmt.Print("Output for Fibonacci series  of 10 :", result)
}
Output is
Output for Fibonacci series  of 10 :55

Recursive anonymous function 

The anonymous function is a function without a name. Recursive functions can be declared as anonymous also.
Following is example program for Recursive anonymous function in golang
package main

import "fmt"

func main() {
 var myfunction func()
 myfunction = func() {
  fmt.Println("Anonymous function example")
  myfunction()

 }
 myfunction()

}
Output is
Anonymous function example
Anonymous function example
...
...
...
infinite times

Monday, December 10, 2018

Golang Example - strconv ParseFloat function guide

This blog post covers package strconv ParseFloat Function with examples in the Go Language.
Golang Example - strconv ParseFloat function guide

golang strconv ParseFloat function

strconv is a standard inbuilt package in go language that provides various function implementations for converting a string to types into an int, float, boolean etc..
String to float is a common task of a programmer during development
ParseFloat is an inbuilt function, converts a String value to a floating  number
You can check official documentation is here
Here is the syntax of this function
func ParseFloat(inputstring string, bitSize int) (float64, error)
Argument list
inputstring is a numeric floating number represented in string bitSize is int type argument of precision value. It can be 32 for float32 or 64 for float64
Return type 
This function always returns two values. The float64 value is returned which contains a floating number.we can convert to float32 value if required. the error is returned with *NumError value if unable to convert a string to a floating number

function usage - success and error cases 

Following are various uses cases of converting a string to floating types In the below code, ParseFloat() function takes a string and convert it to a floating number with given precision of 64. For Conversion, 64bits are considered. Go language uses IEEE_754  binary format for storing floating numbers Returned floating number of type float64 and error-nil is returned.
floatNumb, err := strconv.ParseFloat("123.3412312312", 64)
fmt.Println(floatNumb)
fmt.Println(reflect.TypeOf(floatNumb))
fmt.Println(err)
Output is
123.3412312312
float64
<nil>
Now we will see changing precision value from 64 to 32
floatNumb, err := strconv.ParseFloat("123.3412312312", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 
output is
123.34123229980469
float64
<nil>
The below example gives an error - strconv.ParseFloat: parsing "abc": invalid syntax when given input string is not numeric In this case, this function returns 0 value of type float64 and err contains a description of an error
floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 
Output is
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax

ParseFloat function Example program

Here is an example for Converting string to float64 numbers using parseFloat.
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatString := "12545.23"
 floatNumb, err := strconv.ParseFloat("abc", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 if n1, err := strconv.ParseFloat(floatString, 32); err == nil {
  fmt.Printf("%T, %v\n", n1, n1)
 }
 if n2, err := strconv.ParseFloat(floatString, 64); err == nil {
  fmt.Printf("%T, %v\n", n2, n2)
 }

}
Output is
0
float64
strconv.ParseFloat: parsing "abc": invalid syntax
float64, 12545.23046875
float64, 12545.23

Convert String to float64/float32 values

ParseFloat() function returns float64 value by default. float32(float64value) function used to convert to float32 value Here is an program code for casting string to float64/float32
package main

import (
 "fmt"
 "reflect"
 "strconv"
)

func main() {
 floatNumb, err := strconv.ParseFloat("123.23", 32)
 fmt.Println(floatNumb)
 fmt.Println(reflect.TypeOf(floatNumb))
 fmt.Println(err)
 float32Value := float32(floatNumb) // Convert to float 32
 fmt.Println(float32Value)
 fmt.Println(reflect.TypeOf(float32Value))
}
Output is
123.2300033569336
float64
<nil>
123.23
float32