C while loop infinite loop EOF not working - c

I am having problem with EOF in my while loop. It does not seem to simply end when EOF is entered but rather does this...
How can I fix it and have the while loop stop and move on. Thanks.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest, int* average, int count);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int count; // number count
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
// Starting prompts
printf("\nHello this program will take in intagers and print");
printf("\nout the largest, smallest and avarage of integers");
printf("\nenterd int.");
printf("\nPlease enter in a integer ");
while (scanf("%d", &integer) != EOF)
{
if (integer != EOF)
{
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
else
{
printf("\n \n");
}
}
printf("\nThe largest number entered is %d and the smallest", largest);
printf("\nwas %d and the average of all the numbers is %d\n", smallest, average);
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest, int *average, int count)
{
int x; // just a holder variable
// finds average
x = 0;
x += integer;
*average = (x / count);
// Finds smallest and largest
if (integer <= *smallest)
{
*smallest = integer;
}
if (integer >= *largest)
{
*largest = integer;
}
printf("Enter another integer or <EOF> to quit ");
return;
}
[1]: http://i.stack.imgur.com/P0307.png
UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}

scanf returns the number of elements successfully converted. If it can't convert any, it returns 0. EOF is only returned for end-of-file (on Unix a Control-D).
So you should modify your program to save the return value from scanf and then test it for 0 and EOF separately.
It is also pointless to compare the integer variable with EOF, since all you can possibly know about EOF is that it is a negative integer. Read the scanf manual page and understand what it does and what it returns when and where. That'll solve the puzzle. :-)
Alright, some more hints. Can you make sense of this?
for (;;) {
int successfully_converted = scanf("%d", &integer);
if (successfully_converted == EOF) {
/* Do something when the user is tired of typing. */
puts("Thank you for an enjoyable game.\n");
exit(0);
} else if (successfully_converted == 0) {
puts("This didn't look like an integer\n");
exit(1);
} else {
/* Do something with integer. */
}
}

You are not comparing the integer value with EOF
. You are comparing the scanf result with EOF..
Here as you enter 1 value each time, scanf result will be 1.
So evrrytime the while loop condition fails and infinite loop is generated.
Also if you EOF then what character would you enter to end the loop???
So EOF should not be used.
So I would suggest you to use do while loop
do
{
scanf("%d",&integer);
....
...
printf("enter 1 to continue");
scanf("%d",&check);
}while(check == 1);

Test the result of scanf() against EOF, 0, and 1.
int cnt;
while ((cnt = scanf("%d", &integer)) == 1) {
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
if (cnt == 0) {
printf("Something other than an integer was entered.\n");
}
else if (cnt == EOF) {
printf("EOF or I/O Error occurred.\n");
}
// Add the following for debug if desired
else {
printf("Should _never get here!\n");
}
...

UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}

Related

How can assign only the three largest integers from a for loop in C into three separate variables?

