Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find type of array entered by the user.
In C programming, we can classify an array based on the type of numbers it contains. An array can be classified as an even array (all elements are even), an odd array (all elements are odd), or a mixed array (contains both even and odd elements).
Algorithm
Here's the approach to determine the array type −
- Read the array size and elements from user
- Count even and odd numbers in separate counters
- Compare counters with total size to determine array type
- Display the result based on the comparison
Example
The following program demonstrates how to find the type of array entered by the user −
#include <stdio.h>
int main() {
int n, i;
int odd = 0, even = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements: ");
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
/* Count even and odd numbers */
for(i = 0; i < n; i++) {
if(arr[i] % 2 == 0)
even++;
else
odd++;
}
/* Determine array type */
if(odd == n)
printf("Array type: Odd Array<br>");
else if(even == n)
printf("Array type: Even Array<br>");
else
printf("Array type: Mixed Array<br>");
return 0;
}
Output
Enter number of elements: 4 Enter the elements: 2 4 6 8 Array type: Even Array
How It Works
- The program uses two counters:
evenandoddto track the count of even and odd numbers - For each element, we check if
arr[i] % 2 == 0(even) or not (odd) - Finally, we compare the counters with total array size
nto determine the type - If
odd == n, all elements are odd; ifeven == n, all elements are even; otherwise, it's mixed
Conclusion
This program efficiently classifies arrays by counting even and odd elements. The modulo operator is key to determining if a number is even or odd, making the solution both simple and effective.
Advertisements
