C# foreach loop take values from outer loop to inner loop - c#

I have the below code.
int[] a = new int[] { 8, 9 };
for(int i=0;i<n;i++)
{
print i;
int z;
//during first iteration
z=8;
during second iteration
z=9;
}
Output should be something like this.
during first iteration i=0 and z=8
during second iteration i=1 and z=9
array a contains 2 elements. N and number of elements in array a will be always same. next my for loop will execute. during first iteration want z value should be 8(first element of array ) and second iteration my z value should be 9. I want to map 1st element of integer array to first iteration of for loop and so on.

try
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
int z = a[i]; // this line will get value from a one by one, 0, 1, 2, 3 and so on...
}
Edit 1 -
After seeing the comments on the other answer, the array 'a' turns out is a dynamic array which have size n (which is 2)
the revised edition:
int n = 2;
int[] a = new int[n];
string input = null;
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
input = Console.ReadLine();
try {
a[i] = int.Parse(input);
Console.WriteLine(string.Format(
"You have inputted {0} for the {1} element",
input, i
));
} catch { Console.WriteLine("Non integer input"); i -= 1; }
}

you can try this
int [] a = {8,9};
for(int i=0; i< a.Length; i++)
{
int z = a[i]; //for taking value from array at the specific ith position
Console.WriteLine("i: " + i + " z:" + z);
}

try this
List<int> a = new List<int>();
int n = 2; // you can change it according to your need
for (int i = 0; i < n; i++)
{
string str = Console.ReadLine(); // make sure you enter an integer and conver it
int z = int.Parse(str);
a.Add(z);
}
foreach (int k in a)
{
Console.WriteLine(k);
}

Related

how to print the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.
Code
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.
I would use something like this for the output:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
When the inner loop is done, that means one row has been completely printed. So that's the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

How to refactor this code to combine several sections?

Let's say I have these 3 not so different codes.
How can I combine them, or let's just say I want to enter 10 numbers once I open the application.
I want those numbers to be added to each other, and at the same time show me if the number is even or not.
Here is the input code:
int[] dizi = new int[10];
for (int i=0; i<=10; i++)
{
dizi[i] = Convert.ToInt32(Console.ReadLine());
}
Here is the addition code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
toplam=toplam+sayi;
}
Console.WriteLine("Dizideki sayıların toplamı = " + toplam);
Here is the even number code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
if (sayi%2 ==0)
Console.WriteLine(sayi);
}
All code in one for loop.
For input 10 elements you need for from 0 to i < array.Length
because array int[10] access by index from 0 to 9
var array = new int[10];
var sum = 0;
for (var i = 0; i < array.Length; i++)
{
var number = Convert.ToInt32(Console.ReadLine());
sum += number;
if (number % 2 == 0)
Console.WriteLine($"The number {number} is even");
}
Console.WriteLine($"Sum = {sum}");

C#: how to detect repeating values in an array and process them in such a way that each repeating value is only processed once?

