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);
Related
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;
}
I am having trouble printing out the number of items entered and the average of this program and I am supposed to use a while loop can you help me figure out what I am doing wrong.
#include <stdio.h>
int main(void) {
double n;
int counter = 0;
double sum = 0.0, average;
scanf("%lf", &n);
while (1 != scanf("%lf", &n)) {
counter++;
scanf("%lf", &n);
sum = sum + n;
printf("%d", counter);
average = sum / counter;
printf("%lf", average);
}
return 0;
}
This is what it's supposed to look like
Input: 2.2 2.4 1.5 1.1 3.3 5.5 Q
Output: 6 2.666667
You should read the values in a loop, testing if scanf() returns 1 for successful conversion, update the sum and counter inside the body of the while loop and output the average and count after the end of the loop.
Here is a modified version:
#include <stdio.h>
int main(void) {
int counter = 0;
double n, sum = 0.0;
while (scanf("%lf", &n) == 1) {
counter++;
sum = sum + n;
}
if (counter == 0) {
printf("no values\n");
} else {
printf("%d %f\n", counter, sum / counter);
}
return 0;
}
There is too much redundancy in your code:
double n;
int counter = 0;
double sum = 0.0, average;
// you do not need the following initial read
// (see reconstructed while condition)
scanf("%lf", &n);
// replace the following line with "while (1)"
while (1 != scanf("%lf", &n)) {
// sth like the following if block is to be inserted to check end of input
if (scanf("%lf", &n) == 0) {
break;
}
counter++; // ok
// you do not need the following line
// if block takes care of the input
scanf("%lf", &n);
sum = sum + n; // ok
// better pull the remaining lines out of the while loop
printf("%d\n", counter); // better to insert '\n' here
average = sum / counter;
printf("%lf\n", average); // and here '\n'
}
return 0;
And btw, for the code above, your input layout had to be :
2.2
2.4
1.5
1.1
3.3
5.5
Q
A working example might be, like;
int main(void) {
double n;
int counter = 0;
double sum = 0.0, average;
while (1) {
if (scanf("%lf", &n) == 0) {
break;
}
counter++;
sum = sum + n;
}
printf("%d\n", counter);
average = sum / counter;
printf("%lf\n", average);
return 0;
}
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;
}
#include <stdio.h>
main()
{
int choice, no;
printf("1. Show sum of odd/even number to N term\n");
printf("2. Smallest, largest and average of the supplied numbers\n");
printf("3. Terminate the programs\n\n");
printf("Enter your choice[1|2|3]: ");
scanf("%d", &choice);
if (choice == 1)
{
int i , no , sum = 0, j, sum2 = 0;
printf("\nEnter any number: ");
scanf("%d", &no);
for (i = 2; i <= no; i = i + 2)
{
sum = sum + i;
}
printf("\nSum of all even number between 1 to %d = %d\n", no, sum);
for (j = 1; j <= no; j = j + 2)
{
sum2 = sum2 + j;
}
printf("Sum of all odd number between 1 to %d = %d\n", no, sum2);
}
else if(choice == 2)
{
float max, min, avg, num,counter=0, sum = 1;
printf("\nPlease enter all the number you want![0 to end]: ");
scanf("%f", &num);
max = min = num;
while (num != 0)
{
printf("Please enter all the number you want![0 to end]: ");
scanf("%f", &num);
if (max < num && num > 0)
max = num;
else if (min > num && num > 0)
min = num;
sum = sum + num;
counter++;
}
printf("\nThe smallest and largest of entered numbers are %.2f and %.2f respectively.\n", min, max);
avg = sum / counter;
printf("The sum of entered number is %.2f\n", sum);
printf("The average of entered number is %.2f\n", avg);
}
}
My problem is when i choose number 2 it will show smallest and largest number but the sum show wrongly when i enter large number like 200! But it work fine when i enter small value!?
small number
Big number
picture included
Your sum has never count the first input. With initial value sum = 1,
For your small numbers: your sum = (1 + 1 + 1 + 2) happens to be right.
But for your big numbers: your sum = (1 + 100 + 100 + 200 ) = 400.1 (you can see you missed the first input 100);
Your mistakes:
sum should be initialized as 0;
you did not count the first input (before loop): not calc sum nor counter++
when user finally input 0, you should not continue counter++ because '0' is not a valid input.
Your program has several issues:
You initialise the sum to 1, not to 0 as it ought to be.
You handle the first value and subsequent values differently. This is basically okay, but make sure that the treatment is the same in bothz cases. In your code, you assign min and max for the first value correctly, but miss incrementing the sum and the counter.
Your code doesn't check whethet a valid float has been entered. That means that it will hang if the user enters something that isn't a float. Your program should handle such input as if it were zero.
In theory, you should not divide by counter when it is zero. In practice, that doesn't happen, because you also account for the terminating zero in your counter.
Perhaps it would be better to treat the first value like all other values. You could then either initialise min and max to big and small values (for example ±FLT_MAX from <float.h>) or you could check count == 0 inside the loop to implement diferent behaviour for the first and the following values.
In that case, you could break out of an infinite loop when invalid input or zero was given. This might seem complicated, but leads to simpler code:
#include <stdio.h>
#include <float.h>
int main(void)
{
float max = -FLT_MAX; // minimum possible float value
float min = FLT_MAX; // maximum possible float value
float sum = 0.0f;
int count = 0;
for (;;) {
float num;
printf("Please enter all the number you want![0 to end]: ");
if (scanf("%f", &num) < 1 || num == 0) break;
if (max < num) max = num;
if (min > num) min = num;
sum += num;
count++;
}
if (count) {
float avg = sum / count;
printf("%d values\n", count);
printf("Smallest: %.2f\n", min);
printf("Largest: %.2f\n", max);
printf("Sum: %.2f\n", sum);
printf("Average: %.2f\n", avg);
}
return 0;
}
#include <stdio.h>
main()
{
int choice = 0;
for (;choice != 3;)
{
printf("_____________________________________________________________\n\n");
printf("1. Show sum of odd/even number to N term\n");
printf("2. Smallest, largest and average of the supplied numbers\n");
printf("3. Terminate the programs\n\n");
printf("Enter your choice[1|2|3]: ");
scanf("%d", &choice);
printf("_____________________________________________________________\n\n");
if (choice == 1)
{
int i, no, sumc1 = 0, j, sum2c1 = 0;
printf("\nEnter any number: ");
scanf("%d", &no);
for (i = 2; i <= no; i = i + 2)
{
sumc1 = sumc1 + i;
}
printf("\nSum of all even number between 1 to %d = %d\n", no, sumc1);
for (j = 1; j <= no; j = j + 2)
{
sum2c1 = sum2c1 + j;
}
printf("Sum of all odd number between 1 to %d = %d\n\n\n", no, sum2c1);
}
else if (choice == 2)
{
float counter, num, large, small, num2, sum = 0, avg;
printf("\nEnter first number[Enter 0 to stop]: ");
scanf("%f", &num);
num2 = num;
large = num;
small = num;
for (counter = 0; num != 0; counter++)
{
printf("Enter another number [Enter 0 to stop]: ");
scanf("%f", &num);
if (num > large && num > 0)
large = num;
if (num<small && num > 0)
small = num;
sum = sum + num;
}
sum = sum + num2;
avg = sum / counter;
printf("\nThe largest number is %.2f\n", large);
printf("The smallest number is %.2f\n", small);
printf("The sum of entered numbers are %.2f\n", sum);
printf("The average of entered number are %.2f\n\n\n", avg);
}
}
}
I just figured out the main problem thanks to all, although some of replies gave me full code, i have to use just simple code because i only started to learn the basic. thanks.
this code might be useful for someone.
//uniten.encik//
Well, the problem is the above. To sum it up, it compiles, but I guess my main idea is just wrong. What I'm trying to do with that code is:
I want the person to give us the elements of the array, how many he wants to (with a limit of a 100 elements).
After that, I'm checking what array positions are prime numbers.(ex: position 2,3,5,etc. Not the elements itself).
After that, I'm doing the average of the values in the prime numbers position.
That's it. Any ideas? Keep in mind that I'm on the first period of engineering, so I'm not the best in programming.
The code is below:
#include <stdio.h>
#include <windows.h>
int main(void)
{
int k, i, j, d, v[101], sum, prim, f;
float ave;
i = 0;
while ((i < 101) && (j != 0) )
{
i++;
printf("Set the value of the element %d => ", i);
scanf("%d", &v[i]);
printf("To stop press 0 => ");
scanf("%d", &j);
}
k = 0;
prim = 1;
f = i;
sum = 0;
while (f > 2)
{
if (i % (f - 1) == 0)
{
prim = 0;
}
else
{
k++;
sum = sum + v[f];
}
f = f - 1;
}
med = sum / k;
printf("%d, %d, %d", k, soma, i);
printf("The average is => %f \n", ave);
system("pause");
}
For those wondering, this is what i got after the editing in the correct answer:
int main(void)
{
int v[101];
int n = 0;
int k,j = 0;
int i=0;
int sum = 0;
while( i<100 )
{
i++;
printf ("Set the value of the element %d => ", i);
scanf ("%d", &v[i]);
int x,primo=1;
if (i>1){
for (x=2; x*x<=i; x++) {
if (i % x == 0) primo = 0;
}
if(primo==1)
{
sum = sum+ v[i];
n++;
}
}
printf ("To stop press 0 => ");
scanf ("%d", &j);
if(j == 0)
break;
}
float ave =(sum /n);
printf("%d, %d, %d", n,i,sum);
printf("The average is => %f \n", ave);
system("pause");
}
First lets make a readable method to test if a number is prime; this answer from another SO post gives us a good one:
int IsPrime(int number) {
int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
Second, let's clean your code, and compute a running sum of all the prime numbers encountered so far. Also, we will check the return values of scanf (but we should avoid scanf !)
And third, we add some indentation.
int main(void)
{
int n = 0;
int i = 0;
int j = 0;
int k = 0;
int sum = 0;
while( i<101 )
{
i++;
printf ("Set the value of the element %d => ", i);
if(scanf ("%d", &k) != 1)
continue;
if(is_prime(k))
{
sum += k;
++n;
}
printf ("To stop press 0 => ");
if(scanf ("%d", &j) == 1)
if(j == 0)
break;
}
float ave = sum / (double) n;
printf("The average is => %f \n", ave);
system("pause");
}
Well there are a few things to say. First the easy part: if the max number of integers allowed to read is 100 your variable "v" should be v[100]. This is not a char array, so this array don't need to have an extra element (v[100] will be an array of int that goes from v[0] to v[99]; adjust the loop limit too).
Also, you are checking if the number you have is prime in the variable f, but this var is assigned with the variable i and i is not an element of the array. You want to assign f something like v[i] (for i equal to 0 to the count of numbers read minus one). So you will need 2 loops: the one you are using now for checking if the number is prime, and another one that assigns v[i] to f.
Another thing to say is that you are calling scanf two times for reading, you could just read numbers and store it in a temporary variable. If this number is not zero then you store it in the array and keep reading, else you stop the reading.
By last I strongly recommend you set var names that make sense, use single letters only for the index variables; names like temp, array, max and countnumbers should appear in your code. It will be easier for you and everyone else to read your code, and you will reduce the number of mistakes.
Here's the solution to your problem. Very easy stuff.
/* C program to find average of all prime numbers from the inputted array(you can predefine it if you like.) */
#include <stdio.h>
#include <conio.h>
void main()
{
int ar[100], i, n, j, counter;
float avg = 0, numprime = 0;
printf("Enter the size of the array ");
scanf("%d", &n);
printf("\n Now enter the elements of the array");
for (i = 0; i < n; i++)
{
scanf("%d", &ar[i]);
}
printf(" Array is -");
for (i = 0; i < n; i++)
{
printf("\t %d", ar[i]);
}
printf("\n All the prime numbers in the array are -");
for (i = 0; i < n; i++)
{
counter = 0;
for (j = 2; j < ar[i]; j++)
{
if (ar[i] % j == 0)
{
counter = 1;
break;
}
}
if (counter == 0)
{
printf("\t %d", ar[i]);
numprime += 1;
avg += at[i];
}
}
avg /= numprime;
printf("Average of prime numbers is ℅f", avg);
getch();
}
You just need counter variables like above for all average computations. (Cause we need to know number of prime numbers in the array so we can divide the total of them and thus get average.) Don't worry about typecasting it is being done downwards... This solution works. I've written it myself.
Here is a cut at doing what you wanted. You don't need near the number of variables you originally had. Also, without knowing what you wanted to do with the prime number, I just output when a prime was encountered. Also as previously mentioned, using a function for checking prime really helps:
#include <stdio.h>
// #include <windows.h>
/* see: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime */
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
int main(void)
{
int i, v[101], sum, pcnt=0, psum=0;
float ave;
i=0;
printf ("\nEnter array values below, use [ctrl + d] to end input\n\n");
printf ("Set the value of the element %d => ", i);
while((i<101) && scanf ("%d", &v[i]) != EOF ){
sum += v[i];
if (IsPrime (v[i]))
psum += v[i], pcnt++;
i++;
printf ("Set the value of the element %d => ", i);
}
ave=(float)psum/pcnt;
printf("\n\n Number of elements : %d\n",i);
printf(" The sum of the elements: %d\n",sum);
printf(" The number of primes : %d\n",pcnt);
printf(" The average of primes : %f\n\n", ave);
return 0;
}
Sample Output:
Enter array values below, use [ctrl + d] to end input
Set the value of the element 0 => 10
Set the value of the element 1 => 20
Set the value of the element 2 => 30
Set the value of the element 3 => 40
Set the value of the element 4 => 51
Set the value of the element 5 => 11
Set the value of the element 6 => 37
Set the value of the element 7 =>
Number of elements : 7
The sum of the elements: 199
The number of primes : 2
The average of primes : 24.000000