Problem Statement
You are given an array of size n. And the next line will contain n positive integers. Find the number of prime numbers in the array and find the average of all even integers in the array. Implement it using two functions(one is for prime and second one is for finding the average) and traverse the array using pointers.
See the sample input-output for more clarification.
Sample Input-
-----------------------
5
2 5 9 11 14
Sample Output-
-----------------------
Prime numbers: 3
Average of all even integers: 8.00
answer:
Here is a function in C that returns 1 if a number is prime, and 0 otherwise:
int is_prime(int n) {
if (n < 2) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
This function uses a loop to check if n
is divisible by any integer between 2 and the square root of n
. If n
is divisible by any of these integers, it returns 0. Otherwise, it returns 1.
Here is a function in C that calculates the average of all even integers in an array:
double average_of_evens(int *arr, int n) {
int sum = 0;
int count = 0;
for (int *p = arr; p < arr + n; p++) {
if (*p % 2 == 0) {
sum += *p;
count++;
}
}
return (double)sum / count;
}
This function uses a loop to iterate over the elements of the array, and for each even element it increments the sum and count. Finally, it calculates and returns the average by dividing the sum by the count.
To solve the problem, you can read the size of the array and the elements of the array from the input, and then use the is_prime
and average_of_evens
functions to count the number of prime numbers and calculate the average of the even integers.
Here is the complete program:
#include <stdio.h>
int is_prime(int n);
0 Comments