Blog

  • Overview

    Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection, and supports concurrent programming.

    Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. The Go programming language was announced in November 2009 and is used in some of the Google’s production systems.

    Features of Go Programming

    The most important features of Go programming are listed below −

    • Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)
    • Compilation time is fast.
    • Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement.
    • Go programs are simple, concise, and safe.
    • Support for Interfaces and Type embedding.
    • Production of statically linked native binaries without external dependencies.

    Features Excluded Intentionally

    To keep the language simple and concise, the following features commonly available in other similar languages are omitted in Go −

    • Support for type inheritance
    • Support for method or operator overloading
    • Support for circular dependencies among packages
    • Support for pointer arithmetic
    • Support for assertions
    • Support for generic programming

    Go Programs

    A Go program can vary in length from 3 lines to millions of lines and it should be written into one or more text files with the extension “.go”. For example, hello.go.

    You can use “vi”, “vim” or any other text editor to write your Go program into a file.

  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Kotlin is rich in built-in operators and provide the following types of operators:

    • Arithmetic Operators
    • Relational Operators
    • Assignment Operators
    • Unary Operators
    • Logical Operators
    • Bitwise Operations

    Now let’s look into these Kotlin Operators one by one.

    (a) Kotlin Arithmetic Operators

    Kotlin arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication and division etc.

    OperatorNameDescriptionExample
    +AdditionAdds together two valuesx + y
    SubtractionSubtracts one value from anotherx – y
    *MultiplicationMultiplies two valuesx * y
    /DivisionDivides one value by anotherx / y
    %ModulusReturns the division remainderx % y

    Example

    Following example shows different calculations using Kotlin Arithmetic Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x + y = "+(x + y))println("x - y = "+(x - y))println("x / y = "+(x / y))println("x * y = "+(x * y))println("x % y = "+(x % y))}

    When you run the above Kotlin program, it will generate the following output:

    x + y = 60
    x - y = 20
    x / y = 2
    x * y = 800
    x % y = 0
    

    (b) Kotlin Relational Operators

    Kotlin relational (comparison) operators are used to compare two values, and returns a Boolean value: either true or false.

    OperatorNameExample
    >greater thanx > y
    <less thanx < y
    >=greater than or equal tox >= y
    <=less than or equal tox <= y
    ==is equal tox == y
    !=not equal tox != y

    Example

    Following example shows different calculations using Kotlin Relational Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x > y = "+(x > y))println("x < y = "+(x < y))println("x >= y = "+(x >= y))println("x <= y = "+(x <= y))println("x == y = "+(x == y))println("x != y = "+(x != y))}

    When you run the above Kotlin program, it will generate the following output:

    x > y = true
    x < y = false
    x >= y = true
    x <= y = false
    x == y = false
    x != y = true
    

    (c) Kotlin Assignment Operators

    Kotlin assignment operators are used to assign values to variables.

    Following is an example where we used assignment operator = to assign a values into two variables:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x = "+  x)println("y = "+  y)}

    When you run the above Kotlin program, it will generate the following output:

    x = 40
    y = 20
    

    Following is one more example where we used assignment operator += to add the value of self variable and assign it back into the same variable:

    funmain(args: Array<String>){var x: Int =40
    
       x +=10println("x = "+  x)}

    When you run the above Kotlin program, it will generate the following output:

    x = 50
    

    Following is a list of all assignment operators:

    OperatorExampleExpanded Form
    =x = 10x = 10
    +=x += 10x = x – 10
    -=x -= 10x = x – 10
    *=x *= 10x = x * 10
    /=x /= 10x = x / 10
    %=x %= 10x = x % 10

    Example

    Following example shows different calculations using Kotlin Assignment Operators:

    funmain(args: Array<String>){var x: Int =40
    
       x +=5println("x += 5 = "+ x )
       
       x =40;
       x -=5println("x -= 5 = "+  x)
       
       x =40
       x *=5println("x *= 5 = "+  x)
       
       x =40
       x /=5println("x /= 5 = "+  x)
       
       x =43
       x %=5println("x %= 5 = "+ x)}

    When you run the above Kotlin program, it will generate the following output:

    x += 5 = 45
    x -= 5 = 35
    x *= 5 = 200
    x /= 5 = 8
    x %= 5 = 3
    

    (d) Kotlin Unary Operators

    The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

    Following is the list of Kotlin Unary Operators:

    OperatorNameExample
    +unary plus+x
    unary minus-x
    ++increment by 1++x
    decrement by 1–x
    !inverts the value of a boolean!x

    Example

    Following example shows different calculations using Kotlin Unary Operators:

    funmain(args: Array<String>){var x: Int =40var b:Boolean =trueprintln("+x = "+(+x))println("-x = "+(-x))println("++x = "+(++x))println("--x = "+(--x))println("!b = "+(!b))}

    When you run the above Kotlin program, it will generate the following output:

    +x = 40
    -x = -40
    ++x = 41
    --x = 40
    !b = false
    

    Here increment (++) and decrement (–) operators can be used as prefix as ++x or –x as well as suffix as x++ or x–. The only difference between the two forms is that in case we use them as prefix then operator will apply before expression is executed, but if use them as suffix then operator will apply after the expression is executed.

    (e) Kotlin Logical Operators

    Kotlin logical operators are used to determine the logic between two variables or values:

    Following is the list of Kotlin Logical Operators:

    OperatorNameDescriptionExample
    &&Logical andReturns true if both operands are truex && y
    ||Logical orReturns true if either of the operands is truex || y
    !Logical notReverse the result, returns false if the operand is true!x

    Example

    Following example shows different calculations using Kotlin Logical Operators:

    funmain(args: Array<String>){var x: Boolean =truevar y:Boolean =falseprintln("x && y = "+(x && y))println("x || y = "+(x || y))println("!y = "+(!y))}

    When you run the above Kotlin program, it will generate the following output:

    x && y = false
    x || y = true
    !y = true
    

    (e) Kotlin Bitwise Operations

    Kotlin does not have any bitwise operators but Kotlin provides a list of helper functions to perform bitwise operations.

    Following is the list of Kotlin Bitwise Functions:

    FunctionDescriptionExample
    shl (bits)signed shift leftx.shl(y)
    shr (bits)signed shift rightx.shr(y)
    ushr (bits)unsigned shift rightx.ushr(y)
    and (bits)bitwise andx.and(y)
    or (bits)bitwise orx.or(y)
    xor (bits)bitwise xorx.xor(y)
    inv()bitwise inversex.inv()

    Example

    Following example shows different calculations using Kotlin bitwise functions:

    funmain(args: Array<String>){var x:Int =60// 60 = 0011 1100  var y:Int =13// 13 = 0000 1101var z:Int
    
       z = x.shl(2)// 240 = 1111 0000println("x.shl(2) = "+  z)
       
       z = x.shr(2)// 15 = 0000 1111println("x.shr(2) = "+  z)
       
       z = x.and(y)// 12 = 0000 1100println("x.and(y)  = "+  z)
       
       z = x.or(y)// 61 = 0011 1101println("x.or(y)  = "+  z)
       
       z = x.xor(y)// 49 = 0011 0001println("x.xor(y)  = "+  z)
       
       z = x.inv()// -61 = 1100 0011println("x.inv()  = "+  z)}

    When you run the above Kotlin program, it will generate the following output:

    x.shl(2) = 240
    x.shr(2) = 15
    x.and(y)  = 12
    x.or(y)  = 61
    x.xor(y)  = 49
    x.inv()  = -61
    
  • Debugging Program

    A debugger tool is used to search for errors in the programs.

    A debugger program steps through the code and allows you to examine the values in the variables and other data objects during execution of the program.

    It loads the source code and you are supposed to run the program within the debugger. Debuggers debug a program by −

    • Setting breakpoints,
    • Stepping through the source code,
    • Setting watch points.

    Breakpoints specify where the program should stop, specifically after a critical line of code. Program executions after the variables are checked at a breakpoint.

    Debugger programs also check the source code line by line.

    Watch points are the points where the values of some variables are needed to be checked, particularly after a read or write operation.

    The gdb Debugger

    The gdb debugger, the GNU debugger comes with Linux operating system. For X windows system, gdb comes with a graphical interface and the program is named xxgdb.

    Following table provides some commands in gdb −

    CommandPurpose
    breakSetting a breakpoint
    runStarts execution
    contContinues execution
    nextExecutes only the next line of source code, without stepping into any function call
    stepExecute the next line of source code by stepping into a function in case of a function call.

    The dbx Debugger

    There is another debugger, the dbx debugger, for Linux.

    The following table provides some commands in dbx −

    CommandPurpose
    stop[var]Sets a breakpoint when the value of variable var changes.
    stop in [proc]It stops execution when a procedure proc is entered
    stop at [line]It sets a breakpoint at a specified line.
    runStarts execution.
    contContinues execution.
    nextExecutes only the next line of source code, without stepping into any function call.
    stepExecute the next line of source code by stepping into a function in case of a function call.
  • Data Types

    Kotlin data type is a classification of data which tells the compiler how the programmer intends to use the data. For example, Kotlin data could be numeric, string, boolean etc.

    Kotlin treats everything as an object which means that we can call member functions and properties on any variable.

    Kotlin is a statically typed language, which means that the data type of every expression should be known at compile time.

    Kotlin built in data type can be categorized as follows:

    • Number
    • Character
    • String
    • Boolean
    • Array

    (a) Kotlin Number Data Types

    Kotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals.

    Following table list down all the Kotlin number data types, keywords to define their variable types, size of the memory taken by the variables, and a value range which can be stored in those variables.

    Data TypeSize (bits)Data Range
    Byte8 bit-128 to 127
    Short16 bit-32768 to 32767
    Int32 bit-2,147,483,648 to 2,147,483,647
    Long64 bit-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
    Float32 bit1.40129846432481707e-45 to 3.40282346638528860e+38
    Double64 bit4.94065645841246544e-324 to 1.79769313486231570e+308

    If we will try to store a value more than permitted value in a variable of particular data type, the Kotlin compiler will complain because an overflow would occur at runtime.

    Example

    Following example shows how to define and access different Kotlin number data types:

    funmain(args: Array<String>){val a: Int =10000val d: Double =100.00val f: Float =100.00fval l: Long =1000000004val s: Short =10val b: Byte =1println("Int Value is "+ a)println("Double  Value is "+ d)println("Float Value is "+ f)println("Long Value is "+ l )println("Short Value is "+ s)println("Byte Value is "+ b)}

    When you run the above Kotlin program, it will generate the following output:

    Int Value is 10000
    Double  Value is 100.0
    Float Value is 100.0
    Long Value is 1000000004
    Short Value is 10
    Byte Value is 1
    

    (b) Kotlin Character Data Type

    Kotlin character data type is used to store a single character and they are represented by the type Char keyword. A Char value must be surrounded by single quotes, like ‘A’ or ‘1’.

    Example

    Following example shows how to define and access a Kotlin Char data type:

    funmain(args: Array<String>){val letter: Char    // defining a Char variable
       letter ='A'// Assigning a value to itprintln("$letter")}

    When you run the above Kotlin program, it will generate the following output:

    A
    

    Kotlin supports a number of escape sequences of characters. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character

    println('\n')//prints a newline characterprintln('\$')//prints a dollar $ characterprintln('\\')//prints a back slash \ character

    The following escape sequences are supported in Kotlin: \t, \b, \n, \r, \’, \”, \\ and \$.

    (c) Kotlin String Data Type

    The String data type is used to store a sequence of characters. String values must be surrounded by double quotes (” “) or triple quote (“”” “””).

    We have two kinds of string available in Kotlin – one is called Escaped String and another is called Raw String.

    • Escaped string is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.
    • Raw string is declared within triple quote (“”” “””) and may contain multiple lines of text without any escape characters.
    funmain(args: Array<String>){val escapedString : String  ="I am escaped String!\n"var rawString :String  ="""This is going to be a
       multi-line string and will
       not have any escape sequence""";print(escapedString)println(rawString)}

    When you run the above Kotlin program, it will generate the following output:

    I am escaped String!
    This is going to be a
       multi-line string and will
       not have any escape sequence
    

    (d) Kotlin Boolean Data Type

    Boolean is very simple like other programming languages. We have only two values for Boolean data type – either true or false.

    funmain(args: Array<String>){val A: Boolean =true// defining a variable with true valueval B: Boolean =false// defining a variable with false valueprintln("Value of variable A "+ A )println("Value of variable B "+ B )}

    When you run the above Kotlin program, it will generate the following output:

    Value of variable A true
    Value of variable B false
    

    Boolean has a nullable counterpart Boolean? that can store a null value as below:

    val boolNull: Boolean?=null

    (e) Kotlin Array Data Type

    Kotlin arrays are a collection of homogeneous data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

    We will study array in a separate chapter, for now let’s look at one example to define an array of integers and then access its one of the elements.

    funmain(args: Array<String>){val numbers: IntArray =intArrayOf(1,2,3,4,5)println("Value at 3rd position : "+ numbers[2])}

    When you run the above Kotlin program, it will generate the following output:

    Value at 3rd position : 3
    

    Kotlin Data Type Conversion

    Type conversion is a process in which the value of one data type is converted into another type. Kotlin does not support direct conversion of one numeric data type to another, For example, it is not possible to convert an Int type to a Long type:

    funmain(args: Array<String>){val x: Int =100val y: Long = x  // Not valid assignmentprintln(y)}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:3:18: error: type mismatch: inferred type is Int but Long was expected
       val y: Long = x  // Not valid assignment
    

    To convert a numeric data type to another type, Kotlin provides a set of functions:

    • toByte()
    • toShort()
    • toInt()
    • toLong()
    • toFloat()
    • toDouble()
    • toChar()

    Now let’s rewrite above example once again and try to run it:

    funmain(args: Array<String>){val x: Int =100val y: Long = x.toLong()println(y)}

    When you run the above Kotlin program, it will generate the following output:

    100
    
  • Programming Style

    Programming style is all about following some rules while developing programs. These good practices impart values like readability, and unambiguity into your program.

    A good program should have the following characteristics −

    • Readability
    • Proper logical structure
    • Self-explanatory notes and comments

    For example, if you make a comment like the following, it will not be of much help −

    ! loop from 1 to 10 
    do i = 1,10  

    However, if you are calculating binomial coefficient, and need this loop for nCr then a comment like this will be helpful −

    ! loop to calculate nCr 
    do i = 1,10
    • Indented code blocks to make various levels of code clear.
    • Self-checking codes to ensure there will be no numerical errors like division by zero, square root of a negative real number or logarithm of a negative real number.
    • Including codes that ensure variables do not take illegal or out of range values, i.e., input validation.
    • Not putting checks where it would be unnecessary and slows down the execution. For example −
    real :: x 
    x = sin(y) + 1.0
    
    if (x >= 0.0) then
       z = sqrt(x)
    end if
    • Clearly written code using appropriate algorithms.
    • Splitting the long expressions using the continuation marker ‘&’.
    • Making meaningful variable names.
  • Variables

    Variables are an important part of any programming. They are the names you give to computer memory locations which are used to store values in a computer program and later you use those names to retrieve the stored values and use them in your program.

    Kotlin variables are created using either var or val keywords and then an equal sign = is used to assign a value to those created variables.

    Syntax

    Following is a simple syntax to create two variables and then assign them different values:

    var name ="Zara Ali"var age =19var height =5.2

    Examples

    Once a variable is created and assigned a value, later we can access its value using its name as follows:

    funmain(){var name ="Zara Ali"var age =19println(name)println(age)}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    19
    

    Let’s see one more example where we will access variable values using dollar sign $:

    funmain(){var name ="Zara Ali"var age =19println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    

    Let’s see one more example to display the variable values without using a dollar sign as below:

    funmain(){var name ="Zara Ali"var age =19println("Name = "+ name)println("Age = "+ age)}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    

    Kotlin Mutable Variables

    Mutable means that the variable can be reassigned to a different value after initial assignment. To declare a mutable variable, we use the var keyword as we have used in the above examples:

    funmain(){var name ="Zara Ali"var age =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    Name = Nuha Ali
    Age = 11
    

    Kotlin Read-only Variables

    A read-only variable can be declared using val (instead of var) and once a value is assigned, it can not be re-assigned.

    funmain(){val name ="Zara Ali"val age =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"// Not allowed, throws an exception
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:8:4: error: val cannot be reassigned
       name = "Nuha Ali" // Not allowed, throws an exception
       ^
    main.kt:9:4: error: val cannot be reassigned
       age = 11
       ^
    

    Read-only vs Mutable

    The Mutable variables will be used to define variables, which will keep charging their values based on different conditions during program execution.

    You will use Read-only variable to define different constant values i.e. the variables which will retain their value throughout of the program.

    Kotlin Variable Types

    Kotlin is smart enough to recognise that “Zara Ali” is a string, and that 19 is a number variable. However, you can explicitly specify a variable type while creating it:

    funmain(){var name: String ="Zara Ali"var age: Int =19println("Name = $name")println("Age = $age")
       
       name ="Nuha Ali"
       age =11println("Name = $name")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    Name = Zara Ali
    Age = 19
    Name = Nuha Ali
    Age = 11
    

    Soon we will learn more about different data types available in Kotlin which can be used to create different type of variables.

    Kotlin Variable Naming Rules

    There are certain rules to be followed while naming the Kotlin variables:

    • Kotlin variable names can contain letters, digits, underscores, and dollar signs.
    • Kotlin variable names should start with a letter or underscores
    • Kotlin variables are case sensitive which means Zara and ZARA are two different variables.
    • Kotlin variable can not have any white space or other control characters.
    • Kotlin variable can not have names like var, val, String, Int because they are reserved keywords in Kotlin.
  • Program Libraries

    There are various Fortran tools and libraries. Some are free and some are paid services.

    Following are some free libraries −

    • RANDLIB, random number and statistical distribution generators
    • BLAS
    • EISPACK
    • GAMS–NIST Guide to Available Math Software
    • Some statistical and other routines from NIST
    • LAPACK
    • LINPACK
    • MINPACK
    • MUDPACK
    • NCAR Mathematical Library
    • The Netlib collection of mathematical software, papers, and databases.
    • ODEPACK
    • ODERPACK, a set of routines for ranking and ordering.
    • Expokit for computing matrix exponentials
    • SLATEC
    • SPECFUN
    • STARPAC
    • StatLib statistical library
    • TOMS
    • Sorting and merging strings

    The following libraries are not free −

    • The NAG Fortran numerical library
    • The Visual Numerics IMSL library
    • Numerical Recipes
  • Keywords

    Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception.

    Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:

    funmain(){varfun="Zara Ali"// Not allowed, throws an exceptionvar age =19// Valid variable nameprintln("Name = $fun")println("Age = $age")}

    When you run the above Kotlin program, it will generate the following output:

    main.kt:2:7: error: expecting property name or receiver type
       var fun = "Zara Ali"  // Not allowed, throws an exception
    
      ^
    main.kt:2:11: error: expecting '(' var fun = "Zara Ali" // Not allowed, throws an exception
          ^
    main.kt:5:21: error: keyword cannot be used as a reference println("Name = $fun")
                    ^

    Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords

    As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin.

    (a) Kotlin Hard Keywords

    Following is a list of hard keywords and they cannot be used as identifiers:

    asas?breakclass
    continuedoelsefalse
    forfunifin
    !ininterfaceis!is
    nullobjectpackagereturn
    superthisthrowtrue
    trytypealiastypeofval
    varwhenwhile

    (b) Kotlin Soft Keywords

    Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:

    bycatchconstructordelegate
    dynamicfieldfilefinally
    getimportinitparam
    propertyreceiversetsetparam
    valuewhere

    (c) Kotlin Modifier Keywords

    Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:

    actualabstractannotationcompanion
    constcrossinlinedataenum
    expectexternalfinalinfix
    inlineinnerinternallateinit
    noinlineopenoperatorout
    overrideprivateprotectedpublic
    reifiedsealedsuspendtailrec
    vararg
  • Numeric Precision

    We have already discussed that, in older versions of Fortran, there were two real types: the default real type and double precision type.

    However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifie.

    The Kind Attribute

    Different kind of numbers are stored differently inside the computer. The kind attribute allows you to specify how a number is stored internally. For example,

    real, kind = 2 :: a, b, c
    real, kind = 4 :: e, f, g
    integer, kind = 2 :: i, j, k
    integer, kind = 3 :: l, m, n
    

    In the above declaration, the real variables e, f and g have more precision than the real variables a, b and c. The integer variables l, m and n, can store larger values and have more digits for storage than the integer variables i, j and k. Although this is machine dependent.

    Example

    Live Demo

    program kindSpecifier
    implicit none
    
       real(kind = 4) :: a, b, c
       real(kind = 8) :: e, f, g
       integer(kind = 2) :: i, j, k
       integer(kind = 4) :: l, m, n
       integer :: kind_a, kind_i, kind_e, kind_l
       
       kind_a = kind(a)
       kind_i = kind(i)
       kind_e = kind(e)
       kind_l = kind(l)
       
       print *,'default kind for real is', kind_a
       print *,'default kind for int is', kind_i
       print *,'extended kind for real is', kind_e
       print *,'default kind for int is', kind_l
       
    end program kindSpecifier

    When you compile and execute the above program it produces the following result −

    default kind for real is 4
    default kind for int is 2
    extended kind for real is 8
    default kind for int is 4
    

    Inquiring the Size of Variables

    There are a number of intrinsic functions that allows you to interrogate the size of numbers.

    For example, the bit_size(i) intrinsic function specifies the number of bits used for storage. For real numbers, the precision(x) intrinsic function, returns the number of decimal digits of precision, while the range(x) intrinsic function returns the decimal range of the exponent.

    Example

    Live Demo

    program getSize
    implicit none
    
       real (kind = 4) :: a
       real (kind = 8) :: b
       integer (kind = 2) :: i
       integer (kind = 4) :: j
    
       print *,'precision of real(4) =', precision(a)
       print *,'precision of real(8) =', precision(b)
       
       print *,'range of real(4) =', range(a)
       print *,'range of real(8) =', range(b)
       
    
       print *,'maximum exponent of real(4) =' , maxexponent(a)
       print *,'maximum exponent of real(8) =' , maxexponent(b)
      
       print *,'minimum exponent of real(4) =' , minexponent(a)
       print *,'minimum exponent of real(8) =' , minexponent(b)
       
       print *,'bits in integer(2) =' , bit_size(i)
       print *,'bits in integer(4) =' , bit_size(j)
       
    end program getSize

    When you compile and execute the above program it produces the following result −

    precision of real(4) = 6
    precision of real(8) = 15
    range of real(4) = 37
    range of real(8) = 307
    maximum exponent of real(4) = 128
    maximum exponent of real(8) = 1024
    minimum exponent of real(4) = -125
    minimum exponent of real(8) = -1021
    bits in integer(2) = 16
    bits in integer(4) = 32
    

    Obtaining the Kind Value

    Fortran provides two more intrinsic functions to obtain the kind value for the required precision of integers and reals −

    • selected_int_kind (r)
    • selected_real_kind ([p, r])

    The selected_real_kind function returns an integer that is the kind type parameter value necessary for a given decimal precision p and decimal exponent range r. The decimal precision is the number of significant digits, and the decimal exponent range specifies the smallest and largest representable number. The range is thus from 10-r to 10+r.

    For example, selected_real_kind (p = 10, r = 99) returns the kind value needed for a precision of 10 decimal places, and a range of at least 10-99 to 10+99.

    Example

    Live Demo

    program getKind
    implicit none
    
       integer:: i
       i = selected_real_kind (p = 10, r = 99) 
       print *,'selected_real_kind (p = 10, r = 99)', i
       
    end program getKind

    When you compile and execute the above program it produces the following result −

    selected_real_kind (p = 10, r = 99) 8
    
  • Comments

    A comment is a programmer-readable explanation or annotation in the Kotlin source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Kotlin compiler.

    Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Kotlin comments are very much similar to the comments available in Java, C and C++ programming languages.

    Kotlin Single-line Comments

    Single line comments in Kotlin starts with two forward slashes // and end with end of the line. So any text written in between // and the end of the line is ignored by Kotlin compiler.

    Following is the sample Kotlin program which makes use of a single-line comment:

    // This is a commentfunmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    A single line comment can start from anywhere in the program and will end till the end of the line. For example, you can use single line comment as follows:

    funmain(){println("Hello, World!")// This is also a comment}

    Kotlin Multi-line Comments

    A multi-line comment in Kotlin starts with /* and end with */. So any text written in between /* and */ will be treated as a comment and will be ignored by Kotlin compiler.

    Multi-line comments also called Block comments in Kotlin.

    Following is the sample Kotlin program which makes use of a multi-line comment:

    /* This is a multi-line comment and it can span
     * as many lines as you like 
     */funmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, Word!
    

    Kotlin Nested Comments

    Block comments in Kotlin can be nested, which means a single-line comment or multi-line comments can sit inside a multi-line comment as below:

    /* This is a multi-line comment and it can span
     * as many lines as you like 
     /* This is a nested comment */// Another nested comment */funmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!