C# sequence unhandled exception [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
//1. add 10 numbers in sequence , print only steam numbers.
int[] seq= new int[10];
int n = 0;
int[] seq2= new int[n];
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2[n] = seq[i];
n++;
}
}
for (int i = 0; i < seq2.Length; i++)
{
Console.WriteLine(seq2[i]);
}
There is something wrong with sequence2 and the program isn't telling anything about it , can someone help ? it's not about the task i did it other way but i just want to understand what did i do wrong here .

You declared Seq2 array with length 0 in below shown part of your code. So it will always fail with Index was outside the bounds of the array exception when you do this seq2[n] = seq[i];.
int n = 0;
int[] seq2= new int[n];
Declare Seq2 as list instead. Like this..
var seq2= new List<int>();
and then do this..
seq2.Add(seq[i]);
Your final code will look like this..
int[] seq= new int[10];
var seq2= new List<int>();
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
}
}
for (int i = 0; i < seq2.Count(); i++)
{
Console.WriteLine(seq2[i]);
}

Since you don't know the number of elements in the second array, and C# doesn't have dynamic arrays (I think), just use a list instead:
int[] seq= new int[10];
int n = 0;
List<int> seq2= new List<int>;
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
n++;
}
}
for (int i = 0; i < seq2.Length - 1; i++)
{
Console.WriteLine(seq2[i]);
}

Are the arrays obligatory?
int n = 10;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Add number ");
int a = int.Parse(Console.ReadLine());
if (a%2==0)
{
Console.WriteLine(a);
}
}
If they are, you will need a List because you don't know how many of them will be even.
Edit: just read the bottom line..

Related

c# Code : System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' please see my code [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
These codes aren't running.When inside the nested loop I'm trying to assign integer value on totalMembers[j] array index , the compiler throws mentioned exeption.please help so that this program can run.
int totalHours = 0, memArraySize = 0;
int[] totalMembers = new int[memArraySize];
int[] memHours = new int[memArraySize];
for (int i = 0; i < 2; i++)
{
var stringNumbers = Console.ReadLine();
var numbers = stringNumbers.Split(' ');
int.TryParse(numbers[0], out totalHours);
int.TryParse(numbers[1], out memArraySize);
for (int j = 0; j < 2; j++)
{
totalMembers[j] = Convert.ToInt32(Console.ReadLine());
memHours[i] = memHours[i] + totalMembers[j];
}
}
int totalHours, memArraySize;
int[] totalMembers;
int[] memHours;
for (int i = 0; i < 2; i++)
{
var stringNumbers = Console.ReadLine();
var numbers = stringNumbers.Split(' ');
int.TryParse(numbers[0], out totalHours);
int.TryParse(numbers[1], out memArraySize);
totalMembers = new int[memArraySize];
memHours = new int[memArraySize];
for (int j = 0; j < 2; j++)
{
totalMembers[j] = Convert.ToInt32(Console.ReadLine());
memHours[i] = memHours[i] + totalMembers[j];
}
}
so that the arrays totalMembers and memHours can contain values.

How can I fill array with unique random numbers with for-loop&if-statement?

