In my code, the program will not allowed the negative number entered, the program will stop reading, then calculate the maximum value, minimum value and average value.
That is my code
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
int length = sizeof(age) / sizeof(age[0]);
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
Please enter ages: 5 -1
expected result: max:5;min:5,average:5;
actual result: max:5;min:-1,average: 0.4;
That was a question that I met, the code should not accept any negative value.
Thank you all.
but if I add age[i] = 0; then break;
The average value will equal to 0.5.
You don't need an array.
You don't need both a loop variable and a length.
It's more appropriate to use ? : for updating minimum/maximum.
You don't need two loops
You need to check the int return value of scanf(), which indicates the number of items successfully scanned, so it should be 1. I'll leave that for you/OP to add (hint: replace for-loop by while-loop to avoid having to add a separate length variable again).
int main(void)
{
printf("Please enter ages: \n");
int minimum = INT_MAX;
int maximum = 0;
int sum = 0;
int count = 0;
for (count = 0; count < 10; count++)
{
int age;
scanf("%d", &age);
if (age < 0)
{
break;
}
sum += age;
minimum = (age < minimum) ? age : minimum;
maximum = (age > maximum) ? age : maximum;
}
if (count > 0)
{
printf("Min: %d\n", minimum);
printf("Max: %d\n", maximum);
printf("Avg: %.1f\n", (float)sum / count);
}
else
{
printf("You didn't enter (valid) age(s).\n");
}
return 0;
}
Your approach is overly complicated and wrong.
You want this:
...
int length = 0; // declare length here and initialize to 0
for (int i = 0; i < sizeof(age) / sizeof(age[0]); i++) {
scanf("%d", &age[i]);
if (age[i] < 0) // if it is negative number, it is should stop reading
break;
length++; // one more valid number
}
// now length contains the number of numbers entered
// the rest of your code seems correct
You also might need to handle the special case where no numbers are entered, e.g: the only thing entered is -1. It doesn'make sense to calculate the average or the largest/smallest number when there are no numbers.
A possible solution could be:
(corrections are written in the commented code)
#include <stdio.h>
int main(void){
int arraySize = 10;
int age[arraySize]; //initialize not required
//the number of existing values inside the array (effective length)
int length = 0;
printf("Please enter ages: \n"); // allow user to enter numbers
for(int i=0; i<arraySize; i++){
scanf("%d",&age[i]);
// if it is negative number, it is should stop reading
if(age[i]<0){ break; }
//the else-if is not required
//but, if the compiler goes here,
//it means that the value is acceptable, so
length++;
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for(int j=0; j<length; j++){
if(maximum<age[j]){ maximum = age[j]; }
else if(minimum>age[j]) { minimum = age[j]; }
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
OP's primary problem is the 2nd loop iterates 10 times and not i times (the number of times a non-negative was entered.
For fun, let us try a non-floating point solution as it really is an integer problem.
An array to store values is not needed.
#include <limits.h>
#include <stdio.h>
int main(void) {
// Keep track of 4 things
int min = INT_MAX; // Set min to the max int value.
int max = INT_MIN;
long long sum = 0; // Use wide type to cope with sum of extreme ages.
int count = 0;
#define INPUT_N 10
printf("Please enter ages: \n");
for (count = 0; count < INPUT_N; count++) {
int age;
if (scanf("%d", &age) != 1) {
fprintf(stderr, "Missing numeric input.");
return EXIT_FAILURE;
}
if (age < 0) {
break;
}
if (age < min) min = age;
if (age > max) max = age;
sum += age;
}
if (count == 0) {
fprintf(stderr, "No input.");
return EXIT_FAILURE;
}
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
// Could use FP and
// printf("Average: %.1f\n", 1.0 *sum / count);
// But for fun, how about a non-FP approach?
#define SCALE 10
#define SCALE_LOG 1
sum *= SCALE; // Scale by 10 since we want 1 decimal place.
// Perform a rounded divide by `count`
long long average_scaled = (sum + count/2) / count;
// Print the whole and fraction parts
printf("Average: %lld.%.*lld\n",
average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);
return 0;
}
First of all, you must record how many positive numbers you enter. Then the value of length will be correct.
Second, for the second for loop, j must be smaller than the number of positive ages. Therefore, you won't add negative age[j] to average.
You can simply modify the second for loop.
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
int length = 0;
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
length++;
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
if ( age[j] > 0.0 )
{
average += age[j];
}
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
Related
This program is supposed to end when the user enters 0 and then show the count, sum, average, min and max. I am able to figure out the sum count and average but my min and max isn't working.
int main()
{
int number = 0;
int count = 0;
int sum = 0;
int average;
int min = 0;
int max = 0;
do {
printf("Enter a number: ");
scanf_s("%d", &number);
if (number > 0)
{
count = count + 1;
sum += number;
min = number;
max = number;
}
average = sum / count;
if (number < min)
{
min = number;
}
else if (number > max)
{
max = number;
}
} while (number != 0);
printf("count: %d\n", count);
printf("Sum: %d\n", sum);
printf("average: %d\n", average);
printf("Minimum: %d\n", min);
printf("Maximum: %d\n", max);
system("pause");
}
First, initialize min and max with proper values.
int min = INT_MAX;
int max = INT_MIN;
Second, update min only when the input number less than current min.
Update max only when the input number is greater than the current max.
int main()
{
int number = 0;
int count = 0;
int sum = 0;
int average;
int min = INT_MAX; // don't forget to include limits.h
int max = INT_MIN;
do {
printf("Enter a number: ");
scanf_s("%d", &number);
if (number > 0)
{
count = count + 1;
sum += number;
if (number < min)
{
min = number;
}
if (number > max)
{
max = number;
}
}
else if (number < 0)
{
printf("Negative value entered...skipping");
}
} while (number != 0);
printf("count: %d\n", count);
printf("Sum: %d\n", sum);
average = sum / count;
printf("average: %d\n", average);
printf("Minimum: %d\n", min);
printf("Maximum: %d\n", max);
system("pause");
}
You need to do two things:
Remove min = number; and max = number from the check number > 0. This is because, you are overriding the variables with the number value. This will lead to loss of previous min and max values, if any.
Instead of int min = 0; and int max = 0, use the upper and lower
limit for integer data type. That is present in limits.h. You can use INT_MAX (2147483647) and INT_MIN (–2147483648).
There is another problem with your code. instead of else if (number > max), it should be if (number > max). For every number you need to check for both min and max values.
Also, the condition if (number > 0) should instead be if (number != 0). This is because you want the program to end when user enters
0, so for it to accept negative numbers that condition has to be
changed.
Also, you need not calculate average every single time. Instead
you can calculate after coming out of the loop.
Also, you need to move the checks for min and max inside the check
number != 0. The reason for this is that you don't want to calculate min and max when number == 0.
You used:
if (number > 0)
{
count = count + 1;
sum += number;
min = number;
max = number;
}
Here, don't use:
min = number;
max = number;
Because, when number is greater than 0, min and max value will be set to the input number so the if and else if statement below it, will not work.
Set the first number that scanf reads as initial value of min and initial value of max;This will always work whatever the numbers are.
if (count==1)
{
min=number;
max=number;
}
'm currently writing a C program that prompts a user to enter five numbers and to display the maximum number. So here's what i came up with
int max_num(float num_arr[])
// this is a number array
{
int max = 0;
for (int k = 0; k <= 4; k++)
{
max = num_arr[0];
if (max > num_arr[k])
{
max = num_arr[k];
printf("The maximum number is is %d\n", max);
}
}
}
Any help is appreciated.
Your function will not work for numbers entered less than 0, also int type is wrong for the fuunction since it's not returning anything. Here is a better version of the same:
void max_num(float num_arr[], int size)
{
if(size>0) float max = num_arr[0];
for (int k = 0; k <= size; k++) {
if (max < num_arr[k]) {
max = num_arr[k];
}
}
printf("The maximum number is %f\n", max);
}
And if you need to return max:
float max_num(float num_arr[], int size)
{
if(size>0) float max = num_arr[0];
for (int k = 0; k <= size; k++) {
if (max < num_arr[k]) {
max = num_arr[k];
}
}
return max;
}
You are setting
max = num_arr[0];
in every loop iteration, so you are losing the max value every time and set it
to the first value in the array.
The correct version is:
for(int k = 0;k<5;k++)
{
if(num_arr[k] > max)
max = num_arr[k];
}
printf("The maximum number is is %d\n", max);
Having a <= in the condition is not incorrect, but it's not very readable either,
it's hard to miss the = sign. It's always better to just use <, in this case
k<5.
Also it's better practice to pass the size of the array to the functions, so you
don't have to hard code the maximal number of items to loop through (like you
did in your code). Like this:
#include <stdio.h>
float max_num(float *array, size_t len)
{
if(array == NULL)
{
fprintf(stderr, "invalid argument, array == NULL\n");
return 0;
}
if(len == 0)
{
fprintf(stderr, "Invalid array size, cannot be 0\n");
return 0;
}
float max = array[0];
for(size_t i = 0; i < len; ++i)
{
if(array[i] > max)
max = array[i];
}
return max;
}
int main(void)
{
float nums[] = { 1.1, -2.2, 8, 6, 99 , -12 };
float max = max_num(nums, sizeof nums / sizeof *nums);
printf("The maximal number in the array is: %f\n", max);
return 0;
}
Rather than if(max > num_arr[k]) it should be if(num_arr[k] > max)
I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.
So I'm coding in C, and I need to come up with code that will take n numbers from the user, and find their minimum, maximum, average, and sum of squares for for their values. So far I have the average and sum of squares portion, but the minimum and maximum is biting me.
Keep in mind I'm at a very rudimentary level, and I have not reached arrays yet. All I know are logical operators, functions, loops, and the use of the stdlib.h, math.h, and stdio.h libraries.
This is what I have so far.
The average function gave me a lot of problems when I tried to put float and double during compiling, so multiply it by a 1.0 fixed that. I have everything, just the minimum and maximum. I keep getting the last entry as my maximum, and a 0 for my minimum.
#include<stdio.h>
int main()
{
float average;
int i, n, count=0, sum=0, squaresum=0, num, min, max;
printf("Please enter the number of numbers you wish to evaluate\n");
scanf_s("%d",&n);
printf("Please enter %d numbers\n",n);
while(count<n)
{
min=0;
max=0;
if(num>max)
max=num;
if(num<min)
min=num;
scanf_s("%d",&num);
sum = sum+num;
squaresum = squaresum + (num*num);
count++;
}
average = 1.0*sum/n;
printf("Your average is %.2f\n",average);
printf("The sum of your squares is %d\n",squaresum);
printf("Your maximum number is %d\n",max);
printf("Your minimum number is %d\n",min);
return(0);
}
Your algorithm is not quite right. Below is the correct implementation:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void)
{
float average;
int n, num, count = 0, sum = 0, squaresum = 0;
int min = INT_MAX, max = INT_MIN;
bool gotAnswer = false;
/* Don't Let User Enter Wrong Input */
while(!gotAnswer)
{
printf("Please enter the number of numbers you wish to evaluate: ");
if(scanf_s("%d", &n) != 1)
{
/* User Entered Wrong Input; Clean Up stdin Stream*/
while(getchar() != '\n')
{
continue;
}
}
else
{
/* User Input Was Good */
gotAnswer = true;
}
}
/* Clear stdin Stream Just In Case */
while(getchar() != '\n')
continue;
while(count < n)
{
/* Don't Let User Enter Wrong Input */
gotAnswer = false;
printf("Enter number %d: ", count + 1);
if(scanf_s("%d", &num) != 1)
{
/* User Entered Wrong Input; Clean Up stdin Stream */
while(getchar() != '\n')
continue;
/* Let User Try Again */
continue;
}
else
{
/* User Input Was Correct */
gotAnswer = true;
/* Clear stdin Stream Just In Case */
while(getchar() != '\n')
continue;
}
if(num > max)
max = num;
if(num < min)
min = num;
sum += num;
squaresum += num * num;
count++;
}
average = 1.0 * sum / n;
printf("Your average is %.2f\n", average);
printf("The sum of your squares is %d\n", squaresum);
printf("Your maximum number is %d\n", max);
printf("Your minimum number is %d\n", min);
system("pause");
return 0;
}
I've added error checking and recovery. Please ask if you have any questions about the logic.
The way your code is currently written, min has to start out at a high value (not 0), or the code won't work. The best value to choose is the maximum possible value for an int.
You should also consider whether or not you want to reset these variable each time through the loop.
Enter the first num outside the loop and assign that to max min
scanf("%d",&num);
max = min = num;
Change your while loop to infinite loop
while(1) {...}
and now check for the condition that whether your counter count is equal to n is or not to break out from the infinite loop
if(count == n)
break;
Full code after modification:
#include<stdio.h>
int main()
{
float average;
int i, n, count=0, sum=0, squaresum=0, num, min, max;
printf("Please enter the number of numbers you wish to evaluate\n");
scanf_s("%d",&n);
printf("Please enter %d numbers\n",n);
scanf_s("%d",&num);
max = min = num;
while(1)
{
if(num>max)
max=num;
if(num<min)
min=num;
sum = sum+num;
squaresum = squaresum + (num*num);
count++;
if(count == n)
break;
scanf_s("%d",&num);
}
average = 1.0*sum/n;
printf("Your average is %.2f\n",average);
printf("The sum of your squares is %d\n",squaresum);
printf("Your maximum number is %d\n",max);
printf("Your minimum number is %d\n",min);
return(0);
}
Assume your first number in the list as the minimum and maximum.
Compare every next character with the current minimum and the current maximum and update accordingly.
your while loop should look like
min=3;
max=0;
while(count<n)
{
scanf("%d",&num);
if(num>max)
max=num;
if(num<min)
min=num;
sum = sum+num;
squaresum = squaresum + (num*num);
count++;
}
And I agree with Robert Harvey♦.. You must set min
Add a boolean, moved giving the values min, max 0 are the start of loop
#include<stdio.h>
int main()
{
float average;
int i, n, count=0, sum=0, squaresum=0, num, min, max;
bool first = true;
printf("Please enter the number of numbers you wish to evaluate\n");
scanf_s("%d",&n);
printf("Please enter %d numbers\n",n);
min=0;
max=0;
while(count<n)
{
scanf_s("%d",&num);
if (first) {
first = false;
min = max = num;
}
if(num>max)
max=num;
if(num<min)
min=num;
sum = sum+num;
squaresum = squaresum + (num*num);
count++;
}
average = 1.0*sum/n;
printf("Your average is %.2f\n",average);
printf("The sum of your squares is %d\n",squaresum);
printf("Your maximum number is %d\n",max);
printf("Your minimum number is %d\n",min);
return(0);
}
Should also consider to check the return value of scanf
There're some issues in your code:
Where num is read? You should do it before min and max
When while loop executes first time you should just assign num to max and min.
Something like that:
int min = 0;
int max = 0;
// If your compiler supports C99 standard you can put
// bool first_time = true;
int first_time = 1;
while (count < n) {
printf("Please, enter the next number\n");
scanf_s("%d", &num);
// If your compiler supports C99 you can put it easier:
// if (first_time) {
if (first_time == 1) {
first_time = 0;
max = num;
min = num;
}
else {
if(num > max)
max = num;
if(num < min)
min = num;
}
...
int marks , marks_count=0 , max=0 , min=100 , marks_number=1;
float total , avg;
printf("Hit enter to input marks of 10 student.\n\n");
getchar();
do
{
printf("Input %d Mark : " , marks_number);
scanf("%d" ,& marks);
if (marks>max)
{
max=marks;
}
else if (marks<min)
{
min=marks;
}
marks_count++;
marks_number++;
total=total+marks;
}
while (marks_count<10);
while (marks_number<10);
avg=total/marks_count;
printf("\n\nAverage marks are : %.2f\n" , avg);
printf("Maximum marks are : %d\n" , max);
printf("Minimum marks are : %d\n\n\n" , min);
You can use this code, it checks if the loop starts for the first time or not. If it runs for the first time it assigns the value of n to the minimum and the maximum variable and after that, it continues. When it runs a second time it checks and finds that the program runs a second time thus it does not initialize the variables with the value of n without comparing.
int n, limit, sum = 0, minimum, maximum;
float average;
bool firstTime = "true";
printf("\nEnter Limit: ");
scanf("%d", &limit);
printf("\nEnter %d numbers: \n", limit);
for (int i = 0; i < limit; i++)
{
scanf("%d", &n);
if (firstTime)
{
minimum = n;
maximum = n;
firstTime = false;
}
if (minimum > n)
{
minimum = n;
}
if (maximum < n)
{
maximum = n;
}
sum = sum + n;
}
average = sum / limit;
printf("\nMinimum: %d", minimum);
printf("\nMaximum: %d", maximum);
printf("\nSum: %d", sum);
printf("\nAverage: %.3lf", average);
I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}