I am trying to make a program that takes two user inputs (x and y), checks all numbers in the interval for all prime numbers, and then prints only the three largest prime numbers if available. So far, my code checks all the prime numbers in an interval starting from the largest to the smallest.
My code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primeChecker(divisor+1,dividend);
}
void largestonly(int*counter, int*largest1, int*largest2, int*largest3){
int temp;
temp=*counter;
if (temp>*largest1&&*largest2) ///incomplete attempt
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y,largest1, largest2, largest3, counter, divisor, dividend, i;
divisor=2;
dividend=counter;
inputXY(&x, &y);
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for (i=0; i<=3; i++){
for(counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1) largestonly(&counter, &largest1, &largest2, &largest3);
}
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
I have yet to successfully write a working function that can sort all the integers produced by the for loop in main(). It is the largestonly() function as seen above. In relation to that, my printlargest() function undoubtedly does not work. My idea in here is that if largest1 does not contain any value (or is equal to 0 or some other more appropriate value that I could not think of), the function will only print the two largest prime numbers found. Relatively, if both largest1 and largest2 are empty, only the largest prime number will be printed. If all variables are empty, it should print "No prime numbers found!". I am very lost with what to do with my code at the moment so any type of help will be greatly appreciated. Thank you.
There are a few things to do here.
First, pay attention to the line 21, you call a primeChecker() function that doesn't exist. It will raise an error when compiling.
Second, you don't have to "sort" anything. You only have to store the prime numbers into the variables as they arrive. I noticed you consider largest3 to be the first one that has to be filled (at least it is what can be understood from printlargest()), this gives us the following:
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
Additionally, there is no need to pass the address of counter in the first place, as you won't need to modify it.
Lastly, in the main() function, you don't need a double loop. Think of it this way. If you were to do the exercise mentally, you'd go down the numbers, check if they were primes, and write them down if they satisfy the conditions: being primes and being the first, second or third. You wouldn't need to do it 3 times. Hence:
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
Also, the way you declared your variables without initializing them can sometimes be dangerous. In this case, as largest1, largest2 and largest3 weren't set to 0, you'd have had no chance to trigger any of the printlargest() cases. It may be because you were stuck on a part of your program you thought would also handle that but I still want to point it out, just in case.
EDIT: you could also add a condition in the for loop such that if largest1 is not equal to 0, it exits the loop. It would prevent the program to loop through (potentially) big amount of numbers when you already have everything you need. It would look like this (with the existing for loop, for context):
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
if(largest1 != 0)
break;
}
Hope this clears out the issues you had, feel free to ask anything if necessary, or to point out things I'd have misunderstood in your question.
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primechecker(divisor+1,dividend);
}
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
First, define how you would check for a prime number:
bool is_prime(int num)
{
if (num < 2)
return false;
for (int i = 2; i <= num / i; ++i)
if (num % i == 0)
return false;
return true;
}
Then, define a function that returns the 3 largest prime numbers in a given interval:
void get_max_3_in_range(int lo, int hi, int *max1, int *max2, int *max3)
{
*max1 = 0; // smallest
*max2 = 0;
*max3 = 0; // largest
int round = 0;
for (int i = lo; i <= hi; ++i) {
if (is_prime(i)) {
if (round % 3 == 0) *max1 = i;
if (round % 3 == 1) *max2 = i;
if (round % 3 == 2) *max3 = i;
++round;
}
}
if (*max1 > *max2) swap_int(max1, max2);
if (*max2 > *max3) swap_int(max2, max3);
}
Here is your swap():
void swap_int(int *v1, int *v2)
{
int tmp = *v1;
*v1 = *v2;
*v2 = tmp;
}
Driver program:
int main(void)
{
int x, y;
inputXY(&x, &y);
int max1, max2, max3;
get_max_3_in_range(x, y, &max1, &max2, &max3);
printf("x = %d\ty = %d\n", x, y);
printf("max1 = %d\tmax2 = %d\tmax3 = %d\n", max1, max2, max3);
}
Output:
Enter value of x: 0
Enter value of y: 100
x = 0 y = 100
max1 = 83 max2 = 89 max3 = 97
You can choose what to output in case one or more of the maximums is/are zero. Here, I chose to print them all.
Side note: Your inputXY() is very error-prone. Because if the user enters a string, your code will break. scanf() returns a value that you must check.
Following is a better version:
void inputXY(int *x, int *y)
{
for(;;) {
printf("Enter value of x: ");
if (scanf("%d", x) != 1)
flush_stdin();
else
break;
}
flush_stdin();
for(;;) {
printf("Enter value of y: ");
if (scanf("%d", y) != 1)
flush_stdin();
else
break;
}
}
And flush_stdin() (Never do fflush(stdin)!!) will clear what remained in the buffer, in case the user didn't enter (just) a number:
void flush_stdin(void)
{
scanf("%*[^\n]");
}

C program on part of algorithm which focus on finding Armstrong-like number

I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is codeļ¼Œ a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}

Programs counting even and odd numbers

I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.

Finding biggest and smallest numbers using user input

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

Writing a program to find the largest in a series of numbers.

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

Resources