Is it possible to loop over incremental variable names? - c#

Supposing I have some variables with names : daywinner1 , daywinner2 , daywinner3...
How can I loop over these variables by increasing their incremental components ???
I've tried but I can't achieve it
My code :
string[][] olympia =
{
new string[]{"a","b","c" },
new string[]{"d","e"},
new string[]{"f","g","h","j","k"}
};
int daywinner1 = int.Parse(Console.ReadLine());
int daywinner2 = int.Parse(Console.ReadLine());
int daywinner3 = int.Parse(Console.ReadLine());
for (int i = 0; i < olympia.Length; i++)
{
Console.WriteLine(olympia[][]);
}

It is not possible to iterate over variable names in this way, as each variable is a discrete, separate box.
There is no relationship between "daywinner1", "daywinner2" and "daywinner3" in the code.
You could have named them "distance", "height" and "width", or "red, blue, green". There is no way for the compiler to know what their relationship with each other is, or what order they should be in.
However, you could instead create an array, where each element contains the value you want in an explicit order.
For example:
int[] daywinners = new int[3];
daywinners[0] = int.Parse(Console.ReadLine());
daywinners[1] = int.Parse(Console.ReadLine());
daywinners[2] = int.Parse(Console.ReadLine());
You can then iterate over the array of daywinners like so:
foreach (var daywinner in daywinners) {
}
I recommend learning more about data structures.

Related

Convert string vol to variable name [duplicate]

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]);

How to declare and initialize multiple variables (with different names) within a for loop without using arrays?

I'm trying to perform the job that an array is supposed to do, but without actually using one. I was wondering if this was possible, and if it is, how?
I have to initialize different variables, for example:
int value1 = 0;
int value2 = 0;
int value3 = 0;
int valueN = 0;
I want to receive a value from the user that determinate what is the for loop going to last.
Example: User --> 4
Then I can declare 4 variables and work with them.
for (i = 1; i <= 4; i++) {
Console.Write("Insert a number: ");
int value(i) = int.Parse(Console.ReadLine());
}
I expect to have 4 variables called equally, but with the only one difference that each one has a different number added at the end of the name.
// value1 = 0;
// value2 = 0;
// value3 = 0;
// valueN = 0;
You cannot create dynamically named variables in C# (and I am with those who are wondering why you want to do that). If you don't want to use an array, consider a Dictionary -- it would perform better than an array in some circumstances.
Dictionary<string, int> values = new Dictionary<string, int>();
for (int i = 1; i <= 4; i++)
{
values.Add("value" + i, 0);
}
value["value1"]; //retrieve from dictionary

removing values in List<> at index position without decreasing the list size

I'm trying to create an array of structs and add/remove items from it. Tried to transform it into a List, delete the item at the given index WITH the position itself.
If I use the RemoveAt(index) method for the list, it decreases my list size with one position. The final array should have the same size as in the beginning.
struct Cities
{
public string name;
public int inhabitansNumber;
}
Cities[] cities = new Cities[500]; // the struct array holding the cities
int i = 0;
//insert items into the array:
if (cities[i].Equals(default(Cities)))
{
Console.WriteLine("Please enter the city name:");
cities[i].name = Console.ReadLine();
Console.WriteLine("Please enter population:");
cities[i].inhabitansNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Values added successfuly!");
i++;
}
//remove values from the array:
Console.WriteLine("number of element BEFORE deleting in array {0}", cities.Count());
Console.WriteLine("please enter the position of the element that you want to delete:");
int numToRemove = Convert.ToInt32(Console.ReadLine());
List<Cities> citiesToList = cities.ToList();
citiesToList.RemoveAt(numToRemove);
cities = citiesToList.ToArray();
Console.WriteLine("number of element AFTER deleting in array {0}", cities.Count());
As already mentioned, it would be the best to set the item on the specified index to null instead of completely removing the item.
myArray[itemIndex] = null;
Because you're using structs this isn't possible. But maybe you could declare the array as nullable. So just change
Cities[] cities = new Cities[500];
to the following
Cities?[] cities = new Cities?[500];
Declare your array/list with the element type as nullable:
Cities?[] cities = new Cities?[500];
List<Cities?> citiesToList = cities.ToList();
If you don't want to make the array nullable, you can change only the list by:
List<Cities?> citiesToList = cities.Cast<Cities?>.ToList();
You can then use the list indexer and set element to null:
citiesToList[numToRemove] = null;
Found a solution using only a for loop. Hope it will help you also :) :
//removing item from array without deleting the position
Console.WriteLine("number of element BEFORE deleting in array {0}", cities.Count());
Console.WriteLine("please enter the position of the element that you want to delete:");
int numToRemove = Convert.ToInt32(Console.ReadLine());
for (int j = 0; j < cities.Length-1; j++)
{
if (j >= numToRemove)
{
cities[j] = cities[j + 1];
}
}
Console.WriteLine("number of element AFTER deleting in array {0}", cities.Count());

Looping values into a two-dimensional array with a foreach loop?

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)

Defining Dynamic Array

How can I define a dynamic array in C#?
C# doesn't provide dynamic arrays. Instead, it offers List class which works the same way.
To use lists, write at the top of your file:
using System.Collections.Generic;
And where you want to make use of a list, write (example for strings):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Take a look at Array.Resize if you need to resize an array.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Alternatively you could use the List class as others have mentioned. Make sure you specify an initial size if you know it ahead of time to keep the list from having to resize itself underneath. See the remarks section of the initial size link.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
If you need the array from the List, you can use the ToArray() function on the list.
string[] dinos = dinosaurs.ToArray();
C# does provide dynamic arrays and dynamic array manipulation. The base of an array is dynamic and can be modified with a variable. You can find the array tutorial here (https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx). I have also included code that demonstrates an empty set array and a dynamic array that can be resized at run time.
class Program
{
static void Main(string[] args)
{
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x);
{
int[] dynamicArray1 = { };//empty array
int[] numbers;//another way to declare a variable array as all arrays start as variable size
numbers = new int[x];//setting this array to an unknown variable (will be user input)
for (int tmpInt = 0; tmpInt < x; tmpInt++)//build up the first variable array (numbers)
{
numbers[tmpInt] = tmpInt;
}
Array.Resize(ref numbers,y);// resize to variable input
dynamicArray1 = numbers;//set the empty set array to the numbers array size
for (int z = 0; z < y; z++)//print to the new resize
{
Console.WriteLine(numbers[z].ToString());//print the numbers value
Console.WriteLine(dynamicArray1[z].ToString());//print the empty set value
}
}
Console.Write("Dynamic Arrays ");
var name = Console.ReadLine();
}
}
Actually you can have Dynamic Arrays in C# it's very simple.
keep in mind that the response to your question above is also correct you could declare a
List Generic
The way to Create a Dynamic Array would be to declare your Array for example
string[] dynamicArry1 = { };//notice I did not declare a size for the array
List<String> tmpList = new List<string>();
int i = 1;
for(int tmpInt = 0; tmpInt < 5; tmpInt++)
{
tmpList.Add("Testing, 1.0." + tmpInt + ", 200, 3.4" + tmpInt +"," + DateTime.Now.ToShortDateString());
//dynamicArry1[tmpInt] = new string[] { tmpList[tmpInt].ToCharArray() };
}
dynamicArry1 = tmpList.ToArray();
how about ArrayList ?
If I'm not wrong ArrayList is an implementation of dynamic arrays
Example of Defining Dynamic Array in C#:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
like so
int nSize = 17;
int[] arrn = new int[nSize];
nSize++;
arrn = new int[nSize];

Categories