Question
Write a code in C++ to print out three numbers from an array that add up to the largest value less than 30. I have
Write a code in C++ to print out three numbers from an array that add up to the largest value less than 30.
I have tried but my code keeps printing 3 numbers that produce the smallest value less than 30.
// C++ program to find a triplet
# include
#include
using namespace std;
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
// Fix the first element as A[i]
for (int i = 0; i < arr_size-2; i++)
{
// Fix the second element as A[j]
for (int j = i+1; j < arr_size-1; j++)
{
// Now look for the third number
for (int k = j+1; k < arr_size; k++)
{
if ( A[i] + A[j] + A[k] { printf("Triplet is %d, %d, %d", A[i], A[j], A[k]); cout< return true; } } } } // If we reach here, then no triplet was found return false; } /* Driver program to test above function */ int main() { int A[] = {1, 4, 45, 6, 10, 8}; int sum = 30; int arr_size = sizeof(A)/sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started