Min and max in C using basics - c

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

Related

is there any problem in my minimum number finding?

The code is to find maximum and minimum number, so i make this code
// find maximum and minimum in array
#include <stdio.h>
int main () {
int values[5]; // I take the size of array as 5
int i, max = values[0], min = values[0]; // and gives max and min 0
// index position in the array
printf ("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf ("%d", &values[i]);
}
for (i = 0; i < 5; i++) {
if (values[i] < min) {
min = values[i];
}
if (values[i] > max) {
max = values[i];
}
}
printf ("The maximum number is: %d", max);
printf ("\nThe minimum number is: %d", min);
return 0;
}
everything is fine maximum showing the maximum value but the minimum showing always 0. I need to put values in minus to show minimum values. help please.

Find the maximum, minimum, and average values in the array

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

How do you get the largest number and smallest number in a For-Loop function, The problems asks for a 10 number input and count specific type numbers

Hey guys I'm trying to figure this problem which counts as specific type of numbers yet I cant seem to get the largest and smallest number as stated on the problem, p.s we are not allowed to use lists or what so ever that would make the code easier, we're on controlled structures and if statements atm. Here's the problem "Input 10 integers. Display the total count of positive, negative, odd numbers, even numbers, largest and smallest numbers"
#include <stdio.h>
int main()
{
int numInput;
int count;
int result = 0;
int postiveNum = 0, negativeNum = 0, oddNum = 0, evenNum = 0, largestNum = 0, smallestNum = 0;
printf("Please input a number: \n");
for(count = 1; count <= 10; count++)
{
scanf("%d", &numInput);
if (postiveNum >= postiveNum)
{
largestNum = postiveNum;
}
if(postiveNum <= postiveNum)
{
smallestNum = postiveNum;
}
if(numInput > 0)
{
postiveNum++;
}
if(numInput < 0)
{
negativeNum++;
}
if(numInput % 2 != 0)
{
oddNum++;
}
if(numInput % 2 == 0)
{
evenNum++;
}
};
printf("Positive Numbers: %d\n", postiveNum);
printf("Negative Numbers: %d\n", negativeNum);
printf("Odd Numbers: %d\n", oddNum);
printf("Even Numbers: %d\n", evenNum);
printf("Largest Number: %d\n", largestNum);
printf("Smallest Number: %d\n", smallestNum);
}
You could do something like this
#include <stdio.h>
int main() {
int numInput;
int count;
// initialize largest and lowest num with NULL
int positiveNum = 0, negativeNum = 0, oddNum = 0, evenNum = 0, largestNum = NULL, smallestNum = NULL;
// get 10 numbers as input
for (count = 1; count <= 10; count++) {
printf("Please input a number: \n");
scanf("%d", &numInput);
// if its the first iteration, initialize largest and lowest num with first input value
// then compare the values from next iteration onwards
if (count == 1) {
smallestNum = numInput;
largestNum = numInput;
} else {
// if input num is less than smallest num, rewrite the value
if (numInput < smallestNum)
smallestNum = numInput;
// if input num is greater than the largest num, rewrite the value
if (numInput > largestNum)
largestNum = numInput;
}
// a number can't be positive and negative at the same time so use if else
if (numInput < 0)
negativeNum++;
else
positiveNum++;
// a number can't be even and odd at the same time so use if else
if (numInput % 2 == 0)
evenNum++;
else
oddNum++;
};
printf("Positive Numbers: %d\n", positiveNum);
printf("Negative Numbers: %d\n", negativeNum);
printf("Odd Numbers: %d\n", oddNum);
printf("Even Numbers: %d\n", evenNum);
printf("Largest Number: %d\n", largestNum);
printf("Smallest Number: %d\n", smallestNum);
}
You have to compare different variables in the if statement, change
if (postiveNum >= postiveNum){
largestNum = postiveNum;
for
if (numInput > largestNum){
// you should compare to the variable you want to change inside the if statement
largestNum = numInput;
}
the same for the smallest
if (numInput < smallestNum){
smallestNum = numInput;
}
Also the largestNum should be initialized as the minimum posible.
The same goes for smallestNum, but with the maximum posible.
This considering that the user could input just negative numbers and none of them will be > 0 and your program will print 0 as the minimum number, even tho you never input that number.
Way to find the largest number amongst given input number
I assume there's an input range.
Initialize the variable largestNum with the min number of that range.
Then for each input compare largestNum with that input and update the value of largestNum accordingly.
Way to find the smallest number amongst given input number
Apply the same procedure for finding the smallest number.
The difference is, here you've to initialize the variable smallestNum with the max number of the input range.
Note: I've considered max input range as -10^6 >= input <= 10^6. Change it according to your problem requirement.
Here's a possible sample code -
#include <stdio.h>
#define MIN_NUMBER -1000000
#define MAX_NUMBER 1000000
int main()
{
int numInput;
int count;
int result = 0;
int postiveNum = 0, negativeNum = 0, oddNum = 0, evenNum = 0, largestNum = MIN_NUMBER, smallestNum = MAX_NUMBER;
for(count = 1; count <= 10; count++)
{
printf("Please input a number: \n"); // print it before taking every input
scanf("%d", &numInput);
if (numInput > largestNum)
{
largestNum = numInput;
}
if(numInput < smallestNum)
{
smallestNum = numInput;
}
if(numInput > 0)
{
postiveNum++;
}
if(numInput < 0)
{
negativeNum++;
}
if(numInput % 2 != 0)
{
oddNum++;
}
if(numInput % 2 == 0)
{
evenNum++;
}
}
printf("Positive Numbers: %d\n", postiveNum);
printf("Negative Numbers: %d\n", negativeNum);
printf("Odd Numbers: %d\n", oddNum);
printf("Even Numbers: %d\n", evenNum);
printf("Largest Number: %d\n", largestNum);
printf("Smallest Number: %d\n", smallestNum);
}

MAX AND MIN IN RANDOM NUMBER

I need to write a C program to :
1. fills a 20 elementary array(marks) with random numbers between 0 and 100
2. print the number out 8 to a line.
3. Prints out the max and min and the average of the numbers.
I wrote following program and every thing is ok except min, I dont know how could I do it any help or tips would be really appreciates.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int i = 0;
int sum = 0;
int avg = 0;
int min = 0;
int max = 0;
int x = 0;
int random = 0;
int num[20] = { 0 };
srand(time(NULL));
for (x = 0; x<20; x++)
{
random = rand() % 100 + 1;
num[x] = random;
if (num[x]>max)
{
max = num[x];
}
if (x % 8 == 0)
{
printf("\n");
}
sum += random;
printf("%d\t", num[x]);
}
avg = sum / 20;
printf("\n\nthis is Max number: %d", max);
printf("\nThis is average number:%d", avg);
printf("\nThis is min number:", min);
return 0;
}
You have a condition in your code which determines the maximum value. You need a same for finding the minimum value too,i.e,Something like this:
if (num[x]<min)
{
min = num[x];
}
But this will never be true as min is 0 and num[x] will always be greater than 0. So set min to 100 by changing
int min = 0;
To
int min = 100;
But still,your code won't work as expected. This is because you forgot to add a format specifier(%d) in your last printf. So change
printf("\nThis is min number:", min);
To
printf("\nThis is min number:%d", min);
And finally,your code will work!

Average, max, and min program in C

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

Resources