Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. // we'll start with the simplest example that finds the smallest number in and
  2. // array of numbers of type int.
  3.  
  4. package main
  5.  
  6. import "fmt"
  7.  
  8. func main() {
  9.  
  10. x := []int{ // array of numbers of type int
  11. // just rundom numbers
  12. 85, 89, 65, 45, 32,
  13. 1, 21, 32, 56, 66,
  14. 98, 12, 99, 97, 55,
  15. }
  16. // 0th index of x array is 85
  17. smlNumber := x[0] // assuming first value is the smallest
  18. // smlNumber goin to hold the numbers and print the smallest one
  19. for i := 0; i < len(x); i++ { // iterate over the x
  20.  
  21. if x[i] < smlNumber {
  22.  
  23. smlNumber = x[i] // if smaller value is found replace it with the previous one
  24. }
  25. }
  26. fmt.Println("smlest number is: ", smlNumber) // smlest number is: 1
  27.  
  28. // So, we're assuming smlNumber := x[0] is the smallest which is 85.
  29. // 0th index of x array is 85 . then we're looping over the x array,
  30. // and asking if x[i] which is 0th index because it's the first iteration,
  31. // is less than smlNumber which is also 85,
  32. // and in if block we assign x[i] array's first element at 0th index to the smlNumber = x[i]
  33. // which becomes smlNumber[85] = i[85],
  34. // and then we keep doing the same thing for other numbers in the array,
  35. // but when we come looping to number 1 we assign x[i]
  36. // to the smlNumber which becomes also 1,
  37. // and now smlNumber and x[i] they are both hoding the number 1
  38. // but i keeps looping over x and cheking if x[i] is smaller than smlNumber which is 1
  39. // and after number 1 in x array we have 21, 32, 56, 66, 98, 12, 99, 97, 55,
  40. // which is not smaller than one, So that said smlNumber is not going to change once
  41. // it gets the smallest number, and after iteration is over we just print the smlNumber
  42. // which holds the number 1.
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement