Finding a random array for a specific value
Hi, I was told: "Write a code that determines if a value such as '5' is contained in the array from task 7 (random array), going backwards through the array, starting from the end, and comparing the search for the value with the values in the array. After search, if a value is found, print "Value found" otherwise print "Value not found". "
I understand creating a random array, but I am obsessed with how to work with it through it and find a specific value.
Here is the code so far
class Program
{
static void Main(string[] args)
{
int[] myArray = new int[10];
Random rand = new Random();
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = rand.Next(19);
}
}
}
}
+3
source to share
2 answers
To go back, just use a for loop with an iterator in i--
.
for (int i = myArray.Length - 1; i >= 0; i---)
{
if(// Check if myArray[i] equals the value to find)
{
// If it is the case, you can get out from the for loop with break
break;
}
}
The cycle is for
divided into 4 parts:
for (initializer; condition; iterator)
body
-
initializer
It is performed prior to the first iteration of the loop (here you will want to start with the last index in the array:myArray.Length - 1
) -
condition
is evaluated for each iteration, if that condition is true then it goes to 3 (you want to stay in thefor
while loopi >= 0
), otherwise it will terminate the loopfor
-
body
is performed for each iteration satisfying the condition - In progress
iterator
(here is how you want to go backwards you want to decreasei
) - Then go back to 2
+1
source to share