Freakofif
Freakofif

Reputation: 1

Wrong element output in C#

I apologize in advance, but I'm fairly new to C# in this context (I've used it in Unity, but never on its own).

I'm trying to create a string array, and within a loop, have another array with, let's say, a rating system (int elements). Unfortunately, my problem seems on a level of its own.

This is the code:

using System;

public class Test
{
  public static void Main()
  {
    string [] arr1 = new string[] {"a","b","c","d","e"};
    int a = 0;
    foreach (var element in arr1)
    {          
        int [] myRate = new int [5] {1,2,3,4,5};
        int [] rating = myRate;
        a = rating[0];
        Console.WriteLine (element +": " + (rating[a]));
    } a++;
  }
}

My problem is the output is supposed to be 1 (for all elements because I'm still working on the incrementation), but this is the output:

a: 2
b: 2
c: 2
d: 2
e: 2

I tried to reduce the code as much as possible to pinpoint the problem (that's why it's kind of minimalistic), but I still cannot figure it out. When I change the zero to 1 the output is 2, and so on. If I change it to 4 it says its out of bound. Your help is much appreciated, and thank you in advance.

Upvotes: 0

Views: 120

Answers (3)

Preet
Preet

Reputation: 994

If you want 1 in answer then write:

Console.WriteLine (element +": " + a);

or

Console.WriteLine (element +": " + rating[0]);

because a=rating[0]; i.e. first element of array whose value is 1.

you are using:

Console.WriteLine (element +": " + (rating[a]));

i.e. rating[1] because value of a is 1.

so rating[1] is second element of array whose value is 2

Upvotes: 0

Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10695

Inside your loop, when do this:

a = rating[0];

then a becomes 1, because it's the first item in your int array. Then you write this to console:

rating[a]

...which results to this (since a is 1):

rating[1]

...and the second item in your array is 2, that's why you get this output.


Two ways of outputting 1:

foreach (var element in arr1)
{          
    int [] myRate = new int [5] {1,2,3,4,5};
    int [] rating = myRate;
    a = 0;
    Console.WriteLine (element +": " + (rating[a]));
} a++;

and

foreach (var element in arr1)
{          
    int [] myRate = new int [5] {1,2,3,4,5};
    int [] rating = myRate;
    Console.WriteLine (element +": " + (rating[0]));
} a++;

As a side note, you may consider creating the int[] outside your loop, since you are every iteration creating the same array, unless you actually intend to create arrays with different values every new iteration.

Upvotes: 1

Willy David Jr
Willy David Jr

Reputation: 9131

Because "a" contains number "1".

And number 1 on index of rating array is 2.

If you want to print number 1, you should start at index 0. Which is:

Console.WriteLine (element +": " + (rating[0]));

Upvotes: 0

Related Questions