Click here to Skip to main content
15,902,908 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need the program to stop taking values when 0 is entered but in a way so that user can still enter searchvalue as shown in my code.
int i = 0;
int count = 0;
int item = 0;

int[] arr1 = new int[20];


for (i = 0; i < 20; i++)
{
    Console.Write("Enter a number (0=stop): ");
    arr1[i] = int.Parse(Console.ReadLine());
}


Console.Write("Enter a searchvalue : ");
item = int.Parse(Console.ReadLine());

for (i = 0; i < 20; i++)
{
    if (item == arr1[i])
    {
        count++;
    }
}

Console.WriteLine("Number of occurences of searchvalue (" + item + ") is : " + count);

Console.WriteLine();


What I have tried:

tried different things none of them seem to work.
Posted
Updated 8-Oct-21 13:28pm
v2

Your not checking the value user entered in the first for loop, so the user will have to enter 20 values before exiting loop.

Check the value entered and if zero "break" out of loop.
 
Share this answer
 
You can use the break to terminate the loop.
for (i = 0; i < 20; i++)
{
    Console.Write("Enter a number (0=stop): ");
    arr1[i] = int.Parse(Console.ReadLine());
    if (arr1[i] == 0) {
        break;
    }
}
You would need to handle the program termination; perhaps another variable?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900