Program to find the average of prime numbers |C Program|
Introduction
Algorithm
Include Necessary Headers:
Include necessary header files stdio.h and conio.h.
Function Declaration:
Declare a function named average that takes an integer parameter x
Main Function:
- Declare an integer variable n.
- Clear the console screen (using clrscr())
- Prompt the user to enter a number.
- Read the input number into variable n.
- Call the average function with the user-input number.
- Wait for a key press before closing the console (using getch()).
Average Function:
- Declare variables for loop control (i and j), a flag (flag), and variables for sum (sum) and count (count).
- Print a message indicating that prime numbers will be displayed.
- Iterate through numbers from 2 to the input number (x).
- Check if each number is prime using a nested loop.
- If a number is prime, print it, update the sum and count, and calculate the average within the loop.
- After the loop, print the calculated average.
// Program to find the average of prime numbers
#include<stdio.h>
#include<conio.h>
void average(int x);
void main() {
int n;
clrscr();
printf("enter a number:\n");
scanf("%d", &n);
average(n);
getch();
}
void average(int x) {
int i, j, flag;
float result, sum = 0, count = 0;
printf("the prime numbers are:\n");
for (i = 2; i <= x; i++) {
flag = 0;
for (j = i - 1; j > 1; j--) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d\n", i);
sum = sum + i;
count++;
}
result = (sum / count);
}
printf("the avg of these prime numbers are=%2f", result);
getch();
}
Output
// Output
enter a number:
5
the prime numbers are:
2
3
5
the avg of these prime numbers are=3.333333
Post a Comment
0 Comments