0

I have to check second value in array if is equal to zero. It's working on my first example, where is user input not looped. But is not working on second example, where user input is looped.

First example

int[] array = new int[4];

array[0] = int.Parse(Console.ReadLine());
array[1] = int.Parse(Console.ReadLine());
//This statement Works here
if (array[1] == 0)
{
    Console.WriteLine("Alert!");
}
array[2] = int.Parse(Console.ReadLine());
array[3] = int.Parse(Console.ReadLine());

Second example

int[] array = new int[4];

for (int i = 0; i < array.Length; i = i + 1)
{ 
    //Input
    array[i] = int.Parse(Console.ReadLine());
//This statement is not working
if (array[1] == 0)
{
   Console.WriteLine("Alert!");
}
7
  • Can you print array[1] in the second case and see what's in it? Commented Dec 11, 2016 at 12:44
  • It seems like this is homework, isn't it? Commented Dec 11, 2016 at 12:45
  • It works perfect (after i add the miss } ), What the problem? Commented Dec 11, 2016 at 12:49
  • Array[1] is second value. In my case is "2". Commented Dec 11, 2016 at 12:51
  • I have missing } in my code, I just skipped it when I was copying this code. And its still not working. Commented Dec 11, 2016 at 12:53

3 Answers 3

1

I think you maybe want to do that:

int[] array = new int[4];

for (int i = 0; i < array.Length; i = i + 1)
{ 
    //Input
    array[i] = int.Parse(Console.ReadLine());
    if (array[i] == 0) // use i instead of 1
    {
        Console.WriteLine("Alert!");
    }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

If you use [i], then is meant for all array fields, but I strictly needed only for specific value.
0

I just had to write this if statement outside the loop. Now it Works

int[] array = new int[4];

for (int i = 0; i < array.Length; i = i + 1)
{ 
    //Input
    array[i] = int.Parse(Console.ReadLine());
}

if (array[1] == 0)
{
   Console.WriteLine("Alert!");
}

Comments

0

to be sure to acuire valid values rom user you could use int.TryParse() instead of int.Parse()

        for (int i = 0; i < array.Length; i = i + 1)
        {
            while (!int.TryParse(Console.ReadLine(), out array[i]))
                Console.WriteLine("Input an integer value!");                    
        }

        if (array[1] == 0)
        {
            Console.WriteLine("Alert!");
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.