Decision Making in Go lang

Introduction to decision making Sometimes we need to introduce a power in our program, that our program should automatically make the decision.

For example:  if the temperature of the day is more than 20 degree then it's hot otherwise it's cool.

To introduce this kind of power in our program, we use decision making statements as the list below...
if-else statementsnested if-else statementselse-if ladderswitch/case-control statement Let's create a program to check whether a number is even or odd. Program to check a number is even or odd in Go lang. package main
import "fmt"
func main() {
var n int32
fmt.Print("Enter any number:")
if n % 2 == 0 {
fmt.Println(n,"is even")
} else {
fmt.Println(n,"is odd")
} Output: Enter any number:55
55 is odd  Explanation:A number is even if it is divisible by 2 otherwise odd.So to check a number is even or odd, we need to check divisibility by 2.To perform the divisibility test we use mod (%…

History of C programming language

History of CC is a general-purpose programming language initially developed by the Dennis Ritchie between 1969 to 1973 at AT & T (American Telegraph and telecommunication) Bell Labs.It is named C because its features are derived from the earlier language called B which is developed by the Ken Thomson. According to Ken Thomson B was the stripped-down version of BCPL (Basic combined programming Language).The origin of c is closely tied up with the Unix operating system development.In 1973 with the addition of struct type the c becomes powerful enough that the Unix operating system was designed in C.This was one of the first operating system kernels implemented in a language other than assembly.In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.This book, known to C programmers as "K&R", served for many years as an informal specification of the language.The version of C that it describes is commonly referred to as K&…

Looping in go lang

Loop is a structure with the block of statements can be repeated for the finite number of times. 
Till Now we have learned the programs that execute sequentially, Now we are going to learn control structures which change the normal flow of the program and helps you to create more meaningful and compact program structure.

To understand more, suppose we want to print from 1 to 10 number counting, each number should be printed in the new line.
Program to print numbers from 1 to 10 package main
import "fmt"
func main( ) {
} Another compact way to create this program use loop. The following example creates this program using the loop. Program package main
import "fmt"
func main() {
i := 1 //initialization
for i <= 10 { //condition
fmt.Println(i) //statement
i = i + 1 //updates
} Output 1
10With the above program sn…

Convert Temperature from Fahrenheit to centigrade

The formula to convert temperature from Fahrenheit to Centigrade is as below...C = ( F - 32 ) * 5 / 9
where C and F are temperature in Centigrade and Fahrenheit in respectively. package main
import "fmt"
func main() {
var f float32
fmt.Print("Enter the temperature in fahrenheit: ")
c := ( f - 32 ) * 5 / 9
fmt.Printf("Temprature in centigrade: %.2f",c)

Constant in Go lang

Constant in go langConstants are basically variable which value can't change once created.Constants are created in the same way as variables, the only difference is that to create a variable use var keyword and to create constant use const keyword. Constant Example-1 package main
import "fmt"
func main() {
const playerName string = "Rahul"
//playerName = "Micky" //compile time error, cannot assign to playerName.
} Constant Example-2 package main
import "fmt"
func main() {
const METER_PER_FEET = 0.3048
var feet,meter float32
fmt.Print("Enter value in feet...")
meter = feet * METER_PER_FEET
fmt.Printf("Meter %.2f",meter)
}  Note:In the above example, METER_PER_FEET is a constant.It is suggested that constant name should be written in uppercase, each word separated by an underscore so can be easily identified.

Simple interest in go lang

package main
import "fmt"
func main() {
var p int
var r float32
var t int
fmt.Print("Enter principal, rate and time: ")
si := float32(p) * float32(t) * r / 100
fmt.Printf("Simple interest: %.2f",si)
} Explanation  Most of the things of the above program are already discussed. bur some of the important statement is discussed here. si := float32(p) * float32(t) * r / 100
The above program statement performs a simple calculation p * t * r / 100 and stores the result in variable si. In go lang in a single expression multiple types are not allowed, so we need to convert p and t into float32 type and expression p * t * r becomes a float32 type expression.To typecast a variable we use the following syntax type(var)
 In the above program snippet to print the result fmt.Printf("Simple interest : %.2f",si).Printf() is a function used to print the formatted output.%.2f prints a floating point value with only 2 decimal places.

Identify Variable type and values in go lang

package main
import "fmt"
func main() {
var name string = "Mahesh"
age := 25
price := 300.40
fmt.Printf("%T %v\n",name,name)
fmt.Printf("%T %v\n",age,age)
fmt.Printf("%T %v\n",price,price)
} Output string Mahesh
int 25
float64 300.4
ExplanationIn the above program snippet, we use Printf() functionof fmt package to print the formatted output.Withing the Printf( ) %T and %v is called format specifier which represents the output format.%T represents the Type, which prints the variable type%v represents the variable's value.age := 25, creates a variable age with the short variable declaration and assign the value 25. In this case, the variable automatically receives the type and here age is the type of int.price:=300.40, In this statement price, is created of type float64 because float64 is the default type of floating values in go lang. To create a float32 type variable you need to create a variable as given below.\n is called escape seque…

Sum of two numbers in go lang

package main
import "fmt"
func main() {
var a,b int
a = 5
b = 10
sum := a + b
fmt.Println("Total = ",sum)
} Explanationvar a,b int: declare two variable a and b. Learn here how to create variablea = 5 and b = 10 assign 5,10 to a,b respectivelysum:= a + b:  adds a and b and store the result in sum as well as created sum variable with the short variable declaration (:=). fmt.Println("Total = ",sum): prints the result as Total = 15 ImprovementsAbove program always returns fixed result Total = 15, because a and b are initialized with fixed value 5, 10 respectively.So this program can be improved by using user input.As well as above program variable declaration and initialization can be done in a single statement as shown here var a,b int = 5 , 10
var a,b = 5 , 10 Sum of two numbers with user input package main
import "fmt"
func main() {
var a,b int
fmt.Print("Enter any two numbers: ")
sum := a + b
fmt.Println("Total …

Program to print Hello world in go lang

package main
import "fmt"
func main() {
fmt.Println("Hello Go Lang")
} Output  Hello Go lang ExplanationIf you are a beginner an don't know how to install go lang and run the program, you can learn installation with the installation of go lang.To read the complete explanation of the above program visit, How to print Hello world in go lang.

Variable Naming & Scope of Variable

Rules for Creating the variable nameVariable name can contain Alphabets (A-Z/a-z), Digits (0-9) and Underscore( _ ).A variable name must start with alphabet or underscore.Spaces and special systems are not allowed.Reserved words are not allowed as a variable name.A variable name should be meaningful.Go is case sensitive language so age, Age, AGE all are treated as a different variable. Some correct variable namesnamefather_namefatherName__AGEnumber1car_modal_nameis_verifiedintnum Some incorrect variable names father's_namefather#name2persons0007000Nameinta#b Note There are two popular ways to create multi-word variables. player_name: Each word is separated by an underscoreplayerName: camel case, the first word is in small and from second word first letter of each word is capitalized. Variable Scope Scope is the range of places where a variable is allowed to be used is called variable scope.Variable Scope can be of two typesLocal variables Local variables are those which are allowed…

Variables in Go lang

What is variable Variable is an entity which can change during the problem. For example: y = x + 5xy162738
As shown in the above example, as the value of x is changing y gets changed. so in the above expression x and y are variable and 5 is a constant.
In programming whenever you create a variable, a memory is reserved and a name is assigned to it. If initialized with value then binary value of that will gets stored in memory otherwise initialized with default value. Following figure shows the memory map of a variable. Creating a variable var name string = "Hello Go"
In the above example, a variable is created labeled with the name of type string and initialized with value "Hello Go". the var keyword is used to create a variable. var name = "Hello Go"
 In the above code snippet, the only difference is that data type is not given, because when you initialize the variable then compiler automatically adopts the type from the initialized value. name := "H…

Boolean in go lang

Boolean (named on gorge bool) is a special 1 bit value which represents true or false.In Go lang, true and false are two reserved literals which represent Boolean values.Like some other programming language C, C++, go doesn't allow 1 at the place of true and 0 at the place of 0.Boolean values can be combined with logical operators. List of the logical operators is given below.&&AND||OR!NOT Logical operators&& (AND) and || (OR) operators are used to combine two or more Boolean values/expressions.! (Not) operator also called negation, just reverse the Boolean values.!true results false!false results true&& (AND) operator returns true if all the conditions are true.|| (OR) operator returns true if any one condition is true.The outcome of the combination will be based on the following truth table. Truth table for && (AND) and || (OR) operatorC1C2C1 && C2C1 || C2falsefalsefalsefalsefalsetruefalsetruetruefalsefalsetruetruetruetruetrue Example-1: …

String in golang

Strings are sequence of characters with definite length and can be created by enclosing in double quotes "Hello Go" and back ticks `Hello Go`. A string is a sequence of characters.Strings are the collection of individual bytes, where each character occupy single byte.Characters out of the ASCII characters (can say characters from other languages) occupy more than one byte.A string can be created by enclosing in double quotes "Hello Go" or backticks `Hello Go`.The difference between double quotes and backticks is that double quotes allow escape sequences like \n (newline) and \t (tab) and parses them but backticks don't. Example-1: package main
import "fmt"
func main( ) {
        fmt.Println(len("Hello Go"))
        fmt.Println("Hello Go"[1])
        fmt.Println("Hello"+" "+"Go")
} Output: 8101Hello Go 
 Output Explained:

fmt.Println(len("Hello Go")) returns the length of the string "Hell…

Floating point Data types in Go lang

As we have discussed, In our previous article Data types in go lang, In Go lang Numbers can be categorized into two broad categories. Integral NumbersFloating point Numbers We have already discussed integral numbers In this article we will discuss all floating point numbers.
Floating point Numbers Floating point numbers are those which contains decimal places, for example (2.34 , -90.435 , 0.00007) Rules for floating point numbers 
Floating point number can contain decimal places, For example (0.006, 2.45)Can be +ve and -ve.Floating point number can be written in two formatsFixed format, example (0.007)Exponent format, example (0.7 E -4)0.7 E -4 is equivalent to 0.7 * 10 <sup>-4</sup>In 0.7 E -4, 0.7 (part before e) is called mantissa and -4 (part after E) is called exponent.Exponent format is used when a number is too large or too small to represent in decimal places.Floating point number can be of 32bits or 64bits in size in go lang.float32 represents 32 bits floating poi…

Data Types in Go language

Data type defines a set of related values, describe the operations that can be done on them and define the way the stored in memory.  For example: Suppose you have a Car of VW Polo, but a car can be of any other company with some other basic and some advanced features.
But if we called a name Car, then in your mind a picture is created that there is a vehicle with 4-wheels and steering. Each car has some features like the color, company, make, model etc.

Types in programming work in a similar way, For example, "Hello World" is a string and every string have some length.

Numbers Go Comes with different types to represent numbers, Numbers can be categorized into two broad categories...
Integer The integer represents only those numbers which don't include any decimal places and can be of any positive and negative numbers. Example : {1, 3, -4, 11, 123, 534} all are integer numbers
Go's integer type can be uint8, uint16, uint32, uint64, int8, int16, int32, and int64. 8, 1…

Say Hello world in Go lang

Writing your first program "Hello World" package main
import "fmt"
func main( ) {
       fmt.Print("Hello World")
} Understanding the program line by line As we have discussed in the overview of go lang that Go program is organized in the various package. Here first statement package main specifies that this program will belong to the package main.Next line import "fmt" includes the predefined package fmt in your program so that you can use the functions (features) of this package in your program. Here import is the keyword in go lang use to import package(s).fmt stands for the format, fmt package has the various pre-defined function like Print, Println, Printf to print the formatted text and other methods like Scanf for reading the formatted values.Next Line defines the main() function, which is the starting point of every program. func is a keyword in go lang to define a function.Within the main() function we have written fmt.Print("Hello…

Installing go lang

On WindowsDownload the latest version of go MSI installer from best suited for your system architecture.Start the installation by double-clicking on the installer and installer wizard will open as given in the following figure. For the installation follow the wizard instructions.Note that when you installing go lang using installer then it will ask the location where go will be installed as shown in the figure below. Installation directory of go lang is called GOROOT here the GOROOT is c:\go directory.After this follow the wizard instructions and complete the go lang installation. Test Go installation To Check that Go is installed correctly or not, you need to create a go workspace (a place /folder/directory in which you save you go programs) and create a sample go program and run the program using the command line. The sample program is given below...You can create a sample program by using any simple text editor like notepad, notepad++, sublime or anyone you lik…

Overview of Go lang

Go is a Open source programming language that makes it easy to build simple, reliable and efficient software. History of Go lang The Go programming language is initially started in 2007 as an internal Google project.The original designed by Robert Griesemer, Rob Pike and Ken Thomson.November 2009, Go is publicly released under the open source license.Go has an open source model and many developers over the world contribute to it with the original designers.  Overview of Go langGo is often referred to as "Simple" programming language, a language that can be learned in a few hours if you already know another language C / C++.Go language was designed to feel familiar and to stay as simple as possible.Go language is created System programming in mind, even go can be used to create a web application using Google's App Engine. Why Go lang 1) Efficient use of 21st-century computers Computers have evolved, but programming language doesn't have the same pace of evolution. Tod…

Lists in HTML

What is List? List is a group of items related to each other. Typed of list in htmlUnordered listOrdered listDefination list Unordered V/S Ordered List
Unordered listUnordered list is a group of related items arrange in no order.Order list is created by using <ul> </ul> tag.<li> </li> tag is used to create list items in the list. Creating Unordered List <ul>
       <li>Cold Drink</li>

Types of Unordered ListOrdered ListOrdered list is a group of elements a particular order.<ol> </ol> tag is used to create ordered list.<ol>
     <li>Cold Drink</li>

Types of ordered list Examples of ordered list
Definition List Definition list a group of items with key (terms) and value (definition) pair.

<dl> tag is used to create definition list.<dt> tag creates definit…

Formatting in HTML

What is the formatting?  Formatting means organize things for better presentation.  Formatting tags in HTML
Bold <b> V/S Strong <strong><b> Bold Text</b>
<strong> Strong Text</strong>Note:Both generates the same result but are semantically different.Strong is used to mark the important text. Italic <i> V/s Emphasize <em> <i> Italic Text </i>
<em> Emphasized Text </em>

Underline <u> v/S Insert <ins><u> Underline Text </u>
<ins> Insert Text </ins>

<strike> V/S <del><strike> Strike through text</strike>
<del> Deleted text </del>

Superscript V/S Subscript5 <sup>2</sup>
H <sub>2</sub>O

Center<center>Center aligned text</center>

Font Tag

Popular posts from this blog

Overview of Go lang

Arrays in C Language

Data Types in Go language

Creating your first html page

Say Hello world in Go lang

Arrays in Go lang

Installing go lang

String in golang

Decision Making in Go lang

Decision Making Statements