Go की मूल बातें

Go for Loops

Go has one loop keyword. See its four forms: counting, while-style, infinite and range.

  • शुरुआती
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • The three-part for
  • for as a while loop
  • range
for i := 1; i <= 3; i++
1print
2print
3print
4stop
The loop ends when i <= 3 is false.

One keyword, four forms

Go has one loop keyword: for. It can count with three parts, repeat while a condition is true, run forever until break, or visit every item with range.

The first loop has a start, a condition and a step. The second has only a condition, like while in other languages. The third has nothing and ends with break. range over a string gives the position and the character of each letter.

मुख्य बातें

  1. for i := 1; i <= 3; i++ counts.
  2. for condition { } works like while.
  3. range visits every item.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		fmt.Println("for:", i)
	}

	countdown := 3
	for countdown > 0 { // a while loop
		fmt.Println("while:", countdown)
		countdown--
	}

	total := 0
	for { // an infinite loop, left with break
		total += 10
		if total >= 30 {
			break
		}
	}
	fmt.Println("loop result:", total)

	for index, letter := range "Go" {
		fmt.Println(index, string(letter))
	}
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
for: 1
for: 2
for: 3
while: 3
while: 2
while: 1
loop result: 30
0 G
1 o

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

अगला: Prime Numbers →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज