Program in C++: Write a lambda function to check if a number can be divided by t
ID: 652754 • Letter: P
Question
Program in C++:
Write a lambda function to check if a number can be divided by the first input number (assume there are at least 2 input numbers)
please create a class named "isGreater" to implement this function object.
class isGreater{
public:
bool operator () (int value){
// do something here
}
};
Sample output should look like this:
./main
Enter numbers to check:
5 2 7 10 3 6 8 15 d
There are 3 numbers that can be divided by 5.
The first element greater than 8 is 10.
./main
Enter numbers to check:
3 1 2 3 4 5 6 7 d
There are 3 numbers that can be divided by 3.
There is no element greater than 8!
Explanation / Answer
#include<iostream>
#include<string>
#define MAX 20
using namespace std;
class isGreater
{
int arr[MAX];
int size;
public:
isGreater()
{
size=0;
}
void set(int i)
{
arr[size++]=i;
}
void display()
{
for( int i=0;i<size;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int getvalue(int n)
{
return arr[n];
}
int get_size()
{
return size;
}
bool operator () (int value)
{
// do something here
//elements which can be devided by first element
if( value % arr[0] )
{
return 0;
}
else
{
return 1;
}
}
};
int main()
{
isGreater obj;
char buf[20];
cout<<"Enter numners or d to quit "<<endl;
do
{
cin>>buf;
if( strcmp(buf,"d")== 0)
break;
obj.set(atoi(buf));
}while(strcmp(buf,"d") != 0);
int divisible=0, greatethan_8=0, firsttime=0;
for(int i=0;i<obj.get_size();i++)
{
if( obj.operator()(obj.getvalue(i) )== 1)
{
divisible++;
}
// check value greater than 8 and it's first time
if( obj.getvalue(i) > 8 && firsttime== 0 )
{
greatethan_8=i;
firsttime=1;
}
}
if(divisible)
cout<<"There are "<< divisible<<" numbers that can be divided by "<<obj.getvalue(0)<<endl;
else
cout<<"There are no elements divisible by "<<obj.getvalue(0)<<endl;
if(greatethan_8)
cout<<"The first element greater than 8 is "<<obj.getvalue(greatethan_8)<<endl;
else
cout<<"There is no element greater than 8!"<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.