I'm trying to fill one dimensional array with random BUT unique numbers (No single number should be same). As I guess I have a logical error in second for loop, but can't get it right.
P.S I'm not looking for a more "complex" solution - all I know at is this time is while,for,if.
P.P.S I know that it's a really beginner's problem and feel sorry for this kind of question.
int[] x = new int[10];
for (int i = 0; i < x.Length; i++)
{
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) break;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i);
}
Here is a solution with your code.
int[] x = new int[10];
for (int i = 0; i < x.Length;)
{
bool stop = false;
x[i] = r.Next(9);
for (int j = 0; j <i; j++)
{
if (x[i] == x[j]) {
stop = true;
break;
}
}
if (!stop)
i++;
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
A simple trace of the posted code reveals some of the issues. To be specific, on the line…
if (x[i] == x[j]) break;
if the random number is “already” in the array, then simply breaking out of the j loop is going to SKIP the current i value into the x array. This means that whenever a duplicate is found, x[i] is going to be 0 (zero) the default value, then skipped.
The outer i loop is obviously looping through the x int array, this is pretty clear and looks ok. However, the second inner loop can’t really be a for loop… and here’s why… basically you need to find a random int, then loop through the existing ints to see if it already exists. Given this, in theory you could grab the same random number “many” times over before getting a unique one. Therefore, in this scenario… you really have NO idea how many times you will loop around before you find this unique number.
With that said, it may help to “break” your problem down. I am guessing a “method” that returns a “unique” int compared to the existing ints in the x array, may come in handy. Create an endless while loop, inside this loop, we would grab a random number, then loop through the “existing” ints. If the random number is not a duplicate, then we can simply return this value. This is all this method does and it may look something like below.
private static int GetNextInt(Random r, int[] x, int numberOfRandsFound) {
int currentRand;
bool itemAlreadyExist = false;
while (true) {
currentRand = r.Next(RandomNumberSize);
itemAlreadyExist = false;
for (int i = 0; i < numberOfRandsFound; i++) {
if (x[i] == currentRand) {
itemAlreadyExist = true;
break;
}
}
if (!itemAlreadyExist) {
return currentRand;
}
}
}
NOTE: Here would be a good time to describe a possible endless loop in this code…
Currently, the random numbers and the size of the array are the same, however, if the array size is “larger” than the random number spread, then the code above will NEVER exit. Example, if the current x array is set to size 11 and the random numbers is left at 10, then you will never be able to set the x[10] item since ALL possible random numbers are already used. I hope that makes sense.
Once we have the method above… the rest should be fairly straight forward.
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
int numberOfRandsFound = 0;
int[] ArrayOfInts = new int[DataSize];
int currentRand;
for (int i = 0; i < ArrayOfInts.Length; i++) {
currentRand = GetNextInt(random, ArrayOfInts, numberOfRandsFound);
ArrayOfInts[i] = currentRand;
numberOfRandsFound++;
}
for (int i = 0; i < ArrayOfInts.Length; i++) {
Console.WriteLine(ArrayOfInts[i]);
}
Console.ReadKey();
}
Lastly as other have mentioned, this is much easier with a List<int>…
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
List<int> listOfInts = new List<int>();
bool stillWorking = true;
int currentRand;
while (stillWorking) {
currentRand = random.Next(RandomNumberSize);
if (!listOfInts.Contains(currentRand)) {
listOfInts.Add(currentRand);
if (listOfInts.Count == DataSize)
stillWorking = false;
}
}
for (int i = 0; i < listOfInts.Count; i++) {
Console.WriteLine(i + " - " + listOfInts[i]);
}
Console.ReadKey();
}
Hope this helps ;-)
The typical solution is to generate the entire potential set in sequence (in this case an array with values from 0 to 9). Then shuffle the sequence.
private static Random rng = new Random();
public static void Shuffle(int[] items)
{
int n = list.Length;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
int temp = items[k];
items[k] = items[n];
items[n] = temp;
}
}
static void Main(string[] args)
{
int[] x = new int[10];
for(int i = 0; i<x.Length; i++)
{
x[i] = i;
}
Shuffle(x);
for(int i = 0; i < x.Length; i++)
{
Console.WritLine(x[i]);
}
}
//alternate version of Main()
static void Main(string[] args)
{
var x = Enumerable.Range(0,10).ToArray();
Shuffle(x);
Console.WriteLine(String.Join("\n", x));
}
You can simply do this:
private void AddUniqueNumber()
{
Random r = new Random();
List<int> uniqueList = new List<int>();
int num = 0, count = 10;
for (int i = 0; i < count; i++)
{
num = r.Next(count);
if (!uniqueList.Contains(num))
uniqueList.Add(num);
}
}
Or:
int[] x = new int[10];
Random r1 = new Random();
int num = 0;
for (int i = 0; i < x.Length; i++)
{
num = r1.Next(10);
x[num] = num;
}

fill array with random but unique numbers in C# [duplicate]

