Z1nkMeister Z1nkMeister - 1 year ago 61
C Question

While loop is not stopping when condition is met

I have a while loop that lets the user input any amount of numbers separated by white space, and the program is supposed to terminated while showing the the highest number to the user, when the user inputs a


#include <stdio.h>

int main(){
float fResult[100], fMax;
int c = 1;
while (fResult[c] != 0){
scanf(" %f ", &fResult[c]);
if (fResult[c] > fMax){
fMax = fResult[c];
c = c + 1;
if (fResult[1]==0){
printf("empty sequence");
} else {
printf("%.3f ", fMax);

It works fine until the user inputs a sequence of nothing but negative numbers. Then the result is showing as

For example, when the user inputs
-3 -4 -100 -5 0
, the result should be
, but instead I get a
, which is technically the maximum number.
But isn't the while loop supposed to be ignored if the user inputs a

Answer Source

Simply a case of undefined behaviour:

fmax is accidently zero, upon left uninitialized. Automatic variable when left uninitialized can have any garbage value. It is zero in your case. So in first four iterations, fmax would have stayed at zero value upon comparison with negative values.

You should follow the principle: populate first - then access

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download