PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] What causes panic: runtime error: index out of range [4] with length 4 even though array is initialized as dynamic array

 November 02, 2022     arrays, go, indexing, panic     No comments   

Issue

I have initialized a dynamic array but it shows index out of range.
I have tried giving fixed length also, but it also shows the same error.

Error Description:
panic: runtime error: index out of range [4] with length 4

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums) + 1
    for i := 0; i < arrLen; i++ {
        arrSum += nums[i]
    }
    numSum := arrLen * (arrLen + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}

func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}

Solution

you should change arrLen := len(nums) + 1 to arrLen := len(nums).

Your array length is 4. the indexes are 0,1,2,3 for this. but when you tried to do arrLen := len(nums) + 1 . the arrlen value is now 5. but you have only 4 element. and from your loop you are trying to get a element that is not present in array. that will give you a runtime error and it will panic.

this one will work for you:

package main

import "fmt"

func missingNumber(nums []int) int {
    arrSum := 0
    arrLen := len(nums)
    for i := 0; i < arrLen; i++ {
        arrSum += nums[i]
    }
    m := arrLen + 1
    numSum := m * (m + 1) / 2
    missingNumber := numSum - arrSum
    return missingNumber
}

func main() {
    nums := []int{1, 3, 4, 5}
    result := missingNumber(nums)
    fmt.Println(result)
}


Answered By - Emon46
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing