C PROGRAM
Program to find the average of prime numbers |C Program|
Introduction
Prime numbers are fundamental in mathematics and find applications in various fields including cryptography and computer science. In this blog post, we'll explore a C program that computes the average of prime numbers up to a given input. We'll delve into the code, understand its components, and discuss how it works.
Let's break down the key steps:
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
Conclusion
In this blog post, we dissected a C program that calculates the average of prime numbers. Understanding this code helps grasp fundamental concepts of loops, conditions, and function usage in C programming. It also illustrates the process of finding prime numbers and computing averages in a structured manner, offering valuable insights for those learning C programming.
Post a Comment
0 Comments