I wrote this simple program:
class Program
{
static void Main(string[] args)
{
Console.Write("Number of elements in the array: ");
int numberOfElements = int.Parse(Console.ReadLine());
int[] array = new int[numberOfElements];
for(int i = 0; i < numberOfElements; i++)
{
Console.Write($"Element no {i+1}: ");
array[i] = int.Parse(Console.ReadLine());
}
for(int i = 0; i < array.Length; i++)
{
int count = 0;
for(int j = 0; j < array.Length; j++)
{
if(array[i] == array[j])
{
count++;
}
}
Console.WriteLine($"{array[i]} appears " + count + " times");
}
}
}
}
Is there any option to make the displayed values print only once?
For example, if there are three occurrences - the message displays three times. Is it possible to make it display once when there are more occurrences though?
You could use a GroupBy instead of the for loop
Groups the elements of a sequence.
var results = array
.GroupBy(x => x)
.Select(x => new {Value = x, Count = x.Count()});
foreach(var g in results)
Console.WriteLine($"{g.Value} appears {g.Count} times");
Or another way it to use a HashSet to keep track of what you have displayed. A HashSet is basically a collection that contains no duplicate elements. The Add methods returns true if it can add an element or false otherwise
HashSet<T>.Add(T) Method
returns true if the element is added to the HashSet object; false if the
element is already present.
var hashSet = new HashSet<int>();
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
if (array[i] == array[j])
count++;
// Add to the hashset, if the add method returns true,
// it means the value was uniquely added, ergo you have not displayed yet
if (hashSet.Add(array[i]))
Console.WriteLine($"{array[i]} appears " + count + " times");
}
Full Demo Here
Or another approach is to use a Dictionary. The premise is to iterate over the array, try an add each item to the dictionary with TryAdd if it's already found increment the value
var dictionary = new Dictionary<int,int>();
foreach(var item in array)
if(!dictionary.TryAdd(item,1))
dictionary[item]++;
foreach(var item in dictionary)
Console.WriteLine($"{item.Key} appears {item.Value} times");
Full Demo Here
The first idea I had was the same of the comment from Jon Skeet, since the simplicity it implies.
The idea is to set null for the value we have already counted (matched).
From a developer point of view it is very simple and doesn't deviate too much from the OP's code.
Console.Write("Number of elements in the array: ");
int numberOfElements = int.Parse(Console.ReadLine());
int?[] array = new int?[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
Console.Write($"Element no {i + 1}: ");
array[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < array.Length; i++)
{
int count = 0;
int? current = array[i];
if (array[i] != null)
{
for (int j = 0; j < array.Length; j++)
{
if (current == array[j])
{
count++;
array[j] = null;
}
}
Console.WriteLine($"{current} appears " + count + " times");
}
}
int?[] defines a nullable value type. Therefore each item in the array can have either a null or int value - documentation here.
An approach using Dictionary with O(n) complexity.
Console.Write("Number of elements in the array: ");
int numberOfElements = int.Parse(Console.ReadLine());
var dictionary = new Dictionary<int, int>();
for (int i = 0; i < numberOfElements; i++)
{
Console.Write($"Element no {i + 1}: ");
var value = int.Parse(Console.ReadLine());
if (!dictionary.ContainsKey(value)) dictionary.Add(value, 0);
dictionary[value] = dictionary[value] + 1;
}
foreach (var item in dictionary)
{
Console.WriteLine($"{item.Key} appears {item.Value} times");
}
One simple way would be to swap your outer for loop with a foreach using a set to obtain distinct values.
So replace this:
for (int i = 0; i < array.Length; i++)
With this:
foreach (int i in new HashSet<int>(array))
And this:
if (array[i] == array[j])
With this:
if (i == array[j])
Other approach more suited for you would be too take only unique values from array, i.e.:
var unique = array.Distinct().ToArray();
for (int i = 0; i < unique.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
if (array[i] == array[j])
{
count++;
}
}
Console.WriteLine($"{unique[i]} appears " + count + " times");
}
In the inner loop, try to check if there were already any occurrences of the current element until you exceed the outer index.
for(int i = 0; i < array.Length-1; i++)
{
int count = 1;
bool appeared = false;
for(int j = 0; j < array.Length; j++)
{
// until we are not at the same index as the outer loop
// check if we haven't already met the current element
if(j < i)
{
if (array[i] == array[j])
{
// set current value appearance to true
// to know if current element should be displayed
appeared = true;
// break the loop because there is no sense of continuing
// current look
break;
}
}
// if we are ahead of outer index
// check if there are occurences of the element
else if(j > i)
{
if (array[i] == array[j])
count++;
}
}
// don't print the current element if it has appeared before
if(!appeared)
Console.WriteLine($"{array[i]} appears {count} times");
}
I believe there should be a more optimal solution, as this one's time complexity is linear... You can think of some optimization. For example, you can store occurred elements in the array and check through the array at each iteration, so you don't need to start the inner loop from the beginning, but instead start it from the outer loop's position + 1 but it's also not the best solution.
P.S check out about string interpolation, because you don't need to concatenate strings when you use it.
You can also use Lookup here:
var sb = new StringBuilder();
foreach (var value in array.ToLookup(item => item))
{
sb.AppendLine($"{value.Key} appears " + value.Count() + " times");
}
Console.WriteLine(sb.ToString());

