mercredi 16 décembre 2020

Why does this work, finding min value and index for an array

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

Aucun commentaire:

Enregistrer un commentaire