For loop Patterns

Pattern 1 Iterating over array n times

1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5,
1,2,3,4,5,


package main

import "fmt"

func main() {

	arr := []int{1, 2, 3, 4, 5}
	n := len(arr)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%d,", arr[j])
		}
		fmt.Println()
	}
}

Pattern 2 Printing staircase patterns

1,
1,2,
1,2,3,
1,2,3,4,
1,2,3,4,5,

package main

import "fmt"

func main() {

	arr := []int{1, 2, 3, 4, 5}
	n := len(arr)
	for i := 0; i < n; i++ {
		for j := 0; j < i+1; j++ {
			fmt.Printf("%d,", arr[j])
		}
		fmt.Println()
	}
}



1,2,3,4,5,
  2,3,4,5,
    3,4,5,
      4,5,
        5,

package main

import "fmt"

func main() {

	arr := []int{1, 2, 3, 4, 5}
	n := len(arr)
	for i := 0; i < n; i++ {

		for j := i; j < n; j++ {

			fmt.Printf("%d,", arr[j])
		}
		fmt.Println()

		// for spaces
		for j := 0; j < i+1; j++ {
			fmt.Print("  ")
		}

	}
}

Pattern 3 Printing all Subarray

1,
1,2,
1,2,3,
1,2,3,4,
2,
2,3,
2,3,4,
3,
3,4,
4,

package main

import "fmt"

func main() {

	arr := []int{1, 2, 3, 4}
	n := len(arr)
	for i := 0; i < n; i++ {
		for j := i; j < n; j++ {

			//loop is running from i to j
			for k := i; k <= j; k++ {
				fmt.Printf("%d,", arr[k])
			}
			fmt.Println()
		}
	}
}

Pattern 4 Iterating over all Subarray and printing Sum, lengths

Sum[0:0] = 1, length = 1
Sum[0:1] = 3, length = 2
Sum[0:2] = 6, length = 3
Sum[0:3] = 10, length = 4

Sum[1:1] = 2, length = 1
Sum[1:2] = 5, length = 2
Sum[1:3] = 9, length = 3

Sum[2:2] = 3, length = 1
Sum[2:3] = 7, length = 2

Sum[3:3] = 4, length = 1

package main

import "fmt"

func main() {
	arr := []int{1, 2, 3, 4}
	n := len(arr)
	for i := 0; i < n; i++ {
		sum := 0
		for j := i; j < n; j++ {
		
		  // maintain the rollover sum between i to j
			sum += arr[j]
			fmt.Printf("Sum[%d:%d] = %d, length = %d\n", i, j, sum, j-i+1)
		}
	}
}

Please visit https: https://codeandalgo.com for more such contents

Leave a Reply

Your email address will not be published. Required fields are marked *