×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang for Loop | Find Output Programs | Set 1

This section contains the for loop find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on August 14, 2021

Program 1:

package main  

import "fmt"  

func main() {
   for num := 1; num <= 10; num++ 
   {  
      fmt.Print(num," ")  
   }  
}  

Output:

./prog.go:6:35: syntax error: unexpected newline, expecting { after for clause

Explanation:

The above program will generate a syntax error due to the position of curly braces in the for loop. The correct program is given below,

package main

import "fmt"

func main() {
	for num := 1; num <= 10; num++ {
		fmt.Print(num, " ")
	}
}

// Output: 1 2 3 4 5 6 7 8 9 10

Program 2:

package main  

import "fmt"  

func main() {
   for (num := 1; num <= 10; num++) {  
      fmt.Print(num," ")  
   }  
}

Output:

./prog.go:6:13: syntax error: unexpected :=, expecting )

Explanation:

The above program will generate a syntax error due to parenthesis in the for loop. The correct program is given below,

package main

import "fmt"

func main() {
	for num := 1; num <= 10; num++ {
		fmt.Print(num, " ")
	}
}

// Output: 1 2 3 4 5 6 7 8 9 10

Program 3:

package main

import "fmt"

func main() {
	for num := 2; num <= 5; num++ {
		for cnt := 1; cnt <= 10; cnt++ {
			fmt.Print(num*cnt, " ")
		}
		fmt.Println()
	}
}

Output:

2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 

Explanation:

In the above program, we printed tables from 2 to 5 using the nested for loop on the console screen.


Program 4:

package main  

import "fmt"  

fun main() {
   for num := 2; num <= 5; num++ {  
      for cnt := 1; cnt <= 10; cnt=cnt+1 {
        fmt.Print(num*cnt," ") 
      }
      fmt.Println() 
   }  
}  

Output:

./prog.go:5:1: syntax error: non-declaration statement outside function body

Explanation:

The above program will generate a syntax error because we used fun instead of func to define the main() function.


Program 5:

package main

import "fmt"

func main() {
	var num = 10
	for num == 10 {
		fmt.Println("Hello World")
	}
}

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
...
...
Prints "Hello World" infinite times.

Explanation:

The above program will print "Hello World" infinite times because the num==10 condition is true.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.