Error : Index was outside of the bounds of the array - c#

When I run this code:
Console.Write("How many numbers do you wish to enter? ");
int n = int.Parse(Console.ReadLine());
int[] arrayOfNumbers = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Enter number [{0}]: ", i + 1);
arrayOfNumbers[i] = int.Parse(Console.ReadLine());
}
int minNumber = arrayOfNumbers[0];
int maxNumber = arrayOfNumbers[0];
int sumOfNumbers = 0;
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[n] < minNumber)
{
minNumber = arrayOfNumbers[n];
}
else if (arrayOfNumbers[n] > maxNumber)
{
maxNumber = arrayOfNumbers[n];
}
sumOfNumbers += arrayOfNumbers[n];
}
double sumDouble = (double)sumOfNumbers;
double average = sumDouble / n;
Console.Write("The min number is : {0}", minNumber);
Console.Write("The max number is : {0}", maxNumber);
Console.Write("The sum of the numbers is : {0}", sumOfNumbers);
Console.Write("The average sum of the numbers is : {0:f2}", average);
It gives me an error : Index was outside of the bounds of the array.
The error is at line 28.
I have a task to find min and max number + sum and average of 'n' numbers.

Inside the for, you must replace the variable 'n' by 'i'.
Like this:
(...)
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[i] < minNumber)
{
minNumber = arrayOfNumbers[i];
}
else if (arrayOfNumbers[i] > maxNumber)
{
maxNumber = arrayOfNumbers[i];
}
sumOfNumbers += arrayOfNumbers[i];
}
(...)

Related

Storing values in an array and outputting the highest,lowest,average. Output flaw

This was a small problem the teacher gave us at school. We were asked to make a program which keeps asking the user to input test scores until he inputs -99 to stop the program. The values are stored in an array and the highest, lowest and average scores are displayed.
The problem I have with my code is that whenever I run it it always gives me a value of 0 for lowest scores even though there are no zeros in the input. Can anyone please point out the mistake in my code?
Code:
static void Main(string[] args)
{
int[] za = new int[100];
scores(za, 0);
}
public static void scores(int[] ar, int x)
{
Console.Write("Please enter homework score [0 to 100] (-99 to exit): ");
int a = Convert.ToInt16(Console.ReadLine());
if (a != -99)
{
ar[x] = a;
x++;
scores(ar, x);
}
else
{
Console.Clear();
Console.WriteLine("Homework App");
int[] arr = new int[x];
foreach (int l in arr)
{
arr[l] = ar[l];
}
int lowest = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (lowest > arr[i]) { lowest = arr[i]; }
}
int highest = arr[0];
for (int j = 1; j < arr.Length; j++)
{
if (highest < arr[j]) { highest = arr[j]; }
}
double sum = 0;
double nums = 0;
for (int k = 0; k < arr.Length; k++)
{
sum = sum + arr[k];
nums++;
}
double average = sum / nums;
Console.WriteLine("Highest Score: {0}", highest);
Console.WriteLine("Lowest Score: {0}", lowest);
Console.WriteLine("Average Score: {0}", average);
Console.ReadLine();
}
}
When you're copying items, don't use a foreach loop and then the element stored in the array as the index that you're inserting to. Instead, use a for loop with a counter variable.
You should change this:
int[] arr = new int[x];
foreach (int l in arr)
{
// You're using the wrong value for the index here.
// l represents the value of the item stored in `arr`, which is `0`
arr[l] = ar[l];
}
To this:
int[] arr = new int[x];
for (var counter = 0; counter < x; counter++)
{
arr[counter] = ar[counter];
}

c# subtract a number from an array index in a for loop

I need to find the difference of each number value in an array from an average value. I need to loop through each value and subtract each value FROM the average and display the difference. I have tried several different ways but the difference always comes out as 0 at the end. What am i doing wrong here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace AvgNDiff
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int x = 0;
int i;
string entryString = "";
int counter = 0;
int countdown = 10;
int sum = 0;
int average = 0;
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0")
{
if (x == 0)
Write("Enter up to 10 numbers or type 0 to stop > ");
else if (x == 9)
Write("Enter {0} more number or type 0 to stop > ", countdown);
else
Write("Enter up to {0} more numbers or type 0 to stop > ", countdown);
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
if (entryString != "0")
{
sum += numbers[x];
counter++;
x++;
}
countdown--;
}
average = sum / x;
WriteLine("\n\nYou entered {0} numbers with a sum of {1}", x, sum);
WriteLine("The average of your numbers is " + average);
WriteLine("\n\nNumber Difference");
WriteLine("-------------------------------");
for (i=0; i < x; i++)
{
int value = numbers[i];
int diff = average-value;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), diff));
}
ReadKey();
}
}
}
Take a look here
int value = numbers[i];
int diff = value - average;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), value));
the key issue here is the writeline statement.
Youve told it to display numbers[i], and oh wait.. numbers[i] (as thats what value is)
yet diff contains the variance from the average...
static void Main(string[] args)
{
List<int> numberList = new List<int>();
Console.WriteLine("Enter up to 10 numbers or type 0 to stop:");
for (int i = 0; i < 10; i++)
{
int userInput = 0;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Only integer numbers accepted, let's try again...:");
}
if (userInput == 0)
{
break;
}
else
{
numberList.Add(userInput);
if (i < 9)
{
Console.WriteLine("Yeah, {0} more number{1} to go!", (9 - i), (i == 8 ? "" : "s"));
}
}
}
double average = numberList.Average();
for (int i = 0; i < numberList.Count; i++)
{
Console.WriteLine("#{0}: {1} - {2} = {3}", (i+1), numberList[i], average, (numberList[i] - average));
}
Console.ReadLine();
}
Do not cram the entire soultion into the single Main, extract (and debug) a method:
// Subtract each item from the average
private static double[] MyNormalize(int[] source) {
double sum = 0.0;
foreach (var item in source)
sum += item;
double[] result = new double[source.Length];
for (int i = 0; i < source.Length; ++i)
result[i] = sum / source.Length - source[i];
return result;
}
...
static void Main(string[] args) {
int[] numbers = new int[10];
...
// Input
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0") {
...
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
}
// Business logic
double[] norm = MyNormalize(numbers);
// Output
for (int i = 0; i < numbers.Length; ++i)
WriteLine(String.Format("{0,-10} {1,-10}", numbers[i], norm[i]));
}

