Min, Max, Mean program in C - c

I'm trying to construct a program that will take a users positive input for number of values then scan for the users values and state those values (which can be negative), but if the user enters any letters the program is supposed to skip over them in the list of values. I also can't figure out how to have the program skip over a negative number for the number of values if accidentally inputed (in the first example -4 is accidentally inputed for number of values and skipped, then 4 is used for number of values followed by each value). I would appreciate the help!
Here is what I have so far:
#include <stdio.h>
#include <ctype.h>
int main() {
int i;
double userVal;
double userNum;
double min = 0;
double max = 0;
double sum = 0;
double average;
scanf("%lf", &userVal);
for (i = 1; i <= userVal; ++i) {
scanf("%lf", &userNum);
sum += userNum;
if (i == 1 || min > userNum)
min = userNum;
if (i == 1 || max < userNum)
max = userNum;
}
average = sum / userVal;
printf("The minimum value is %g, the maximum value is %g, and the average value is %g.\n",
min, max, average);
return 0;
}
Picture of output: https://i.stack.imgur.com/8q4YC.png

You can (and should) use the return from scanf. It returns the number of successful scans. It also returns EOF if there was an error.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
// helper function to read all characters up to and including a new line
void consume_line()
{
int c;
while ((c = getchar()) != '\n') {
// Error??
if (c == EOF) {
// Handle error. Maybe exit program?
puts("ERROR");
exit(0);
}
}
}
int main() {
int count;
double min = DBL_MAX;
double max = DBL_MIN;
double sum = 0;
do {
// Read an int. If failure, discard input
if (scanf("%d", &count) != 1) {
consume_line();
count = -1;
}
} while (count <= 0); // Loop until count > 0
int count2 = count; // Use a copy since count is needed later
while (count2 > 0) {
double userNum;
if (scanf("%lf", &userNum) == 1) {
// Success
sum += userNum;
count2--;
if (min > userNum) min = userNum;
if (max < userNum) max = userNum;
}
else {
// Failure
consume_line();
}
}
double average = sum / count;
printf("The minimum value is %g, the maximum value is %g, and the average value is %g.\n",
min, max, average);
return 0;
}

Related

How to get min/max value from 10 numbers with a loop? (C language)

