C++ Exercises: Check a given array of integers and return true if the given array contains either 2 even or 2 odd values all next to each other
C++ Basic Algorithm: Exercise-111 with Solution
Check for Two Adjacent Even or Odd Numbers in Array
Write a C++ program to check a given array of integers. The program will return true if the given array contains either 2 even or 2 odd values all next to each other.
Sample Solution:
C++ Code :
#include <iostream> // Including input-output stream header file
using namespace std; // Using standard namespace
// Function definition that checks if there are two consecutive even or odd numbers in the array
static bool test(int numbers[], int arr_length)
{
int tot_odd = 0, tot_even = 0; // Initializing counters for odd and even numbers
// Loop through the array to find consecutive even or odd numbers
for (int i = 0; i < arr_length; i++)
{
// Check conditions for consecutive even or odd numbers
if (tot_odd < 2 && tot_even < 2)
{
if (numbers[i] % 2 == 0)
{
tot_even++; // Increment count for even numbers
tot_odd = 0; // Reset count for odd numbers
}
else
{
tot_odd++; // Increment count for odd numbers
tot_even = 0; // Reset count for even numbers
}
}
}
// Return true if there are two consecutive odd or even numbers, otherwise false
return tot_odd == 2 || tot_even == 2;
}
int main()
{
// Different test cases with arrays of integers
int nums1[] = {3, 5, 1, 3, 7}; // No two consecutive even or odd numbers
int arr_length = sizeof(nums1) / sizeof(nums1[0]);
cout << test(nums1, arr_length) << endl;
int nums2[] = {1, 2, 3, 4}; // No two consecutive even or odd numbers
arr_length = sizeof(nums2) / sizeof(nums2[0]);
cout << test(nums2, arr_length) << endl;
int nums3[] = {3, 3, 5, 5, 5, 5}; // Two consecutive odd numbers
arr_length = sizeof(nums3) / sizeof(nums3[0]);
cout << test(nums3, arr_length) << endl;
int nums4[] = {2, 4, 5, 6}; // Two consecutive even numbers
arr_length = sizeof(nums4) / sizeof(nums4[0]);
cout << test(nums4, arr_length) << endl;
return 0; // Returning 0 to indicate successful completion of the program
}
Sample Output:
1 0 1 1
Visual Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to check a given array of integers and return true if there is a 3 with a 5 somewhere later in the given array.
Next: Write a C++ program to check a given array of integers and return true if the value 5 appears 5 times and there are no 5 next to each other.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-111.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics