Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // we'll start with the simplest example that finds the smallest number in and
- // array of numbers of type int.
- package main
- import "fmt"
- func main() {
- x := []int{ // array of numbers of type int
- // just rundom numbers
- 85, 89, 65, 45, 32,
- 1, 21, 32, 56, 66,
- 98, 12, 99, 97, 55,
- }
- // 0th index of x array is 85
- smlNumber := x[0] // assuming first value is the smallest
- // smlNumber goin to hold the numbers and print the smallest one
- for i := 0; i < len(x); i++ { // iterate over the x
- if x[i] < smlNumber {
- smlNumber = x[i] // if smaller value is found replace it with the previous one
- }
- }
- fmt.Println("smlest number is: ", smlNumber) // smlest number is: 1
- // So, we're assuming smlNumber := x[0] is the smallest which is 85.
- // 0th index of x array is 85 . then we're looping over the x array,
- // and asking if x[i] which is 0th index because it's the first iteration,
- // is less than smlNumber which is also 85,
- // and in if block we assign x[i] array's first element at 0th index to the smlNumber = x[i]
- // which becomes smlNumber[85] = i[85],
- // and then we keep doing the same thing for other numbers in the array,
- // but when we come looping to number 1 we assign x[i]
- // to the smlNumber which becomes also 1,
- // and now smlNumber and x[i] they are both hoding the number 1
- // but i keeps looping over x and cheking if x[i] is smaller than smlNumber which is 1
- // and after number 1 in x array we have 21, 32, 56, 66, 98, 12, 99, 97, 55,
- // which is not smaller than one, So that said smlNumber is not going to change once
- // it gets the smallest number, and after iteration is over we just print the smlNumber
- // which holds the number 1.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement