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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!