I basically need to store an array of any amount of contents to an integer but then I have to echo it all out after.
I am getting an indexoutofrange error.
for (int index = 0; index < userArray; index++, userArray--)
{
Console.WriteLine("Number " + userArray + " Value is:");
userArrayinputed[userArray] = int.Parse(Console.ReadLine());
}
All the Code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is the Size of the Array?");
string inputArray = Console.ReadLine();
int userArray = Convert.ToInt32(inputArray);
int[] userArrayinputed = new int[userArray];
for (int index = 0; index < userArray; index++, userArray--)
{
Console.WriteLine("Number " + userArray + " Value is:");
userArrayinputed[userArray] = int.Parse(Console.ReadLine());
}
for (int index = userArray; index > 0; index--, userArray--)
{
Console.WriteLine(userArrayinputed);
Console.ReadLine();
}
Correct Code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is the Size of the Array?");
string inputArray = Console.ReadLine();
int userArray = Convert.ToInt32(inputArray);
int maxArray = userArray;
int[] userArrayinputed = new int[userArray];
for (int index = 0; index < userArray; index++)
{
Console.WriteLine("Number " + index + " Value is:");
userArrayinputed[index] = int.Parse(Console.ReadLine());
}
for (int index = 0; index < userArray; index++)
{
Console.WriteLine(userArrayinputed[index]);
Console.ReadLine();
}
So, array's are zero based for indexing, that means if you want an array of 10 then the indexers are going to be 0-9.
so when you go up an array (0-9) you want the top of a for loop to be <(less than the array length) when you are going down the array (9-0) you want the lower bound to be >= 0 (less than or equal to the bottom of the array) otherwise you will start out trying to access at 10 (the array length) and get an OutOfRangeException.
for example:
for (int i = 0; i < myArray.Length -1; i++)
{ ... }
and
for (int i = myArray.Length - 1; i >= 0; i--)
{ ... }
and when you are displaying the index in a for loop you will want to display the index and not the array length.
Also something of note - you were deducting the value of the userArray variable in two separate for loops, which does not reset it when it leaves the loop, so at the end of the method, the userArray variable would have been at -(2*userArray) instead of what I think you were going for which was the index/array length.
So it would look something like this
static void Main(string[] args)
{
Console.WriteLine("What is the Size of the Array?");
string inputArray = Console.ReadLine();
int userArray = Convert.ToInt32(inputArray);
int[] userArrayinputed = new int[userArray];
for (int index = 0; index < userArray; index++)
{
Console.WriteLine("Number " + index + " Value is:");
//note you will get an error here if you try and parse something that isn't an interger
userArrayinputed[index] = int.Parse(Console.ReadLine());
}
for (int index = userArray -1; index >= 0; index--)
{
Console.WriteLine(userArrayinputed[index]);
}
Console.ReadLine();
}
index of array is starting from 0 to (userArray -1)
string inputArray = Console.ReadLine();
int userArray = Convert.ToInt32(inputArray);
int[] userArrayinputed = new int[userArray];
for (int index = 0; index < userArray; index++)
{
Console.WriteLine("Number " + index+ " Value is:");
userArrayinputed[index] = int.Parse(Console.ReadLine());
}
for (int index = 0; index < userArray; index++)
{
Console.WriteLine(userArrayinputed[index]);
Console.ReadLine();
}
Replace
userArrayinputed[userArray]
with
userArrayinputed[index]
and remove the userArray-- from your for loops. Use the index instead to display the current number:
for (int index = 0; index < userArray; index++)
{
Console.WriteLine("Number " + index + " Value is:");
...
Initially, userArrayinputed[userArray] accesses the last index which is userarray-1
since userarray is the length of the array
here is the fix,
for (int index = 0; index < userArray; index++, userArray--)
{
Console.WriteLine("Number " + userArray + " Value is:");
userArrayinputed[userArray-1] = int.Parse(Console.ReadLine());
}
Cause
Your for() loop is first evaluated with userArray == userArrayinputed.Length, so
userArrayinputed[userArray] tries to access the (N + 1)th element of the array which leads to the IndexOutOfRangeException.
Array indexing starts with 0, remember? So an array with say, 3 items
int[] arr = new int[3]
the array has the items arr[0], arr[1] and arr[2] but no arr[3] which would be the 4th item.
Solution
Just use userArrayinputed[index] and remove the userArray-- part in the for() statement.
If you still want to enter the numbers in reverse order you can count down from userArray-1:
for (int index = userArray - 1; index >= 0; index--)
{
Console.WriteLine("Number " + index + " Value is:");
userArrayinputed[index] = int.Parse(Console.ReadLine());
}
To display the numbers, you should WriteLine the array elements, not the array:
for (int index = userArray - 1; index >= 0; index--)
{
Console.WriteLine(userArrayinputed[index]);
Console.ReadLine();
}
Related
i want to write a console app that get int value from user and put them in a array and show sum of the numbers and min and max of them and then print them in the console in order
i write until this point of project but have some bugs...
Console.WriteLine("\n Please Enter the Number of your Numbers: \n");
int k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Please Enter Your Numbers:");
int[] myArray = new int[k];
int sum = 0;
//INPUT
for (int i = 0; i < k; i++)
{
myArray[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Number [" + (i+1) + "]: " + myArray[i] + " and Next:");
}
//DELETE DUPLICATE ELEMENTS
int[] newArray = myArray.Distinct().ToArray();
//SORT
Array.Sort(newArray);
Console.WriteLine("\n Your Sorted Numbers Without Duplicated ones: ");
foreach (int i in newArray)
{
Console.Write(" | " + i);
}
Console.Write(" |");
i think you are trying to make a program like this:
int i,n;
int[] a = new int[100];
Console.WriteLine("element numbers :");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("please entre your numbers : ", n);
for (i = 0; i < n; i++)
{Console.WriteLine($"element i");
a[i] = Convert.ToInt32(Console.ReadLine());}
int sum = 0;
for (i = 0; i < n; i++)
{sum += a[i];}
Console.WriteLine("sum is : {0}", sum);
int max = a[0];
int min = a[0];
for (i = 1; i < n; i++)
{if (a[i] > max)
{max = a[i];}
if (a[i] < min)
{min = a[i];}}
Console.WriteLine("max is : " + max);
Console.WriteLine("min is : " + min);
Console.WriteLine("element numbers are: ");
for (i = 0; i < n; i++)
{Console.WriteLine(a[i]);}
I am having a hard time with a program I need to write. The requirements are that the user enters in the size of the Array. Then they enter the elements of the array after this the program needs to display the values entered then how many times each value occurs. While everything seems to work except its not display the "occurs" part properly. Lets say "1 1 2 3 4" is entered (Array size being 5) It prints
1 occurs 1 time.
1 occurs 1 time.
2 occurs 1 time.
3 occurs 1 time.
4 occurs 2 times.
this isn't right because 1 occured 2 times and 4 is only 1 time. Please Help...
static void Main(string[] args)
{
int[] arr = new int[30];
int size,
count=0,
count1=0,
count2=0;
Console.Write("Enter Size of the Array: ");
size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i=0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("Values Entered: \n");
for (int i = 0; i < size; i++)
{
Console.WriteLine(arr[i]);
if (arr[i] <= 10)
count++;
else
count1++;
}
for(int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j])
count2++;
else
count2 = 1;
}
Console.WriteLine(arr[i] + " Occurs " + count2 + " Times.");
}
Console.WriteLine("The number of valid entries are: " + count + "\nThe number of invalid entries are: " + count1);
Console.ReadKey();
}
if you can use Linq, this is easy job:
After
Console.Write("Values Entered: \n");
add
var grouped = arr.GroupBy(x => x);
foreach (var group in grouped)
{
Console.WriteLine("number {0} occurs {1} times", group.Key, group.Count());
}
EDIT
Since OP isn't allowed to use Linq, here's array-only solution. Much more code than that dictionary approach, but with arrays only.
Console.Write("Values Entered: \n");
//an array to hold numbers that are already processed/counted. Inital length is as same as original array's
int[] doneNumbers = new int[arr.Length];
//counter for processed numbers
int doneCount = 0;
//first loop
foreach (var element in arr)
{
//flag to skip already processed number
bool skip = false;
//check if current number is already in "done" array
foreach (int i in doneNumbers)
{
//it is!
if (i == element)
{
//set skip flag
skip = true;
break;
}
}
//this number is already processed, exit loop to go to next one
if (skip)
continue;
//it hasn't been processed yes, so go through another loop to count occurrences
int occursCounter = 0;
foreach (var element2 in arr)
{
if (element2 == element)
occursCounter++;
}
//number is processed, add it to "done" list and increase "done" counter
doneNumbers[doneCount] = element;
doneCount++;
Console.WriteLine("number {0} occurs {1} times", element, occursCounter);
}
You can simply use dictionary:
static void Main(string[] args)
{
var dic = new Dictionary<int, int>();
Console.Write("Enter Size of the Array: ");
int size = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the elements of an Array: ");
for (int i = 0; i < size; i++)
{
int val = Convert.ToInt32(Console.ReadLine());
int current;
if (dic.TryGetValue(i, out current))
{
dic[val] = current + 1;
}
else
{
dic.Add(val, 1);
}
}
foreach (int key in dic.Keys)
{
Console.WriteLine(key + " Occurs " + dic[key] + " Times.");
}
Console.Read();
}
The problem is that you're resetting count2 to 1 any time you find a mismatch.
What you should do instead is set count2 to 0 in the outer loop (so it basically resets once for each item), and then let the inner loop count all the instances of that number:
// For each item 'i' in the array, count how many other items 'j' are the same
for (int i = 0; i < size; i++)
{
count2 = 0; // processing a new item, so reset count2 to 0
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j]) count2++;
}
Console.WriteLine(arr[i] + " occurs " + count2 + " times.");
}
I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}
I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}
So the code for the function (Named InsertMark) is below. How would you call this function to enter the marks for say 10 people into an array called iMarks?
static void InsertMark(int [] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
Thanks.
Just move the line piMarkArray[piStuNum] = iMark; inside while loop, use index, and exit the loop if index is not less than array length.
int index=0;
while ((iMark < 0 || iMark > 100) && index < piMarkArray.Length) // exit the loop array is full
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
piMarkArray[index++] = iMark; // Here marks are set
}
//update array element with this mark
Here you create array which will hold 10 marks and fill it with your method in a loop:
int[] marks = new int[10];
for(int i = 0; i < marks.Length; i++)
InsertMark(marks, i);
In main function you could have a code:
int iMarks[10];
for(int i = 0; i <10; i++ )
InsertMark(iMarks, i)
are you looking for something like this?
for(int i=0; i<10; i++)
{
InsertMark(iMarks, i);
}
You need to declare an array of size 10: int[] iMarks = new int[10], then in a for loop pass the array and the counter value through to the function.
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Here is the full class/ working example:
static void Main(string[] args)
{
int[] iMarks = new int[10];
for(int x = 0; x < 10; x++)
InsertMark(iMarks, x);
Console.Read();
}
static void InsertMark(int[] piMarkArray, int piStuNum)
{
int iMark;
Console.Write("Enter mark for student " + piStuNum + ": ");
iMark = Convert.ToInt32(Console.ReadLine());
while(iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
//update array element with this mark
piMarkArray[piStuNum] = iMark;
}
}
There are always multiple ways to code anything, and this is no exception. What I'm putting here is one example of idiomatic C# to do this. There are at least two variants I can think of which would be better, but this keeps the closest to the original idea.
First, a basic Student class:
class Student
{
public int ID;
public int Mark;
}
Then, a function to prompt for the mark
int GetMark(int studentID)
{
Console.Write("Enter mark for student " + studentID + ": ");
int mark = Convert.ToInt32(Console.ReadLine());
while (iMark < 0 || iMark > 100)
{
Console.Write("Not a percentage. Enter again: ");
iMark = Convert.ToInt32(Console.ReadLine());
}
return mark;
}
Finally, from your main program, you have a list or array of Student objects called AllStudents and you do:
foreach (Student student in AllStudents)
{
student.Mark = GetMark(student.ID);
}
Alternatively, if you aren't using classes, your loop could be:
int[] marks = new int[10]; // Or whatever size it needs to be.
for (int i = 0; i < marks.Length; i++)
{
marks[i] = GetMark(i);
}