I am getting the error " Index was outside the bounds of the array". This code that I typed from my text book. Cant seem to find anything wrong with it.
class Program
{
static void Main()
{
int[] scores = new int[8];
int x;
string inputString;
for (x = 0; x < scores.Length; ++x)
{
Write("Enter your score on test {0} ", x + 1);
inputString = ReadLine();
scores[x] = Convert.ToInt32(inputString);
}
WriteLine("\n----------------------------");
WriteLine("Scores in original order: ");
for(x = 0; x < scores.Length; ++x)
Write("{0, 6}", scores[x]);
WriteLine("\n----------------------------");
Array.Sort(scores);
WriteLine("Scores in sorted order: ");
for(x = 0; x < scores.Length; ++x)
Write("{0, 6}", scores[x]);
WriteLine("\n----------------------------");
Array.Reverse(scores);
WriteLine("Scores in reverse order: ");
for(x = 0; x < scores.Length; ++x) ;
Write("{0, 6}", scores[x]);
}
}
}
You have an extra semicolon
for (x = 0; x < scores.Length; ++x) ;
Console.Write("{0, 6}", scores[x]);
The for loop runs, doing nothing except increment x to the final value of 8. Then the next line runs with x still having the value from before, which happens to be 8.
To fix it, remove the extra ;.
Related
I need help with two similar programs about arrays.
The first program is about that the user can enter any number of numbers between 0 and 9 (input can be made by the
Entering "-1" will be terminated).
After the input is finished, it should be output, how often each number between 0 and 9 was entered.
The 2nd program is about to enter 10 names and save them in a string array. After entering should first all names be output. After that, only those namesare to be issued which were entered more than once.
The Code for the 1. Program :
int cnt = 0;
int input;
while (true)
{
cnt++;
Console.WriteLine("Geben Sie bitte die {0,1}. Zahl ein (-1 für Ende):", cnt);
input = Convert.ToInt32(Console.ReadLine());
int[] count = new int[10];
int[] num = new int[cnt];
if (input > 9)
{
break;
}
else if (input == -1)
{
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < num.Length; y++)
{
if (num[y] == x)
count[x]++;
}
}
//For displaying output only
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
And for the 2nd Program :
int cnt = 10;
string[] name = new string[11];
for (int i = 1; i < 11; i++)
{
Console.WriteLine("Name Nr.{0,1} eingeben: ", i);
name[i]++;
name[i] = Console.ReadLine();
}
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < name.Length; y++)
{
if (i == x)
{
//For displaying output only
for (int a = 0; a < 10; a++)
Console.WriteLine("Folgende Namen wurden mehrfach eingegeben : ", name[i]);
break;
The Problem for the 1st Program is that if i type "-1" The number 1-9 always shows that it appeared 0 times and the number 0 always as an example 4 times when i type 4 numbers.
And for the 2nd is that i really dont know how to put strings in arrays. I want to know how to do that, because of the similarity of these 2 programs.
First of all: don't initialize the arrays every loop iteration. Initialize them on the beginning.
Second thing: you must count the numbers before inputting -1. See that you try to increase the count when you enter -1 whereas -1 meant to be program termination I'm assuming.
And third: ask the second problem with string array as another question. You'll get both answers faster that way.
Here's few alteration of your code that needs to be done.
int input;
int[] count = new int[10];
while (true)
{
Console.WriteLine("Geben Sie bitte die {0,1}. Zahl ein (-1 für Ende): ");
input = Convert.ToInt32(Console.ReadLine());
if(input >= 0 && input <= 9)
{
for (int x = 0; x < 10; ++x)
{
if(x == input)
{
count[x] += 1;
}
}
}
else if (input == -1)
{
//Input finished, display of numbers appearances.
for (int x = 0; x < 10; x++)
Console.WriteLine("Number " + x + " appears " + count[x] + " times");
break;
}
else
{
break;
}
}
I am practicing with 2D arrays and am making a program that separates a 2D array with random integer values into two separate arrays based on if the values are even or odd.
However, the program seems to be adding additional zeroes to each row in the even and odd arrays. What am I doing wrong?
I think the problem is in the sort() function where I determine the size of the even and odd arrays but I am not sure.
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[10, 10];
// Fills 2D array with random values and prints them out
Random r = new Random();
for (int y = 0; y < arr.GetLength(0); y++)
{
for (int x = 0; x < arr.GetLength(1); x++)
{
arr[y, x] = r.Next(1, 99);
Console.Write(arr[y,x] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
// Function that separates original array into 2 separate ones (even and odd)
sort(arr);
Console.ReadLine();
}
public static void sort(int[,] array)
{
int j1 = 0;
int i1 = 0;
int j2 = 0;
int i2 = 0;
// Increases the size of the even/odd arrays whenever the value of the original array is even/odd respectively
// I think this is where the problem is
for (int y = 0; y < array.GetLength(0); y++)
{
for (int x = 0; x < array.GetLength(1); x++)
{
if (array[y,x] % 2 == 0)
{
i1 += 1;
}
else
{
i2 += 1;
}
}
j1 += 1;
j2 += 1;
}
int[,] evenArr = new int[j1, i1];
int[,] oddArr = new int[j2, i2];
// Sets the values for the even/odd arrays
for (int y = 0; y < array.GetLength(0); y++)
{
for (int x = 0; x < array.GetLength(1); x++)
{
if (array[y, x] % 2 == 0)
{
evenArr[y, x] = array[y, x];
}
else
{
oddArr[y, x] = array[y, x];
}
}
}
// Prints the values for the even array
for (int y = 0; y < evenArr.GetLength(0); y++)
{
for (int x = 0; x < evenArr.GetLength(1); x++)
{
Console.Write(evenArr[y, x] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
// Prints the values for the odd array
for (int y = 0; y < oddArr.GetLength(0); y++)
{
for (int x = 0; x < oddArr.GetLength(1); x++)
{
Console.Write(oddArr[y, x] + " ");
}
Console.WriteLine();
}
}
}
When you initialize your arrays (evenArr = new int[j1, i1], oddArr = new int[j2, i2];) the default values are zero. Since there's an extra zero it means you should check the length and probably reduce it by one.
I am working on a problem from CodeChef where I need to calculate the factorial of n numbers.
The user inputs a number which determines how many ints to perform a factorial calculation on and then inputs the numbers to calculate.
My problem is with the multiplication itself. For example if I have an int == 5 then the result will be 20 (it will calculate n by the last factorial only, not by all of them)
Here is where the problem exists:
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index
for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x
_result[x] = _numbersToProcess[x] * y;// Multiply x by y then add to array
}
}
The outer loop defines how many calculations to perform.
The inner loop calulates the factorials by iterating through each index of _numberToProcess and multiplying it by every number less than the number to be calculated on.
The problem is that the factorial calculation overwrites itself,
for example:
factorial of 5 result: 20 but it should be 120 (it overwrites itself until it reaches the last multiplier)
So I tried the following:
_result[x] = _numbersToProcess[x] *= y;
This is obviously the same as _numbersToProcess[x] = _numbersToProcess[x] * y;
But this gives a completley different result:
If we again input 5 then this will result in the output of -1899959296.
I know I can easily copy and paste from other submissions but I want to know why my method does not result in the correct output.
Here is the method in its entirety:
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate
int[] _numbersToProcess = new int[_numbers];// Array of inputs
int[] _result = new int[_numbers];
int i = 0;
while(i < _numbersToProcess.Length) {
_numbersToProcess[i] = int.Parse(Console.ReadLine());
i++;
}
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index
for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x
_result[x] = _numbersToProcess[x] *= y;// Multiply x by y then add to array
}
}
for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x
Console.WriteLine(_result[n]);// Write to console
}
Console.ReadLine();
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate
int[] _numbersToProcess = new int[_numbers];// Array of inputs
int[] _result = new int[_numbers];
int i = 0;
while(i < _numbersToProcess.Length) {
_numbersToProcess[i] = int.Parse(Console.ReadLine());
i++;
}
for (int x = 0; x < _numbersToProcess.Length; x++)
{// Loop throuigh Array by index
int fact = 1;
for (int y = 1; y <= _numbersToProcess[x]; y++)
{// Y is equal to less than index x
fact = fact*y;
}
_result[x] = fact;
}
for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x
Console.WriteLine(_result[n]);// Write to console
}
Console.ReadLine();
Problem is with your inner for loop. here, you are always, overriding result array.
i.e for y=5;
inner for loop executes for 5 times.
iteration -1 :
y=1,
_numbersToProcess[5]=5
_result[x]=5
iteration -2 :
y=2,
_numbersToProcess[5]=10
_result[x]=10
iteration -3 :
y=3,
_numbersToProcess[5]=30
_result[x]=30
.
.
.
.
.
thus it goes for 12 iteration as your _numbertoprocess[5] is changing and stops once it reaches less than 0 i.e -1899959296.
iteration 12:
_numbertoprocess[5] = -1899959296.
i.e you are changing numbertoprocess everytime in your inner for loop.
you can verify it by adding
Console.WriteLine(y);
Console.WriteLine(_numbersToProcess[x]);
Console.WriteLine(_result[x]);
in your inner for loop.
for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x
_result[x] = _numbersToProcess[x] *= y;// Multiply x by y then add to array
}
In loop condition y < _numberToProcess[x];. It compare between y and _numberToProcess[x] array value
I think you should edit loop condition to y < x
Be lucky.
Here i'm using a recursive function factorial
/* Factorial function*/
int factorial (int n)
{
return (n*factorial(n-1))
}
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate
int[] _numbersToProcess = new int[_numbers];// Array of inputs
int[] _result = new int[_numbers];
int i = 0;
while(i < _numbersToProcess.Length) {
_numbersToProcess[i] = int.Parse(Console.ReadLine());
i++;
}
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index
_result[x] = factorial(_result[x])// Multiply x by y then add to array
}
}
for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x
Console.WriteLine(_result[n]);// Write to console
}
Console.ReadLine();
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
Check this out maybe it will help...
#include <stdio.h>
#include <stdlib.h>
long f(int n) {
if (n==0) return 1;
else return n * f(n-1);
}
int main(int argc, char *argv[]) {
long *factorials;
int *inputs;
int n;
printf("Enter number n = ");
scanf("%d", &n);
factorials = (long *) malloc(n*sizeof(long));
inputs = (int *) malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
long k;
printf("Enter %d number = ", i + 1);
scanf("%ld", &k);
inputs[i] = k;
factorials[i] = f(k);
}
for (int i = 0; i < n; i++) {
printf("Factorial for %d = %ld\n", inputs[i], factorials[i]);
}
return 0;
}
For homework I have been asked to write a C# console program that has the user define a character and size, and the program will output an n*n/2 sized "V" where n is the width of the "V". The best I can get is either triangles or one diagonal line going left and one going right below it. Any suggestions would be greatly appreciated.
public static void Main (string[] args)
{
int maxWidth = 40;
Console.WriteLine ("Please enter your desired character");
string userChar = Console.ReadLine ();
Console.WriteLine ("Please enter your desired width");
int userWidth = Convert.ToInt32 (Console.ReadLine ());
for (int i = 0; i < userWidth; i++) {///opposite diagonal lines
for (int j = 0; j < i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}
for (int i = userWidth - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}
You are approaching the logic wrong by trying to calculate both sides separately.
As a hint, there are 2 spots on each row that are far away from each other at the top, and close to each other at the bottom. Each row, they both move toward each other. So what you want to do is figure out where they are at the top (say, 1 and 10), then each row, add one to the first and subtract one from the last, so they move closer to the middle. at the bottom, they will meet each other.
As another hint, it is possible to complete this task using one loop.
Try this:
int lines = userWidth / 2;
for (var i = 1; i < lines; i++)
Console.WriteLine(userChar.PadLeft(i) + userChar.PadLeft(2 * (lines - i)));
Console.WriteLine(userChar.PadLeft(lines));
I get this:
X X
X X
X X
X X
X X
X X
X X
X X
X X
X X
X
Thanks for all your input, this is the code i ended up coming up with.
public static void Main (string[] args)
{
int maxWidth = 40;
Console.WriteLine ("Please enter your desired character");
string userChar = Console.ReadLine ();
Console.WriteLine ("Please enter your desired width");
int userWidth = Convert.ToInt32 (Console.ReadLine ());
for (int i = 0; i < userWidth; i++) {
for (int j = 0; j < i; j++) {
Console.Write (" ");
}
Console.Write (userChar);
for (int j = userWidth-1; j > i; j--) {
Console.Write (" ");
}
for (int j = userWidth-1; j > 0+i ; j--) {
Console.Write (" ");
}
Console.Write (userChar);
Console.WriteLine ();
}
}
Basically I'm working on an assignment and I need to move the values from a normal array to a 2D array. I have to take input to set the length of the aray. The 2d array will be a square array, so say 3 is input my array needs to be 3x3. I've made the 1D array size n*n, with n being what the user inputs. I'm getting an index out of rage exception but I've gone through the code and written out what I think the values of everything should be at each stage and can't find out what's causing it.
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}
The line getting the exception is the last line in that method. I'm passing in a 2D array of size [n,n], a 1D array of size [n*n] and the just n. If you want to see any more of the code let me know.
The problem is in you lines:
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
arrayLength variable makes jump out of bounds on startArray. Note that both x and i are in range from 0 to arrayLength
If you know already dimensions of your 2d array, you can easily achieve this by (here I assume it 3x3):
var x = 0;
for (int i = 0; i < arrayLength; i++) {
if(i!= 0 && i % 3 == 0) ++x; // go to another row
twoDArray[i, x] = startArray[i];
}
I would start by adding the following to the start of your method. These document your assumptions about the dimensions of the arrays passed as arguments.
Debug.Assert(twoDArray.Rank == 2);
Debug.Assert(startArray.Rank == 1);
Debug.Assert(twoDArray.GetLength(0) == arrayLength);
Debug.Assert(twoDArray.GetLength(1) == arrayLength);
Debug.Assert(startArray.GetLength(0) == arrayLength * arrayLength);
maybe twoDArray issnt initilized correctly:
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
//twoDArray musst be initialized correctly, otherwise use:
twoDArray = new int[arrayLength][arrayLength];
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}