Write a c program to sort the given n integers and perform following operations Find the products of every two odd position elements, Find the sum of every two even position elements Explanation
#include <stdio.h>
#include <stdlib.h>
// Function to sort the array
void sortArray(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Function to find the product of every two odd position elements
void productOfOddPositionElements(int arr[], int n) {
printf("Products of every two odd position elements: ");
for (int i = 0; i < n; i += 2) {
if (i + 2 < n) {
printf("%d ", arr[i] * arr[i + 2]);
}
}
printf("\n");
}
// Function to find the sum of every two even position elements
void sumOfEvenPositionElements(int arr[], int n) {
printf("Sums of every two even position elements: ");
for (int i = 1; i < n; i += 2) {
if (i + 2 < n) {
printf("%d ", arr[i] + arr[i + 2]);
}
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int));
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort the array
sortArray(arr, n);
printf("Sorted array: ");
printArray(arr, n);
// Find the product of every two odd position elements
productOfOddPositionElements(arr, n);
// Find the sum of every two even position elements
sumOfEvenPositionElements(arr, n);
free(arr);
return 0;
}
Comments
Post a Comment