how do I get the minimum to print properly? - c

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.

Related

Find two largest numbers in input

I need to make a program that will perform the following task:
Enter N natural numbers. Complete the input with 0. Output the number
of the maximal number.
I have already done this, and you can see the code below:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num >= max) {
max = num;
max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place + 1);
return 0;
}
The teacher then made the task more difficult – the program needs to print the maximum number and the next maximum after it of the entered numbers.
How can I do it?
If you can use arrays and sort use that way. if not, this is in your code
int main(void) {
int i = 0, num, max_place = -1, second_max_place = -1;
int max = -2147483647;
int second_max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num == 0) break;
if (num >= max) {
second_max = max;
second_max_place = max_place;
max = num;
max_place = i;
}
if(num < max && num >= second_max){
second_max = num;
second_max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else{
printf("\nMax number was on %d place, bruh", max_place + 1);
printf("\nSecond Max number was on %d place, bruh", second_max_place + 1);
}
return 0;
}

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;
}

Min, Max, Mean program in 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;
}

How to write a program that calculates the average of the inputted positive numbers and ignores the negatives

Following are the problem, my code and my question:
Do not use an array to hold numbers that user enters in this exercise! Write a program that calculates average of positive numbers that user enters. Program asks user to enter numbers and calculates the average of entered numbers when user enters 0 as the number. The zero is not included in the average. If user enters a negative number the program must print a message telling that only positive numbers are accepted and ignore the negative number.
Here's most of the code written:
#pragma warning (disable:4996)
#include <stdio.h>
int main() {
int number;
int sum = 0;
printf("Please enter the 1st number or 0 to stop: ");
scanf("%d", &number);
int count = 0;
while (number != 0)
{
sum = sum + number;
count++;
printf("Please enter another number or 0 to stop: ");
scanf("%d", &number);
}
if (count < 0) {
printf("Only positive numbers\n");
}
if (count > 0)
{
printf("AVERAGE = %f", ((float)sum) / count);
}
}
SPECIFIC QUESTION:
If a user enters a negative number, how can I not let it affect the average and prompt the user to enter a positive number?
#include <stdio.h>
int main() {
int number;
int sum = 0;
printf("Please enter the 1st number or 0 to stop: ");
scanf("%d", & number);
int count = 0;
while (number != 0) {
if (number > 0) {
sum = sum + number;
count++;
} else {
printf("only positive numbers are accepted\n");
}
printf("Please enter another number or 0 to stop: ");
scanf("%d", & number);
}
if (count > 0) {
printf("AVERAGE = %f", ((float) sum) / count);
}
return 0;
}
You checked if the amount of times the user entered something is negative (which it can never be). Instead just make an if statement before u add the number to the sum.
#include <stdio.h>
int main() {
int number;
int sum = 0;
printf("Please enter the 1st number or 0 to stop: ");
scanf("%d", &number);
int count = 0;
while (number != 0)
{
if (number > 0) {
sum = sum + number;
} else {
printf("Only positive numbers\n");
}
count++;
printf("Please enter another number or 0 to stop: ");
scanf("%d", &number);
}
if (count > 0)
{
printf("AVERAGE = %f", ((float)sum) / count);
}
}
#include <stdio.h>
int main() {
int number;
int sum = 0;
int count = 0;
printf("Please enter the 1st number or 0 to stop: ");
scanf("%d", & number);
while (number != 0)
{
if (number > 0)
{
sum = sum + number;
count++;
}
else
{
printf("only positive numbers are accepted\n");
}
printf("Please enter another number or 0 to stop: ");
scanf("%d", & number);
}
if (count > 0)
{
printf("AVERAGE = %f", ((float) sum) / count);
}
if ( count == 0)
{
printf(" no numbers to calculate average.");
}
return 0;
}
The following code is working as desired :-
#include <stdio.h>
int main()
{
int number;
int sum = 0;
int count = 0;
printf("Please enter the numbers and enter 0 to stop ");
scanf("%d", &number);
while (number != 0)
{
if (number > 0) {
sum += number;
count++; // increase the count only when a positive number is entered
}
else {
printf("Enter only positive numbers\n");
}
printf("Please enter another number or 0 to stop: ");
scanf("%d", &number);
}
printf("AVERAGE = %f", ((float)sum) / count);
}
The problem with Rasumus' code is that it's increasing the count even when a negative number is entered, that will show erroneous average value.

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