Header Ads

Write a Program in C++ for Kids With the Greatest Number of Candies

In kids with greatest Number of Candies problem you will have and array of candies a kid have and you have some extra candies. These extra candies you have to give to each children and if that kid have greatest candies among all then you have to store true i.e., is 1 in result array else you have to store false i.e., is 0 in result array.



Code :


#include<iostream>
#include<climits>
using namespace std;

int main(){
int extraCandies,n, maxNo=INT_MIN;

cout<<"Input number of kids : ";
cin>>n;

int candies[n];
bool result[n];

cout<<"Input Extra Candies : ";
cin>>extraCandies;

for (int i = 0; i < n; i++)
{
cin>>candies[i];
maxNo=max(maxNo,candies[i]);
}

for (int i = 0; i < n; i++)
{
candies[i]=candies[i]+extraCandies;
if(candies[i]>=maxNo){
result[i] = true;
} else{
result[i] = false;
}
candies[i]=candies[i]-extraCandies;
}

for (int i = 0; i < n; i++)
{
cout<<result[i]<<" , ";
}
return 0;
}

Output :

Input number of kids : 5
Input Extra Candies : 3
Enter Number of Candies for kids
2 3 5 1 3
1 1 1 0 1

Explanation :

Include the library 'iostream' for I/O operations and 'climits' is used to define constant within limits to a variable, like we have used INT_MIN which is used to define possible minimum value to the variable 'maxNo'. 
Now, within main function declare three variables : int extraCandies,n, maxNo=INT_MIN; 
Take the number of kids from the user, the value of that will be stored in 'n'. Then declare a array 'candies' of integer type and 'result' of boolean type these both are of size n. They will store the number of candies and result respectively.
Now take the number of extra candies from the user and store it in the variable 'extraCandies'. 
Input values in the candies using for loop and calculate maximum in the array within that for loop using max function which is a build in functions used to find maximum between two 
for (int i = 0; i < n; i++)
{
cin>>candies[i];
maxNo=max(maxNo,candies[i]);
    }

Declare one more for loop in which you will give and take extra candies to every kid. To do so first add extra candies to the kid and then check using if statement whether, if the candies with the kid is equal to or greater than the maximum, then in result array insert true else false.

At the end use another for loop to print the array of result,  in that 1 is for true and 0 is for false.
for (int i = 0; i < n; i++)
{
cout<<result[i]<<" ";
}






Related Links :












Post a Comment

0 Comments