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
Finding even and odd numbers in a set of elements dynamically using C language
In C programming, we can find and calculate the sum of even and odd numbers from a set of elements using dynamic memory allocation. This approach allows us to handle variable-sized datasets efficiently by allocating memory at runtime.
Syntax
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
// Handle memory allocation failure
}
// Use the allocated memory
free(ptr);
Algorithm
The logic to separate even and odd numbers is straightforward −
- Even numbers: Numbers divisible by 2 (remainder is 0 when divided by 2)
- Odd numbers: Numbers not divisible by 2 (remainder is 1 when divided by 2)
for(i = 0; i < n; i++) {
if(*(ptr + i) % 2 == 0) {
evenSum += *(ptr + i); // Add to even sum
} else {
oddSum += *(ptr + i); // Add to odd sum
}
}
Example
Here's a complete program that dynamically allocates memory for an array and calculates the sum of even and odd numbers −
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, n;
int *ptr;
int evenSum = 0, oddSum = 0;
// Read number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory dynamically
ptr = (int *)malloc(n * sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Memory allocation failed!<br>");
return 1;
}
// Read elements from user
printf("Enter %d elements:<br>", n);
for(i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
// Calculate sum of even and odd numbers
for(i = 0; i < n; i++) {
if(*(ptr + i) % 2 == 0) {
evenSum += *(ptr + i);
} else {
oddSum += *(ptr + i);
}
}
// Display results
printf("Sum of even numbers: %d<br>", evenSum);
printf("Sum of odd numbers: %d<br>", oddSum);
// Free allocated memory
free(ptr);
return 0;
}
Enter the number of elements: 5 Enter 5 elements: 34 23 12 11 45 Sum of even numbers: 46 Sum of odd numbers: 79
Key Points
- Always check if
malloc()returnsNULLto handle memory allocation failures - Use
free()to deallocate memory when no longer needed - The modulo operator
%helps determine if a number is even (remainder 0) or odd (remainder 1) - Pointer arithmetic
*(ptr + i)is equivalent to array notationptr[i]
Conclusion
Dynamic memory allocation with malloc() provides flexibility for handling variable-sized datasets. Combined with modulo arithmetic, we can efficiently separate and sum even and odd numbers from any collection of integers.
Advertisements
