C++ Exercises: Check if a given array of integers contains 5 next to a 5 somewhere
Check for Adjacent '5's in Array
Write a C++ program to check if a given array of integers contains 5 next to a 5 somewhere.
Sample Solution:
C++ Code :
#include <iostream> // Including input-output stream header file
using namespace std; // Using standard namespace
// Function definition that checks if the array contains two consecutive 5s
static bool test(int nums[], int arr_length)
{
// Loop through the array to check for two consecutive 5s
for (int i = 0; i < arr_length - 1; i++)
{
if (nums[i] == 5 && nums[i] == nums[i + 1]) // Checking if two consecutive elements are both equal to 5
return true; // Returning true if two consecutive 5s are found
}
return false; // Returning false if no two consecutive 5s are found
}
int main()
{
int nums1[] = { 1, 5, 6, 9, 10, 17 }; // Initializing array nums1 with various integers
int arr_length = sizeof(nums1) / sizeof(nums1[0]); // Calculating length of array nums1
// Calling test function with nums1 and displaying the result (true or false)
cout << test(nums1, arr_length) << endl;
int nums2[] = { 1, 5, 5, 9, 10, 17 }; // Initializing array nums2 with two consecutive 5s
arr_length = sizeof(nums2) / sizeof(nums2[0]); // Calculating length of array nums2
// Calling test function with nums2 and displaying the result (true or false)
cout << test(nums2, arr_length) << endl;
int nums3[] = { 1, 5, 5, 9, 10, 17, 5, 5 }; // Initializing array nums3 with multiple consecutive 5s
arr_length = sizeof(nums3) / sizeof(nums3[0]); // Calculating length of array nums3
// Calling test function with nums3 and displaying the result (true or false)
cout << test(nums3, arr_length) << endl;
return 0; // Returning 0 to indicate successful completion of the program
}
Sample Output:
0 1 1
Visual Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to compute the sum of the numbers in a given array except those numbers starting with 5 followed by atleast one 6. Return 0 if the given array has no integer.
Next: Write a C++ program to check whether a given array of integers contains 5's and 7's.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics