This program takes user input 10 times, then determines the lowest value and the index location for that lowest value.
Why does this if-statement work? The "counter == 0" part, wouldn't that always be false? Meaning the code wouldn't work? Yet it does?
#include <stdio.h>
#pragma warning(disable: 4996)
#define arraySize 10
int getNum(void);
int main()
{
int myArray[arraySize] = {0};
int counter = 0;
int minIndex = 0;
int minValue = 0;
printf("Enter 10 Integer Values\n");
for (counter = 0; counter < arraySize; counter++)
{
printf("Enter Integer #%d: ", counter);
myArray[counter] = getNum();
if (counter == 0 || (minValue > myArray[counter]))
{
minValue = myArray[counter];
minIndex = counter;
}
}
printf("Min: %d, Index: %d.", minValue, minIndex);
return 0;
}
int getNum(void)
{
char record[121] = {0};
int number = 0;
fgets(record, 121, stdin);
if( sscanf(record, "%d", &number) != 1 )
{
number = -1;
}
return number;
}
Lets work with this inputs: 0,1,2,3,4,5,6,7,8,-1
In the first iteration counter==0
is true and minValue > myArray[counter]
is false because 0 > 0 return false, the operator || allow to enter the if.
In the following iterations the sentence counter==0
will be false ever, but the minValue > myArray[counter]
will be false or true depends on the number. With 1,2,3,4,5,6,7,8 will be false but whit -1 will enter because 0 > -1. And make the min value = -1;
The || operator works like this:
true || true =true
true || false =true
false || true ==true
false || false ==false
To sum up, if there is one true sentence the program will enter in the if sentence.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.