How to make a Jagged Array?

Thinking like a simple array:
Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());
string[] strA = new string[x];
strA[0] = "Hello";
strA[1] = "World";
for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}
Now, how can I do it with a double array?
I've already tried this:
Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());
// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];
strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";
for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}
If's there's a simpler way of doing this, i'll be happy to learn it.
It's only for knowledge, I'm studying double array for the first time, so have patience please :)
Here's my example:
https://dotnetfiddle.net/PQblXH
You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])
If you want to hardcode:
string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};
in case you want to provide x and y:
string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();
Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):
// strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];
// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)
Edit: Let's print out jagged array line after line:
Good old for loops
for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();
// please, note that each line can have its own length
string[] line = strA[i];
for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}
Compact code:
Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));
You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].
First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.
To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());
var table = new string[x, y];
You need to to declare your table before knowing its size.
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row, col] = Console.ReadLine();
}
}
table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write(table[row, col]);
}
Console.Write("\n");
}
For a 3x3 table with 00X, 0X0, X00 as inputs the result is
00X
0X0
X00
It works. You separate each cell when we display by simply adding a comma or a space.
Fiddle
And for Jagged Array:
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
var table = new string[x][];
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
Console.WriteLine($"Enter of the line n°{row}");
var lineSize = int.Parse(Console.ReadLine());
table[row] = new string[lineSize];
for (int col = 0; col < table[row].Length; col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row][col] = Console.ReadLine();
}
Console.Write("\n");
}
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
for (int col = 0; col < table[row].Length; col++)
{
Console.Write(table[row][col]);
}
Console.Write("\n");
}
Wrong variable in use:
for(int j = 0;i < y;i++) <- Should be j
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}

Why I get 0 as a value in my array elements?

I'm encountering a problem with the code :
for (int i = 0; i < nr; i++)
{
intarray = new int[nr];
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i]+"Test1 "+i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i]+"Test2 "+i);
}
//nr = 3
Some outputs : http://prntscr.com/5d8msx http://prntscr.com/5d8nkm ... .My problem that first 2 (intarray[0] and intarray[1]) are always 0, why are they always 0 because they aren't supposed to. intarray is initialiazed outside the function. Btw the generateRandom is this
Random r = new Random();
static int generateRandom(int max)
{
int randnum = r.Next(0, max);
return randnum;
}
You are creating a new array in the for-loop each time:
intarray = new int[nr];
This part should be outside the loop.
Since int is a value-type, all values of the array are initialized with its default value (0)
Initialize you array outside loop.
var intarray = new int[nr];
for (int i = 0; i < nr; i++)
{
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i]+"Test1 "+i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i]+"Test2 "+i);
}
What you are doing now is create new array every time. and int init by 0.
I think your logic is wrong.
Every iteration in your first for loop, you are creating a new array reference. Since your array type is int, all elements of your array fills with 0 by default.
Since in Random.Next(int, int) overload, minimum values is inclusive, it might generate 0 as a result.
For example;
In your first iteration i is 0 and you create an array referance called intarray with new int[3] and you assing intarray[0] some random number (which is from 0 to 3) but the other elements in your array (intarray[1] and intarray[2]) are filled with 0 which is default value for an int.
At last iteration; your nr value is 3 and your i is 2. That means you fill your intarray[2] with a random number from 0 to 3, but since you didn't assing any value your intarray[0] and intarray[1] elements, they still keep 0 value by default.
As a solution, you should initialize your array outside of your for loop, like;
intarray = new int[nr];
for (int i = 0; i < nr; i++)
{
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i] + "Test1 " + i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i] + "Test2 " + i);
}

Categories