Maha

Maha

  • NA
  • 0
  • 326.1k

Parallel Arrays & while loop

Aug 14 2012 7:40 PM
This program will check the price of a given item. If item is found that means in the while loop itemOrdered is equal to validValues[x] then the loop ends and the execution will go to next if expression. If loop will execute the price of the item.

Suppose we say give item is not found then while loop will end with x=4. Next execution will go to if expression and will skip executing the price (because item is not found) and program will end.

My question is if(x != validValues.Length) expression is always true. But in one occasion (when item is found) loop is executed and other occasion (when item is not found) loop is skipped. Please explain this variation. 


using System;
public class ParallelArrays1
{
public static void Main()
{
int[] validValues = {101, 108, 201, 213, 266};
double[] prices = {0.89, 1.23, 3.50, 0.69, 5.79};//parallel array

Console.Write("Enter item No: ");
int itemOrdered = Convert.ToInt32(Console.ReadLine());

int x = 0;
while (x < validValues.Length && itemOrdered != validValues[x])
++x;

if (x != validValues.Length)
Console.WriteLine(prices[x].ToString("c"));
else //error corrected
Console.WriteLine("Item entered is not found. End of the program");

Console.ReadKey();
}
}




Answers (2)