How can i use any of? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can i use any of?

I want to know how to make a script that if any element from an array equals with a random variable than cout "you won" else "you lost".

31st Mar 2019, 5:38 PM
Bacca
Bacca - avatar
1 Answer
+ 9
#include <cstdlib> // contains srand() and rand() functions #include <ctime> // for time() function #include <iostream> // standard i/o int main() { srand(time(0)); // seed to generate a true random number const int size = 10; // size of the array int arr[size] = {1,2,3,4,5,6,7,8,9,10}; for(int i=0; i<size; ++i) { if(arr[i] == rand()) { std::cout << "you won"; break; // you won, exits from for loop } if(i==size-1) // if reached end of array without winning std::cout << "you lost"; } std::cout << std::endl; return 0; } -> if you want to generate a number between a range you can use the % operator, for example, to generate a number between 0 and 9: rand()%10
31st Mar 2019, 6:30 PM
Andrea Leoni
Andrea Leoni - avatar