Hi im fairly new in programming and started with C language and now im stuck with loops.
The problem is that I try to write a program that has to get an input value of 10 INT numbers that are greater than 20, and after that the program has to determine which of the numbers is the maximum and which is minimum. at the end it has to calculate the average of all numbers.
So now I managed to get only the average calculation to work correctly, and the main problem is the max/min values.
#include<stdio.h>
void main()
{
//Variables
int num, i = 1, cnt = 0, sum = 0, max = 0, min = 0;
float average;
printf("Enter 10 int numbers greater than 20:\n");
//Input check
while (i <= 10)
{
printf("\n%d) ", i);
scanf("%d", &num);
max = num;
min = num;
if (num <= 20)
{
printf("Wrong number! enter an integer greater than 20:\n");
continue;
}
i++;
sum += num;
cnt++;
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
//Average calculation and output
average = sum / (float)cnt;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average of all numbers is: %.2f\n", average);
}
Here is a quick check game in c that asks for few numbers and then when you enter 0 it shows you the lowest and highest number in the array (number collected)
int main(){
int a, max = 0, min;
char answer;
while(answer != 'n')
{
for(int i = 0; i < 100; i++){
printf("Enter Number:");
if (scanf("%d", &a) == 1)
{
if(a == 0) //check if the input value is 0 then break the loop
break;
else
{
if(a > max)
max = a;
if(a < min)
min = a;
}
}
}
printf("lowest: %d, highest: %d", min, max);
printf("\nWould you like to start over? (j/n): ");
scanf("%s", &answer);
max = 0;
//min=0;
if(answer == 'n')
break;
}
return 0;
}

how do I get the minimum to print properly?

This is supposed to ask the user to input a number than if the number is positive it outputs the number and adds one to the count and outputs the value of count (just for the most recent input value). if the number input is negative it just asks for a new number and if the input is 0 it outputs the count, minimum, maximum, sum and average for the entire run of the program.
I've gotten most of it working I'm just having trouble with getting the minimum value for the 0 scenario. I also get a runtime error for int min
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main() {
int input = 7;
int count = 0;
int sumInput = 0;
int lastInupt = 0;
int max;
int min;
double avg;
while (input != 0) {
printf("enter a number\n");
scanf("%i", &input);
if (input > 0) {
count++;
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
/*input1 = input;*/
sumInput += input;
//lastInupt = input;
}
else if (input < 0) {
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
}
if (input > lastInupt) {
if (input > max) {
max = input;
/*input1 = input;*/
}
}
if (lastInupt > input) {
if (min > input){
min = input;
}
}
/*while (min > 0)
{
if (input < min) {
min = input1;
}
}*/
}
avg = (float)sumInput / (float)count;
printf("you have entered %i positive numbers..\n", count);
printf("Sum of inputs: %i", sumInput);
printf("\nThe maximum # is: %i", max);
printf("\nThe average is: %.2lf", avg);
printf("\nThe minimum # is: %i", min);
getchar();
getchar();
return 0;
}
The code has to keep the same general format this is an assignment for my college.
Consider initializing both min and max and skip the lastInput variable.
int min = INT_MAX;
int max = INT_MIN;
.....
if (input > max)
max = input;
if (min > input)
min = input;
This should ensure that min and max are always initialized, and in the special case where the first and only input is 0 both min and max will get the value 0.
Because you initialize min to MAX_INT (the highest possible value for an int variable) the first iteration min > input will always evaluate to true and min will be updated. Similar for max and MIN_INT
if min and max only should be updated when input !=0 then modify the entire program to
int main() {
int input = 7;
int count = 0;
int sumInput = 0;
int max = INT_MIN;
int min = INT_MAX;
double avg;
while (input != 0) {
printf("enter a number\n");
scanf("%i", &input);
if (input > 0) {
count++;
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
sumInput += input;
if (input > max ) max = input;
if (input < min ) min = input;
}
else if (input < 0) {
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
}
}
if(count==0) { // only 0 entered.
printf("inform user she didnt enter any positive numbers");
} else {
avg = (float)sumInput / (float)count;
printf("you have entered %i positive numbers..\n", count);
printf("Sum of inputs: %i", sumInput);
printf("\nThe maximum # is: %i", max);
printf("\nThe average is: %.2lf", avg);
printf("\nThe minimum # is: %i", min);
}
getchar();
getchar();
return 0;
}
Since your runtime error was fixed, I will address the min == 0 issue.
When a 0 is input, it will fail the two first if statements input>0 and input < 0
But it still will try the last two if statements, and of course 0 will be less than the current min, so it will set min to 0 (incorrectly)
What you need to do is put this after the else if(input < 0) block
else{//input is 0
break;
}
So that it will skip checking if input is below min when input is 0. As you want to break from the loop at this point anyway.

Coding for multiple modes in C?

My assignment is to find all possible modes for a set of numbers (0 to 100).
We were told to do so using arrays and also to count the frequency that each number occurs.
I've coded for the mode, however, my program does not work is there are multiple modes (example: 1, 2, 7, 7, 9, 10, 7, 2, 2. In this stance, 2 and 7 are both the mode and my program needs to print both of them, but mine doesn't).
I think I might have to make another array set, but I'm not sure? Any advice would be appreciated.
Here is what I have:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) { //setting all values to 0
c[i] = 0;
i = i + 1;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) { // counting how often each score appears
c[x] = c[x] + 1;
if (c[x] >= mode) {
mode = x;
}
scanf("%d", &x);
}
printf("THE MODE(S) ARE %d\n", mode);
i = 0;
while (i <= 100) { //printing all values so long as they've occurred at least once
if (c[i] > 0) {
printf("%d occurs %d times\n", i, c[i]);
}
i = i + 1;
}
}
You have to count the highest frequency of any number and if that frequency equals the frequency of any other number then that number will also be mode.
So the changes that you need to do are:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) //setting all values to 0
{
c[i] = 0;
++i;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) // counting how often each score appears
{
c[x] = c[x] + 1;
if (c[x] >= mode)
{mode = c[x];}
scanf("%d", &x);
}
for(i=0;i<=100;i++){//printing all values having highest frequency
if (c[i]==mode)
{
printf("THE MODE(S) ARE %d\n", i);
}
i = 0;
while (i<=100) //printing all values so long as they've occurred at least once
{
if (c[i] > 0)
{
printf("%d occurs %d times\n", i, c[i]);
}
++i;
}
}
Instead of determining the mode in the main entry loop, you should determine the maximum count. Then you can print all values with this count of occurrences in a final loop.
You should also check the return values of scanf().
I would also advise to use an initializer for the array to avoid a loop and to use for loops that more clearly identify the initialization, test and increment of the loop index.
Here is a corrected version of your code:
#include <stdio.h>
int main() {
int x, i, c[101] = { 0 }, max_repeat;
printf("please enter test scores between 0 and 100\n");
max_repeat = 0;
// read the test scores and compute the maximum repeat count
while (scanf("%d", &x) == 1 && x >= 0 && x <= 100) {
c[x] += 1;
if (max_repeat < c[x]) {
max_repeat = c[x];
}
}
printf("The mode(s) are");
for (i = 0; i <= 100; i++) {
if (c[i] == max_repeat) {
printf(" %d", i);
}
}
printf("\n");
return 0;
}

