Slasher
Slasher

Reputation: 618

Check array value inside for loop

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!");
}

Upvotes: 0

Views: 97

Answers (3)

user3598756
user3598756

Reputation: 29421

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!");
        }

Upvotes: 0

Alexander
Alexander

Reputation: 11

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!");
    }
 }

Upvotes: 1

Slasher
Slasher

Reputation: 618

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!");
}

Upvotes: 0

Related Questions