Problem Statement: Given an array of integers. Your task is to write a C program to count the number of odd and even elements in the array.
- Even Number: A number that is completely divisible by 2.
- Odd Number: A number that is not completely divisible by 2.
Example:
Input: arr[] = {2, 4, 5, 7, 10} Output: Even Count = 3 Odd Count = 2 Input: arr[] = {12, 13, 8, 2, 10} Output: Even Count = 4 Odd Count = 1
Algorithm to Count Even and Odd Elements.
Below are the steps that need to follow:
Step 1: Initialize two variables, evenCount and oddCount, to keep track of the count of even and odd elements respectively. Set both counts to zero.
Step 2: Traverse through the array one element at a time.
Step 3: For each element, check if it is even or odd.
Step 4: If the element is even, increment the evenCount by 1.
Step 5: If the element is odd, increment the oddCount by 1.
Step 6: After traversing through the entire array, output the values of evenCount and oddCount.
Program to Count numbers of odd and even elements in an Array.
// C program to count even and odd numbers in the array #include <stdio.h> int main() { int arr[] = {2, 4, 5, 7, 10}; //size of given array int size = sizeof(arr) / sizeof(arr[0]); int evenCount = 0, oddCount = 0; //check even and odd for (int i = 0; i < size; i++) { if (arr[i] % 2 == 0) { evenCount++; } else { oddCount++; } } printf("Number of even elements: %d\n", evenCount); printf("Number of odd elements: %d\n", oddCount); return 0; }
Number of even elements: 3
Number of odd elements: 2
Time Complexity: The time complexity of this algorithm is O(n) because it needs to traverse through all the elements of the array once.
Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variable and other variables.
Similar articles:
No comments:
Post a Comment