So I'm trying to loop values into a two-dimensional array using foreach. I know the code should look something like this.
int calc = 0;
int[,] userfields = new int[3,3];
foreach (int userinput in userfields)
{
Console.Write("Number {0}: ", calc);
calc++;
userfields[] = Convert.ToInt32(Console.ReadLine());
}
This is as far as I can get. I tried using
userfields[calc,0] = Convert.ToInt32(Console.ReadLine());
but apparently that doesn't work with two-dimensional arrays. I'm relatively new with C# and I'm trying to learn, so I appreciate all of the answers.
Thanks in advance!
It is a two dimensional array as the name suggests it has two dimensions. So you need to specify two index when you want to assign a value. Like:
// set second column of first row to value 2
userfield[0,1] = 2;
In this case probably you want a for loop:
for(int i = 0; i < userfield.GetLength(0); i++)
{
for(int j = 0; j < userfield.GetLength(1); j++)
{
//TODO: validate the user input before parsing the integer
userfields[i,j] = Convert.ToInt32(Console.ReadLine());
}
}
For more information have a look at:
Multidimensional Arrays (C# Programming Guide)
Related
I'm kind of new to C# and I'm trying to make a sudoku game. I'm using a for loop to loop through the column arrays and add a random number to the spots but I'm using Random and Next() so it allows the numbers to repeat. But because I can't have more than one of a number in each column (array) for it to function, how can I replace the repeated number with another number that isn't repeated? I don't know how to do this.
Also the columns are stored in other arrays that I've called rows just so that I can say Row1[0][2] to access position 3 in column 1 for example.
Here's the method & for loop I'm using to replace add the numbers to the arrays:
void populateColumns(int[][] arr) // goes through column arrays and replaces the numbers with random ones from Num()
{
int i;
int j = 0;
for (int l = 0; l <= 8; l++)
{
for (i = 0; i <= 8; i++)
{
arr[j][i] = Num();
int currentPos = arr[j][i];
Console.Write(currentPos);
}
j = l;
}
}
This question already has answers here:
Get property value from string using reflection
(24 answers)
string to variable name
(4 answers)
Closed 6 months ago.
I would be thankful if someone help me to resolve some task.
I need to create several variables using cycle "for".
I ask users how many numbers will they input, and declare it like variable "countVariables".
Next step, using cycle "for" I want to create new variables using counter cycle`s "for".
For example, name of created var must be like "num1", "num2", "num3" etc. I try do it using a code below.
I understand, that it isn't good solution, but I need to resolve task just using this way.
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
int tmp.name = Console.ReadLine();
}
You can't do it using variables as you've mentioned but you can use Arrays instead. After reading number of times to repeat, you can create an array based on that then access values by index:
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
var data = new string[countVariables];
for (int i = 1; i <= countVariables; i++)
{
string tmp = "num" + i;
data[i] = Console.ReadLine();
}
Later after the for loop you can access your values using data[0], data[1]... or use another for loop for looping over the values.
You can use a Dictionary for storing the data:
var data = new Dictionary<int, string>();
Console.WriteLine("Input count of numbers: ");
ushort.TryParse(Console.ReadLine(), out ushort countVariables);
for (int i = 1; i <= countVariables; i++)
{
var val = Console.ReadLine();
data.Add(i, val);
}
Write out number on index '4':
Console.WriteLine(data[4]);
so I'm new to coding and I've decided to learn C# with the whole Covid-19 going on, and I've run into a small problem if anybody can assist me.
I'm just writing a basic C# program to allow the user to input 5 numbers into an array and then display the array, but for some reason, I only display the number 5, not the whole array.
Please find my code: ( if anyone can make it easier for me please help me lol (: )
int[] numbers = new int[5];
int num = 0;
int i = 0;
Console.WriteLine("This porgram allows the user to input 5 numbers into an array");
Console.Write("--------------------------------------------------------------");
Console.WriteLine("\n");
for ( i = 0; i < numbers.Length; i ++)
{
Console.WriteLine("Please input number");
num = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < numbers.Length; i++)
{
Console.ReadLine();
Console.WriteLine("Your array is: " , numbers );
}
Console.WriteLine();
// any help will be appreciated!
Two problems:
1) You haven't put the number coming in. After
num = Convert.ToInt32(Console.ReadLine());
put
numbers[i] = num;
Though in fact num is superfluous, so you could just have
numbers[i]= Convert.ToInt32(Console.ReadLine());
2) In the second loop you need to display the specific array element:
Console.WriteLine("Your array item is: " , numbers[i] );
Also, not sure what the ReadLine() in the second loop is for - just means the users has to hit return to see each number.
It's worth mentioning a few other issues in the code:
Variables should be declared as close as possible to where they are used. this i should be declared separately for each for loop - for(int i = 0; ... and num should be declared inside the loop (though as mentioned, it's redundant).
Be clear on the difference between Console.Write() and Console.WriteLine(). WriteLine() simply adds a \n to whatever is displayed. Thus it would be clearer (for the same output to have:
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine();
here is code:
it is the basic syntax of displaying an array.
public class Work
{
public static void Main()
{
int[] arr = new int[5];
int i;
Console.Write("\nRead & Print elements of an array:\n");
Console.Write("-----------------------------------------\n");
Console.Write("Input 5 elements in the array :\n");
for(i=0; i<5; i++)
{
Console.Write("element - {0} : ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for(i=0; i<5; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
}
}
I'm very, very new to C# and would like to ask a maybe very stupid question, the first language I learned was Java, in which I could do this:
int[][] array = new int[1600][900];
array[600][400] = 10;
for(int x = 0; x < 1600; x++)
{
for(int y = 0; y < 900; y++)
{
int something = colour[x][y];
}
}
Now I've searched the web for quite a while, but I've got no idea about how to do this in C#
EDIT:
Thanks for the help everyone, it's been usefull :)
Just use a comma :
int[,] array = new int[1600,900];
array[600,400] = 10;
//...
You can do it in a very similar way in C#:
int[,] array = new int[1600,900];
array[600,400] = 10;
for(int x = 0; x < 1600; x++)
{
for(int y = 0; y < 900; y++)
{
int something = colour[x,y];
}
}
I'm not sure if I understand what's the purpose of the code in the double for cycle. I suppose those three pieces of code don't have anything in common.
int [,] array = new int[1600,900];
To add some color to the answers:
In .NET, an int[][] is a jagged array, or an array of arrays. While this may be a perfectly good structure for you to use, it has the addded overhead that each array must be initialized individually. So your initialization would be:
int[][] array = new int[1600][];
for(int i=0;i<array.Length;i++)
array[i] = new int[900];
now you can access an individual value by using
array[600][400] = 10;
One benefit of using jagged arrays is that the "interior" array can be different sizes. If you don;t need that flexibility than using a rectangular ([,]) array may be a better option for you.
i can't find any mistakes in my code.
here i'm trying to pick all numbers from the string:
(just to simplify the example,, i want to pick numbers that will satisfy some condition)
i use Queue cause i don't want to deal with array's indexes.
Console.Write("enter string: ");
string s = Console.ReadLine();
char[] array = s.ToCharArray();
Queue<char> q = new Queue<char>();
for (int i = 0; i < array.Length; i++)
{
q.Enqueue(array[i]);
}
char[] new_array = new char[q.Count];
for (int i = 0; i < q.Count; i++)
{
new_array[i] = q.Dequeue();
}
Console.WriteLine(new String(new_array));
Input string: 123456
And the output is a little weird:
123
another input: 123
output: 12
of course i made some mistake) but everything seems to be OK
Thank YOU in advance
The problem is the second loop:
for (int i = 0; i < q.Count; i++)
{
new_array[i] = q.Dequeue();
}
As q.Count decrements on every loop iteration, and i increases on every interation, you get only half of the elements.
try something like:
for (int i = 0; q.Count > 0; i++)
{
new_array[i] = q.Dequeue();
}
also consider: Queue.toArray
I would suggest using List<char> instead of Queue<char> and char[]. There's nothing here that particularly needs a queue, and it would avoid the problem that Rudolf pointed out, and a List is much easier to work with than an array. You can also use foreach instead of a for loop, and avoid the intermediate step.
Console.Write("enter string: ");
string s = Console.ReadLine();
List<char> new_array = new List<char>();
foreach(char c in s.ToCharArray())
{
new_array.Add(c);
}
Console.WriteLine(new String(new_array.ToArray()));
As the reason for your error is already stated,you can replace your two loops with just two statements
//A version of Queue constructor accepts IEnumerable object.
//you can directly pass the string to the queue constructor.
Queue<char> Que = new Queue<char>("123456");
//Copies the array and the position is preserved
var new_arr= Que.ToArray();
According to MSDN:
Removes and returns the object at the beginning of the Queue.
As you use Dequeue(), the q.Count value changes in each iteration.
So rather than using q.Count in this loop;
for (int i = 0; i < q.Count; i++)
use
int queueSize = q.Count;
for (int i = 0; i < queueSize; i++)
This will keep your looping limit as a constant number rather than calculating it in each iteration to find a different value because of using Dequeue().