This question already has answers here:
Generate N random and unique numbers within a range
(7 answers)
Best way to randomize an array with .NET
(19 answers)
Closed 6 years ago.
Okay I know there are few posts like this but I need to use only loops (for,do,while) and if, else to fill array with random but unique numbers so how shall i edit this code
int[] x = new int[10];
Random r = new Random();
int i;
for (i = 0; i < x.Length; i++) {
x[i] = r.Next(10);
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
You could check if the newly generated number already exists in the array, if not then add it to the array, if yes then generate a new one.
For examle:
class Program
{
static void Main(string[] args)
{
int[] x = new int[10];
Random r = new Random();
int i;
for (i = 0; i < x.Length; i++)
{
var next = 0;
while (true)
{
next = r.Next(10);
if (!Contains(x, next)) break;
}
x[i] = next;
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
Console.ReadLine();
}
static bool Contains(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == value) return true;
}
return false;
}
}
Without checking that generated number is already presented in array you can't to solve this task.
So you must generate new number and before inserting it into array check for uniq.

Bubblesorting Need answers [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 8 years ago.
I need some help with this code. I'm playing with this for a couple of hours and got nothing. So I'm asking for help from you guys.
The Array[b] was always returns out of bounds exception. I don't know why.
{
int[] Array = new int[6];
Array[0] = c;
Array[1] = d;
Array[2] = e;
Array[3] = f;
Array[4] = g;
int a = 0;
int b = 1;
int temp = 0;
for (int counter = 0; counter < Array.Length; counter++)
{
for (int counter2 = 0; counter2 < Array.Length; counter2++)
{
if (Array[a] > Array[b])
{
Console.WriteLine("{0} is Greater Than {1}, Swapping ({0},{1})", Array[a], Array[b]);
temp = Array[a];
Array[a] = Array[b];
Array[b] = temp;
Console.WriteLine("");
}
else
{
Console.WriteLine("{0} is Less Than {1}, Retain Value Position", Array[a], Array[b]);
Console.WriteLine("");
}
a += 1;
b += 1;
}
a = 0;
b = 0;
}
for (int counter = 0; counter < Array.Length; counter++)
{
Console.Write(Array[counter] + " ");
}
Console.WriteLine("Final Position");
return a;
}
Thanks, this is my code i hope any one of you can help me.
You are comparing one element to the next, so if you've arrived at the last element, there is no "next" element and you're out of bounds.
Change the inner loop to only go until Length - 1 to prevent this:
for (int counter = 0; counter < Array.Length; counter++)
{
for (int counter2 = 0; counter2 < Array.Length - 1; counter2++)
// ...
}
before incrementing b, check if you are in the last index of the array, because you start b at 1 instead of 0, so it will go out of bounds if you enter the block while looping over the last array index.

C# searching array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a random array and I must search how many times the integer number is in the array. This is what I have already. How would you search the resulting array?
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
int[] array = new int[number];
Random rnd = new Random();
for ( int i = 0; i < array.Length; i++)
{
array[i] = rnd.Next(0 , number);
}
foreach (int i in array)
{
System.Console.Write(" {0}",i);
}
Console.ReadKey();
The other answers rely on LINQ, here is the code to do so with plain C#
int count = 0;
foreach (int i in array)
{
if (i == number)
count = count + 1;
}
Note that in your existing code this will always produce 0 because the upper bound of Random.Next() is exclusive. You should change your code to something like this where the number entered is not linked to the array you generate:
int array_size = 1000;
int max_number = 100;
int[] array = new int[array_size];
Random rnd = new Random();
for (int i = 0; i < array.Length; i++)
array[i] = rnd.Next(0, max_number);
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
foreach (int i in array)
System.Console.Write("{0} ", i);
int count = 0;
foreach (int i in array)
if (i == number)
count = count + 1;
Console.WriteLine("Number {0} was found {1} times in the array", number, count);
Console.ReadKey();
foreach(var g in array.GroupBy(x=>x))
{
Console.WriteLine("{0} Count:{1}",g.Key,g.Count())
}

Categories