For-loops, array and ++ operator - c#

Beginner asking a question.
I am testing the increment ++ operator within for-loop and the outcome is different than I expect it to be and I have no clue why. The code is not for a specific program.
int[] numbers = new int[10];
for (int i = 0; i < 10; i++)
{
numbers[i] = i++;
}
for (int a = 0; a < 10; a++)
{
Console.WriteLine("value is {0} at position {1}", numbers[a], a);
}
Output is:
value is 0 at position 0
value is 0 at position 1
value is 2 at position 2
value is 0 at position 3
value is 4 at position 4
value is 0 at position 5
value is 6 at position 6
value is 0 at position 7
value is 8 at position 8
value is 0 at position 9
If i run the first for-loop without the ++ increment (numbers[i] = i;), the values are consecutive and in order (0, 1, 2, 3 etc.). Why the ++ increment causes every other value to be zero? I thought it would be something like 0, 2, 4, 6, 8, 10 etc.
If I run numbers[i] = i+1;
outcome is something I would expect:
value is 1 at position 0
value is 2 at position 1
value is 3 at position 2
value is 4 at position 3
value is 5 at position 4
value is 6 at position 5
value is 7 at position 6
value is 8 at position 7
value is 9 at position 8
value is 10 at position 9

The code you write is
for (int i = 0; i < 10; i++)
{
numbers[i] = i++;
}
that is equal to
for (int i = 0; i < 10; i++)
{
numbers1[i] = i;
i = i + 1;
}
First time i is start from 0
// I change the i to real value for easy understanding
for (int i = 0; i < 10; i++)
{
numbers1[0] = 0;
i = 0 + 1;
//so here i is 1
}
Second time i is 2, because after first time loop the i is 1 then the for (int i = 0; i < 10; i++) will increase i from 1 to 2,
so the second time loop will be
for (int i = 0; i < 10; i++)
{
numbers1[2] = 2;
i = 2 + 1;
//so here i is 3
}
So now you know the numbers[0] is 0 and numbers[2] is 2 but about the numbers[1] you don't set the value for it so it will be the default value which the default value of int is 0.

Thank you Michael! I verified that out also by myself when messing around with the code. First I tried adding one more i++;
for (int i = 0; i < 50; i++)
{
numbers[i] = i++;
i++;
}
It gave me value on every third row.
And then third i++:
for (int i = 0; i < 50; i++)
{
numbers[i] = i++;
i++;
i++;
}
Now value every fourth line.
Solved.

Related

Display every digit of values of array

I have an array of numbers and I want to display the last digit first, then the 2nd, 3rd, and so on.. How do I do that?
for example, I have: 123, 210, 111
It will display 3, 0, 1, first
then 2, 1, 1,
last, 1, 2, 1
I have this as my code:
for(int x = 0; x < 3; x++){
string n = num[x].ToString(); //converting the array to string
for(int y = length-1; y>=0; y++) //length = number of digits
Console.Write(c[y] + "\n");
}
But it displays the digits of the 1st number first, then the 2nd num, and the 3rd. (3, 2, 1, 0, 1,2, 1,1,1)
You just need to reverse the order of the loops and decrease the letter loop counter:
for(int y = length - 1; y>=0; y--) //length = number of digits
{
for(int x = 0; x < 3; x++){
string n = num[x].ToString(); //converting the array to string
Console.Write(n[y] + "\n");
}
}
Firstly you want to be decreasing your loop counter. Also what is the array c? you have assigned the number to 'n' earlier
Not that clean but w.e.
int[] myInts = { 123, 210, 111 };
string[] result = myInts.Select(x => x.ToString()).ToArray();
int k = 0;
for (int i = 3; i > 0; i--)
{
while (k < 3)
{
Console.Write(result[k].Substring(i - 1, 1));
k++;
}
k = 0;
Console.WriteLine();
}

a program that get 10 numbers and print them in reverse order

I'm trying to write a program that takes 10 inputs and prints them in reverse order. Here is my code in c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace inverse
{
class Program
{
static void Main(string[] args)
{
int i ;
int[] n = new int[10];
Console.WriteLine("please enter 10 numbers");
for (i = 1; i <= 10; i++)
n[i] =int.Parse(Console.ReadLine());
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i] + " ");
Console.ReadKey();
}
}
}
It doesn't get any errors but it also doesn't work when i'm trying to debug it. Could you please help me?
You should change your second for loop to:
for (i = 9; i >= 0; i--)
Why?
Because in you incorrect for loop, i starts at 10. In each iteration, it decrements, until i >= 1. In other words, i's value changes from 10 to 1.
But that's not how arrays work, is it? Arrays in C# are 0-based, meaning that the first item is at index 0, and the last item is at index (length - 1). In this specific case, the last item would be at index 9 (10 - 1 = 9)!
When you try to access the item at index 10, of course it throws an exception because the array ends at index 9! Also, even if it has an item at index 10, the first item of the array would not be printed because the loop stops at i = 1.
That is why you want i's value to go from 9 to 0 instead of 10 to 1.
EDIT:
I just realized you made another mistake, your first for loop is incorrect as well. It should loop from 0 to 9, not 1 to 10. This is the correct version:
for (int i = 0 ; i <= 9, i++)
Alternatively, instead of changing the loop's headers, you can just add - 1:
for (i = 1; i <= 10; i++)
n[i - 1] =int.Parse(Console.ReadLine());
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i - 1] + " ");
You need to start from 0 to 9 and vice versa
for (i = 0; i <= 9 i++)
n[i] =int.Parse(Console.ReadLine());
for (i = 9; i >= 0; i--)
Console.WriteLine(n[i]);
Use the below code:
static void Main(string[] args)
{
int i;
int[] n = new int[11];
Console.WriteLine("please enter 10 numbers");
for (i = 1; i <= 10; i++)
n[i] = Convert.ToInt32((Console.ReadLine()));
for (i = 10; i >= 1; i--)
Console.WriteLine(n[i] + " ");
Console.ReadKey();
}
The problem was array index was out of range as the array starts from 0. It gave me error when I gave up to 10 inputs.