How do I write a program that reads array in from text file and finds max and min?

I have been tasked with writing a code that reads numbers in from a txt file array and finding the max, min, sum etc. The (200) numbers are in the format:
3.23
19.398
98.73
2.1
...
Sorry if the code is a bit of a mess, I've been trying to piece together a lot of different tutorials to no avail. I basically need to know how to get the code to read the values sequentially, and pull out the max/min values and keep going through the array. (and find sum along the way) How do I format this correctly?
# include <stdio.h>
int main()
{
//char data[200];
int newnum;
int max = 0, min = 99999999999;
int i = 0;
int y[200];
//min=max=newnum;
FILE *fpdata = fopen("data.txt", "r");
if((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while(fscanf(fpdata,"%f", &y[i++]) != EOF);{
//for(i=0; i < 200; i++)
i--;
printf("i=%d \n", i);
//printf("\n%d%d\n", &y[i++], y);
if(newnum > max)
max = newnum;
if(newnum < min)
min = newnum;
}
printf("The largest number is %d\n", max);
printf("The smallest number is %d\n", min);
fclose(fpdata);
return 0;
}
Any help would be greatly appreciated, I've tried utilizing all possible resources (youtube, other stackoverflow questions) for hours but none explicitly lay out how to format the call in array from the file, read, and pluck values from it.
There are many issues:
You probably want this:
#include <stdio.h>
#include <stdlib.h> // include also stdlib.h
int main()
{
float newnum;
float max = 0, min = 99999999999; // use float type for float numbers
int i = 0;
FILE *fpdata; // callign fopen only once
if ((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while (fscanf(fpdata, "%f", &newnum) != EOF) { // removed extra ;
printf("i = %d, newnum = %f\n", i++, newnum); // reading into newnum
// correct format specifiers
if (newnum > max)
max = newnum;
if (newnum < min)
min = newnum;
}
printf("The largest number is %f\n", max); // correct format specifiers
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}
There is still room for improvments though.
Here is the version that first reads all the data into the data array (data is a nicer name than y) and then does the calculation:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float max = 0, min = 99999999999;
float data[200];
FILE *fpdata;
if ((fpdata = fopen("input1.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
int nbofnumbers = 0;
while (fscanf(fpdata, "%f", &data[nbofnumbers]) != EOF)
{
nbofnumbers++;
}
for (int i = 0; i < nbofnumbers; i++)
{
printf("data[%d] = %f\n", i, data[i]);
if (data[i] > max)
max = data[i];
if (data[i] < min)
min = data[i];
}
printf("The largest number is %f\n", max);
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}
Some issues with your code:
You scan for float but store data as int
You open the file twice
You have an unintended ; at the end of the while
The loop condition (i.e. != EOF) may cause an infinite loop in the file contains something that can't be parsed as a float. Using == 1 is safer.
Your initialization of max and min can be improved
After fixing that the program could be:
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
int main(void)
{
float newnum;
float max = -FLT_MAX;
float min = FLT_MAX;
FILE *fpdata;
if((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while(fscanf(fpdata,"%f", &newnum) == 1)
{
printf("%f\n", newnum);
if(newnum > max) max = newnum;
if(newnum < min) min = newnum;
}
printf("The largest number is %f\n", max);
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}

how to find the min/max of values within a file

#include <stdio.h>
int main(void)
{
int num, i, total, average, min, max;
min = num;
max = num;
FILE *ifile;
ifile = fopen("scores.txt", "r");
i = total = 0;
while (fscanf(ifile, "%d", &num) != EOF) {
i++;
total += num;
}
printf("The total of the integers is %d.\n", total);
printf("The number of integers in the file is %d.\n", i);
average = total/i;
printf("The average of the integers is %d.\n", average);
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min) {
printf ("The minimum is %d\n", min);
} else if (num > max) {
printf ("The maximum is %d\n", max);
}
}
fclose(ifile);
return (0);
}
The part of the code that's wrong is the very end about mins/maxes.
I'm not sure whether to put in a loop for this or to even make min and max variables themselves.
There are at least three issues in your min/max-detection loop:
First, as indicated by chux, min and max are not initialized; hence, when iterating through the numbers, statement if (num < min)... is far from guaranteed to work properly (same for max, of course).
So initialize min with INT_MAX, and initialize max with INT_MIN (both defined in <limits.h>), such that already in the first iteration min and max will be set to values from your file.
Second, the check for if (num < min)... gives you a "local" minimum, i.e. the minimum for all the numbers read so far, but not the "absolute" minimum, as there may come smaller numbers at a later point. So min/max will be valid at the end of the loop, not during the iteration.
Third, if (num < min) ... else if (num > max) is wrong at least if the file contains just one number.
Your code could look like the following:
int min = INT_MAX;
int max = INT_MIN;
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min)
min = num;
if (num > max)
max = num;
}
// min/max are valid earliest at this point:
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
// Note that min/max will not be correct if the file does not contain any number;
// Note further, that fscanf(ifile, "%d", &num) != EOF may result in an endless loop if the file contains characters that "%d" will not read as a valid integral value.
// But this is left to the OP for further improvement :-)
Consider the following modification to your code:
#include <stdio.h>
int main(void) {
int num, i, total, average, min, max;
// open file
FILE *ifile = fopen( "scores.txt", "r" );
// if opening file fails, print error message and exit 1
if (ifile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
// initialize i and total to zero.
i = total = 0;
// read values from file until EOF is returned by fscanf,
// or until an error (hence the comparison "== 1")
while(fscanf(ifile, "%d", &num) == 1) {
// In first round of loop, initialize min and max
// to the number being read (num)
// After min/max have been initialized, they can then
// be compared and modified in the second if statement
// in the remaining loop rounds
if (i == 0) {
min = num;
max = num;
total += num;
++i;
continue;
}
if (num < min) {
min = num;
} else if (num > max) {
max = num;
}
total += num;
++i;
}
// initialize average
average = total/i;
// summary
printf("The sum of all integers in file is %d.\n", total);
printf("The number of integers in file is %d.\n", i);
printf("The average of all integers in file is %d.\n", average);
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
fclose(ifile);
return 0;
}

Resources