In: Computer Science
If the current number is divisible by 2, then print HAP
If the current number is divisible by 5, then print PY
If the current number is divisible by both 2 and 5, then print HAPPY
If the number is neither divisible by 2 nor 5, then print the number
Example: 1 HAP 3 HAP PY HAP 7 HAP 9 HAPPY 11 HAP 13 HAP PY HAP 17 HAP 19 HAPPY …
#include <iostream>
#include <thread>
using namespace std;
// function that will be called by thread first
// it will return HAP if number is divisible by 2
void csu(int value)
{
if(value%2==0)
{
cout<<"HAP";
}
}
// function that will be called by thread second
// it will return PY if number is divisible by 5
void sb(int value)
{
if(value%5==0)
{
cout<<"PY";
}
}
// function that will be called by thread third
// it will return HAPPY if number is divisible by 2 as well as 5
void csusb(int value)
{
if(value%2==0 && value%5==0)
{
cout<<"HAPPY";
}
}
// function that will be called by thread fourth
// it will return a random number between 1-100 if number is neither divisible by 2 nor by 5
void number(int value)
{
if(value%2!=0 && value%5!=0)
{
cout<<(1+rand()%99);
}
}
// main method
int main()
{
int values[50]; // array of 50 elements
// loop to store 50 numbers generated randomly using rand()
// if you don't want to generate random numbers you can take input from user using cin>>values[i];
for (int i=0;i<50;i++)
{
values[i]=1+rand()%99;// numbers generated will be between 1-100
}
// loop to call thread for every element of array
for(int i=0;i<50;i++)
{
thread first (csu,values[i]); // will call csu(values[i])
thread second (sb,values[i]); // will call sb(values[i])
thread third (csusb,values[i]); // will call csusb(values[i])
thread fourth (number,values[i]); // will call number(values[i])
first.join();// wait for thread first to finish
second.join();// wait for thread second to finish
third.join();// wait for thread third to finish
fourth.join();// wait for thread fourth to finish
}
return 0;
}