List< string > to string[,]

I have a List<string> tmpNames that contains names e.g. ("A","B","C","D","E",F").
The size of tmpNames can be different (it is a result obtained from client input).
Now I need to create a matrix with a number of rows and columns.
string[,] tmpMatrix = new string[tmpRows.Count,tmpCols.Count];
But to iterate and build the matrix I have the following code in which I can not access all items in tmpNames.
for(int i= 0; i<tmpRows.Count; i++){
for(int j= 0; j<tmpRows.Count; j++){
tmpMatrix[i,j] = tmpNames[i];
}
}
The result that I need is:
A B C
D E F
You have to calculate which index you need from tmpNames - you need both i and j for that. You might want to put it on paper to see the pattern:
j=0 j=1 j=2
i=0 0 1 2
i=1 3 4 5
Your code should be something like:
for(int i= 0; i<tmpRows.Count; i++){
for(int j= 0; j<tmpCols.Count; j++){
tmpMatrix[i,j] = tmpNames[i * tmpCols.Count + j];
}
}
Note that I have also corrected the condition in the 2nd loop: you have to compare j with tmpCols.Count, not tmpRows.Count.
You could use separate indexes for Row, Column & source:
for(int i = 0, source = 0; i < tmpRows.Count; i++){
for(int j = 0; j < tmpCols.Count; j++){
tmpMatrix[i, j] = tmpNames[source++];
}
}
You can calculate the indexes in the tmpMatrix from the index in the tmpNames list and populate it using a single loop:
int index = 0;
for (int index = 0; index < tmpNames.Count; index++) {
tmpMatrix[index / tmpCols.Count, index % tmpCols.Count] = tmpNames[index];
}
By using divison and modulo (%) you get the result as row and reminder as column:
index index / 3 index % 3
----- --------- ---------
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2

Multiply every other array element by 2

I have an array of 10 digits. I want to multiply by 2, each element of the array with an even index. The elements with an odd index I want to multiply by 1 (in reality, leave unchanged). Hence, array[0] * 2, array[1] * 1, array[2] * 2, etc.
I tried using the modulus operator on the index number of each element, but I don't think that is what my code actually did. My previous silly attempt is as follows:
for (int i = 0; i < 10; i++)
{
if ((Array.IndexOf(myArray, i) % 2) == 0)
{
// multiply myArray[i] by 2
}
else // multiply myArray[i] by 1
}
This code is for any no.of element in the list. (Array can have 1 or more element)
myArray = myArray.Select(x => ((Array.IndexOf(myArray, x) % 2 == 0) ? x * 2 : x * 1)).ToArray();
would give you the array of integers with even index element multiplied by 2, and odd on multipled by 1.
for (int i = 0; i < 10; i++)
{
if((i % 2) == 0)
{
// multiply myArray[i] by 2
}
else // multiply myArray[i] by 1
}
Array.IndexOf(firstParam,secondParam) will give you the index of secondParam. For example:
arr[0] = 10
arr[1] = 3
arr[2] = 5
arr[3] = 1
Array.IndexOf(arr,1) = 3, Array.IndexOf(arr,3) = 1, etc.

Printing out 3 elements in array per line

I have an array with x number of elements and want to print out three elements per line (with a for-loop).
Example:
123 343 3434
342 3455 13355
3444 534 2455
I guess i could use %, but I just can't figure out how to do it.
For loop is more suitable:
var array = Enumerable.Range(0, 11).ToArray();
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0,-5}", array[i]);
if (i % 3 == 2)
Console.WriteLine();
}
Outputs:
0 1 2
3 4 5
6 7 8
9 10
Loop through the array 3 at a time and use String.Format().
This should do it...
for (int i = 0; i < array.Length; i += 3)
Console.WriteLine(String.Format("{0,6} {1,6} {2,6}", array[i], array[i + 1], array[i + 2]));
But if the number of items in the array is not divisable by 3, you'll have to add some logic to make sure you don't go out of bounds on the final loop.
You perhaps need to fix the format spacing...
for(int i=0;i<array.Length;i++)
{
Console.Write(array[i] + " ");
if((i+1)%3==0)
Console.WriteLine();
}
Long... but with comments:
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = list.Count;
int numGroups = list.Count / 3 + ((list.Count % 3 == 0) ? 0 : 1); // A partially-filled group is still a group!
for (int i = 0; i < numGroups; i++)
{
int counterBase = i * 3;
string s = list[counterBase].ToString(); // if this a partially filled group, the first element must be here...
if (counterBase + 1 < count) // but the second...
s += list[counterBase + 1].ToString(", 0");
if (counterBase + 2 < count) // and third elements may not.
s += list[counterBase + 2].ToString(", 0");
Console.WriteLine(s);
}

Categories

Resources