Getting an error about variable not existing in current context

I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}

sequence with min & max numbers

I'm trying to get this program to let me enter a desired number(entries), then enter a desired value to this entries. It should write out the biggest value(green), smallest(red) then the rest of the sequence. And in the next row, biggest and smallest should change places(didn't even type code for this). What am I doing wrong(especially in the last 'for loop' )
int max = int.MinValue;
int min = int.MaxValue;
Console.WriteLine("How many numbers do you want to enter ? ");
int kolicinaBrojeva = int.Parse(Console.ReadLine());
int[] niz = new int[kolicinaBrojeva];
for (int i = 0; i < kolicinaBrojeva; i++)
{
Console.WriteLine("Enter {0}. a number:", i + 1);
niz[i] = int.Parse(Console.ReadLine());
if (niz[i] > max)
{
max = niz[i];
}
if (niz[i] < min)
{
min = niz[i];
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(max + ", ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(min + ", ");
Console.ResetColor();
for (int i = 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
The last for loop should be like below:
for (int i = kolicinaBrojeva - 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
Your current code will read in kolicinaBrojeva numbers correctly, but min and max will not be set correctly. No other int is greater than int.MaxValue and similarly, no other int is less than int.MinValue. You could do the following instead:
int max = int.MinValue;
int min = int.MaxValue;
With this, you'll get the correct min and max, however, I'm not sure of what you're trying to do in the last loop.
Try this.
using System;
class Test
{
static void Main()
{
string[] temp = Console.ReadLine().Split();
int[] numbers = new int[temp.Length];
for (var i = 0; i < numbers.Length; i++)
numbers[i] = int.Parse(temp[i]);
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < numbers[minIndex])
minIndex = i;
if (numbers[i] > numbers[maxIndex])
maxIndex = i;
}
Swap(ref numbers[maxIndex], ref numbers[0]);
Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Print(int[] array, ConsoleColor a, ConsoleColor b)
{
Console.ForegroundColor = a;
Console.Write(array[0] + " ");
Console.ResetColor();
for (int i = 1; i < array.Length - 1; i++)
Console.Write(array[i] + " ");
Console.ForegroundColor = b;
Console.WriteLine(array[array.Length - 1]);
Console.ResetColor();
}
}

The second number in his size

Well its not hard and i did it but i dont know how to find it position.
I know to find the position in CASE1 and CASE2 but not in CASE3.
Any help?
int serial = 1, num, max, max2, i = 2,n;
Console.WriteLine("Enter number of numbers");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
/*case 1 */
max = num;
max2 = num;
for (; i <= n; i++)
{
Console.WriteLine("enter num");
num = int.Parse(Console.ReadLine());
/* case 3 */
if (num > max)
{
max2 = max;
max = num;
serial = i;
}
/* case 2 */
else if (num > max2)
{
max2 = num;
serial = i;
}
}
Let use one more variable to store the position of the maximum number also. In the below serial2 is the result of your problem.
int serial = 1, serial2 = 1, num, max, max2, i = 2,n;
Console.WriteLine("Enter number of numbers");
n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number");
num = int.Parse(Console.ReadLine());
/*case 1 */
max = num;
max2 = num;
for (; i <= n; i++)
{
Console.WriteLine("enter num");
num = int.Parse(Console.ReadLine());
/* case 3 */
if (num > max)
{
max2 = max;
max = num;
serial2 = serial;
serial = i;
}
/* case 2 */
else if (num > max2)
{
max2 = num;
serial2 = i;
}
}
I think this is what you're after - you just weren't updating your second largest index when your entered number replaced the largest number:
Console.WriteLine("Enter number of numbers");
int numberOfNumbers = int.Parse(Console.ReadLine());
int? largestNumber = null;
int? secondLargestNumber = null;
int? indexOfLargestNumber = null;
int? indexOfSecondLargestNumber = null;
for (int i = 0; i < numberOfNumbers; i++)
{
Console.WriteLine("Enter number");
int inputNumber = int.Parse(Console.ReadLine());
if (largestNumber == null || inputNumber > largestNumber)
{
secondLargestNumber = largestNumber;
largestNumber = inputNumber;
indexOfSecondLargestNumber = indexOfLargestNumber;
indexOfLargestNumber = i;
}
else if (secondLargestNumber == null || inputNumber > secondLargestNumber)
{
secondLargestNumber = inputNumber;
indexOfSecondLargestNumber = i;
}
}
/*because you started i=1 rather than i=0 as I've done, incrememting the indexes by 1*/
indexOfSecondLargestNumber++;
indexOfLargestNumber++;
Console.WriteLine("The {0} number entered ({1}) was the second largest.",indexOfSecondLargestNumber,secondLargestNumber);

Categories

Resources