Fakhr
Fakhr

Reputation: 19

Index out of bound. How to resolve

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter the Principal: ");
        int principal = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Please enter the rate: ");
        int rate = Convert.ToInt32(Console.ReadLine());

        int a = rate / 100;
        int b = a * principal;
        int x = b + principal;

        int[] sample = {};

        Console.WriteLine("How long do you want the loop to run: ");
        int loop = Convert.ToInt32(Console.ReadLine());

       // StringBuilder sb = new StringBuilder();

        for (int i = 0; i <= loop; i++)
        {

            sample[x] = x;

           // sb.AppendLine(x.ToString());
            b = a * x;
            x = b + x;
        }
        Console.WriteLine(sample);
    }
 }
}

Hi, I just started learning C# and the topic that my teacher discussed today was arrays. So I decided to create a simple Interest Calculator, but it's giving me

"System.IndexOutOfRangeException: Index was outside the bounds of the array."

Upvotes: 2

Views: 86

Answers (2)

Pethical
Pethical

Reputation: 1482

You must allocate enough space: int[] sample = new int[loop];

Arrays are indexed from zero in C#, so if your array has X length, then the last element's index is X-1. So your for loop should be: for (int i = 0; i < loop; i++)

You are indexing your sample array with x, but I think you wan't to index it with i. sample[i] = x;

You are printing an array, but it will output System.Int32[]. I think you want to print out the elements in the array.

static void Main(string[] args)
{
    Console.WriteLine("Please enter the Principal: ");
    int principal = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Please enter the rate: ");
    int rate = Convert.ToInt32(Console.ReadLine());

    int a = rate / 100;
    int b = a * principal;
    int x = b + principal;

    Console.WriteLine("How long do you want the loop to run: ");
    int loop = Convert.ToInt32(Console.ReadLine());

    int[] sample = new int[loop];

    for (int i = 0; i < loop; i++)
    {
        sample[i] = x;
        b = a * x;
        x = b + x;
    }

    for (int i = 0; i < sample.Length; i++)
        Console.WriteLine(sample[i]);
}

Upvotes: 1

Rans
Rans

Reputation: 602

Do something like this

    Console.WriteLine("How long do you want the loop to run: ");
    int loop = Convert.ToInt32(Console.ReadLine());

    int[] sample = new int[loop];

to set the length from the array

and change your for loop from (int i = 0; i <= loop; i++) to (int i = 0; i < loop; i++)

Upvotes: 1

Related Questions