Home > Software engineering >  Index was outside the bounds of the array. and even my teacher doesn't know the solution
Index was outside the bounds of the array. and even my teacher doesn't know the solution

Time:11-03

I'm trying to make a scan of an array where it follows the index with the numbers inside and I don't understand why it gives me this exception. I cant add any more details its a pretty straight forward question. this is a perfect scan for exsample this is NOT a perfect scan

using System;
                    
public class Program
{
    public static bool IsPerfect(int[] arr)
        {
            int next=0, done=0,i;

            while (done == 0)
            {
                i = arr[next];
                arr[next] = 10;
                next = arr[i];

                if (i == 0)
                    done = 1;
            }

            for(int j = 0; j < arr.Length; j  )            
                if (arr[j] != 10)
                    return false;               
            return true;

          
        }
        
    
    public static void Main()
        {
            int[] arr = { 3, 0, 1, 4, 2 };
            if (IsPerfect(arr) == true)
                Console.WriteLine("is perfect");
            if (IsPerfect(arr) == false)
                Console.WriteLine("boooo");

        }
}

CodePudding user response:

You are not specifying the functioning for duplicates... Use a method to check for duplicates and as soon as you encounter a duplicate element exit the loop... It will work fine!

  • Related