This question already has answers here:
Min and max in C using basics
(4 answers)
Closed 4 years ago.
It works, but if you don't enter any number smaller than 0 it doesn't print the smaller value and prints 0.
int max = 0;
int min = 0;
int a;
printf("Enter a number:\n");
scanf("%d", &a);
while (a != -1){
if (a < min){
min = a;
}
if (a > max){
max = a;
}
scanf("%d", &a);
}
printf("Your largest number is %d. Your smallest number is %d.", max, min);
It's because your initial min is zero so no positive value is going to be less than that.
You're better off changing your loop construct so that initial value is loaded no matter what, something like:
int a, min = 0, max = 0, first = 1; // Force first number to be used.
printf ("Enter a number:\n");
scanf ("%d", &a);
while (a != -1) {
if (first || a < min) min = a;
if (first || a > max) max = a;
first = 0; // Reset after first number.
scanf ("%d", &a);
}
printf ("Largest is %d, smallest is %d.\n", max, min);
You should probably also check the return value from scanf so as to catch non-integer input. That's a way to have more robust code but, for educational programs, it's probably okay (at least as long as you understand the implications).
This could be as simple as replacing:
scanf ("%d", &a)
with something like:
if (scanf ("%d", &a) != 1) {
puts ("Invalid input.");
exit(1);
}
Related
I'm experimenting with a simple C program that should prompt user to enter a chosen number of positive integers. I'm having an issue getting the maximum and minimum of the set of integers I input without the use of an array.
The way that I currently have it is that it will update the max and min among the last two entered values. If someone wouldn't mind looking to see what I'm doing wrong, it would be appreciated.
take a look here:
#include<stdio.h>
int main()
{
int N ,i, value=0, min=0, max=0, sum=0, oldmin=0, Newmin=0, oldmax=0, Newmax=0;
double mean;
do{
printf("How many values are to be entered?: ");
scanf("%d", &N);
printf("\n");
if (N>0){
do{
if (N>0){
// 1st value updated
for (i=1;i<=N;i++)
{
printf("Value %d:\n",i);
scanf("%d", &value);
sum = sum+value;
}
mean = (double)sum/(double)N;
//max
if(oldmax<Newmax){
max = Newmax;
}
else max = oldmax;
//min
if(oldmin>Newmin){
min = Newmin;
}
else min = oldmin;
}
else printf("INPUT ERROR!\n");
}
while(N<0);
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf.",min,max,mean);
}else printf("INPUT ERROR!\n");
} while(N<0);
return 0;}
some remarks :
you need to set the min/max value from value in the same loop you do sum = sum+value; , this is the reason of your problem about min/max
check the scanf result to be sure a number was enter
if (N>0){ do{ if (N>0){ so two check but N never change
if (N > 0) { do { ... } while (N<0); } that has no sense
the embedded loops have no sense, only 1 loop is needed
A proposal removing the problems :
#include<stdio.h>
int main()
{
int N;
fprintf(stderr, "How many values are to be entered?: ");
if ((scanf("%d", &N) != 1) || (N <= 0))
printf("INPUT ERROR!\n");
else {
int i, min, max, sum = 0;
for (i = 0; i < N; ++i) {
int value;
fprintf(stderr, "Value %d:\n",i);
if (scanf("%d", &value) != 1) {
printf("INPUT ERROR!\n");
return -1;
}
sum = sum+value;
if (i == 0) {
min = max = value;
}
else {
if (value < min)
min = value;
if (value > max)
max = value;
}
}
printf("\nThe minimum value is %d, the maximum value is %d, and the average value is %.2lf\n",
min,max, (double)sum/(double)N);
}
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -pedantic -Wextra c.c
pi#raspberrypi:/tmp $ ./a.out
How many values are to be entered?: 3
Value 0:
1
Value 1:
2
Value 2:
3
The minimum value is 1, the maximum value is 3, and the average value is 2.00
I used fprintf to flush the message with a \n, and I set the first min and max value on the first turn to not have to use the MIN_INT MAX_INT may be not defined for you
if(oldmax<Newmax){
Don't compare newmax and oldmax. Compare max and value. Same with min.
I'm not even sure about the purpose of Newmax and oldmax. Remove these variables all-together, as it will just confuse you.
Just use min, max, and value. It will sort out.
I'm trying to declare variables in my main() and then use their address and point to them in a function so that my function doesn't return any thing and all changes of the variable in the function goes straight to the main(). But every time I run this program it asks for x and then for "how many terms to use".. If I write 0 it works and goes to the if statement and if i write and bigger number than 0 than it works but if I write a negative number like -1 it moves on and ends he program??? does anyone have any idea?
Here's my basic code:
void getInput(double *,int *);
void main()
{
double x;
int n;
getInput(&x,&n);
}
void getInput(double *N, int *X)
{
N = 0;
printf("Please enter a real value for x: ");
scanf("%lf", &X);
while(N <= 0)
{
printf("How many terms to use: ");
scanf("%ld", &N);
if (N <= 0)
{
printf("The value of a must be greater than %d\n", N);
}
}
}
Change:
scanf("%lf", &X);
to:
scanf("%d", X);
Inside the getInput function, X is already a pointer.
The same for the other scanf, where you should change scanf("%ld", &N); to scanf("%lf", N);.
Also change N = 0 to *N = 0 and if (N <= 0) to if (*N <= 0).
You also mixed up the %ld and the %lf format specifiers.
Your compiler should have warned you.
And finally change:
printf("The value of a must be greater than %d\n", N);
to
printf("The value of a must be greater than 0");
If you enter e.g. -1 you don't want the text The value of a must be greater than -1 to be displayed.
Unrelated:
it's int main(), not void main().
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what i'm doing wrong but the for loop is not initializing
The code just goes immediately to displaying the printfs. That have no values in them since the for loop didn't activate
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("Pause")
main() {
// INITALIZE VARIABLES
int number = 0;
int i = 0;
int odd = 0;
int even = 0;
int totalNum = 0;
int tempNum = 0;
int count;
printf("Enter a number between 2 and 25\n");
scanf("%i", &number);
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
for (i = 1; i == count; ++i){
printf("input numbers\n");
scanf("%i", &tempNum);
if (tempNum % 2 == 0)
even++;
else
odd++;
totalNum = totalNum + tempNum;
} // END FOR LOOP
// DISPLAY OUTPUT
printf("You entered %i numbers\n", count);
printf("The sum of the %i numbers is %i\n", count, totalNum);
printf("The average of the %i numbers is %i\n", count, totalNum / count);
printf("You entered %i odd numbers and %i even numbers\n", odd, even);
PAUSE;
} // END MAIN
Your loop will only execute at best once, when count == 1 as you initialize i to 1.
If you enter a 1 for count,
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
the loop will run exactly once, until i increments to 2
You probably want:
for (i = 1; i <= count; ++i){
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
it should be...
do{
if (number < 2 || number > 25){
printf("That was an invalid number please try again\n");
scanf("%i", &number);
}
} while (number < 2 || number > 25);
else it asks always another number
i = 1, so i == count; gives false therefore the loop is ignored.
A for loop in C works like this:
for ( variable initialization; condition; variable update ) {
/* Do something... */
}
The loop will execute for as long as condition is true. So, when you do:
for (i = 1; i == count; ++i)
The loop will execute for as long as i == count is true. So, unless count holds 1 when this line is executed, the loop will never run.
As others pointed out, you probably want this:
for (i = 1; i <= count; ++i)
So your loop will run for all values of i, until it reaches count.
As a side note i should point out that the usual way to write for loops in C is something like this:
for (i = 0; i < count; i++)
We start with i = 0 because C arrays are zero-based, so the Nth element of an array has index n-1
You were so close. In addition to fixing your loop test clause for (i = 1; i <= count; i++), I would suggest using " %d" for your format specifier. Your do loop need only be a while loop to avoid printing your invalid number message every time.
Additionally, While not an error, the standard coding style for C avoids caMelCase variables in favor of all lower-case. See e.g. NASA - C Style Guide, 1994.
With those changes, (and changing your odd/even check to a simple &) you could write your code as follows.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// #define PAUSE system("Pause")
int main (void)
{
int number, i, odd, even, totalnum, tempnum, count;
number = i = odd = even = totalnum = tempnum = count = 0;
printf ("enter a number between 2 and 25: ");
scanf (" %d", &number);
while (number < 2 || number > 25) {
printf ("invalid number, again (between 2 and 25): ");
scanf (" %d", &number);
}
printf ("numbers to input: ");
scanf (" %d", &count);
for (i = 1; i <= count; i++) {
printf ("input number %2d: ", i);
scanf (" %d", &tempnum);
if ((tempnum & 1) == 0)
even++;
else
odd++;
totalnum = totalnum + tempnum;
}
printf ("You entered %d numbers\n", count);
printf ("The sum of the %d numbers is %d\n",
count, totalnum);
printf ("The average of the %d numbers is %d\n",
count, totalnum / count);
printf ("You entered %d odd numbers and %d even numbers\n",
odd, even);
// PAUSE;
return 0;
}
note: main is type int (e.g. int main (int argc, char **argv) or simply int main (void) to indicate no arguments taken). Since it is type int it will return a value to the shell. While historic implementations may have allowed void main that is no longer the case for portable code.
Example Use/Output
$ /bin/forskipped
enter a number between 2 and 25: 4
numbers to input: 4
input number 1: 1
input number 2: 2
input number 3: 3
input number 4: 4
You entered 4 numbers
The sum of the 4 numbers is 10
The average of the 4 numbers is 2
You entered 2 odd numbers and 2 even numbers
Look it over and let me know if you have any questions.
Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
How do i do to make my program better?
You're comparing against the wrong values.
do
{
printf("Enter a number.\n");
scanf("%i", &input);
if min > input
min = input
if max < input
max = input
} while (input > 0);
#include <stdio.h>
#include <conio.h>
#include <limits.h>
int main(){
int num;
int i;
int maxi=0;
int minim=INT_MAX;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf("%d", &num);
if(num > 0){
while (num>0){
printf ("\nEnter number:");
if(scanf("%d", &i) == 1 && !(i<0)){
if(minim > i)
minim = i;
if (maxi < i)
maxi = i;
++cont;
--num;
} else {
//fprintf(stderr, "redo input!\n")
;
}
scanf("%*[^\n]%*c");
}
printf ("\nBiggest number is : %d", maxi);
printf ("\nSmallest number is : %d\n", minim);
}
getch();
return 0;
}
You should initialize mini to the largest possible int, i.e. INT_MAX and maxi to the smallest possible int, i.e., INT_MIN. This way, even if the first number is negative, it will be considered for maxi, and if the first number is positive it will still be considered for mini. The constants INT_MAX and INT_MIN are included in <climits> or <limits.h>.
Also, you are comparing the current entered number with num, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}
I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}