Question! I'm just studying the arrangement. Is this code possible to be more concise?

Asked 2 years ago, Updated 2 years ago, 39 views

#include <stdio.h>

int main(void) {
    int aList[5];
    int i = 0, nMin = 0, nMax = 0;

    printf("Please input five numbers: ");
    do {
        scanf("%d", &aList[i]);
        if(i==0) nMin = aList[0]; nMax = aList[0];
        if(nMin > aList[i]) nMin = aList[i];
        if(nMax < aList[i]) nMax = aList[i];
        i++;
    } } while(i < 5);

    printf("MIN: %d, MAX: %d\n", nMin, nMax);
}

I made a code that receives 5 integers and outputs the minimum and maximum values as an exercise.

I think I can make it more concise, but I can't think of it. What if you make it simpler?!

Input example:

1 5 2 4 3

Output example:

MIN: 1, MAX: 5

c array

2022-09-20 20:18

2 Answers

Please refer to the code below.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <limits.h>

int main(void) {
    int aList[5];
    int i = 0, nMin = INT_MAX, nMax = INT_MIN;

    printf("Please input five numbers: ");

    for (int i = 0; i < 5; i++)
    {
        scanf("%d", &aList[i]);

        if (nMin > aList[i])
            nMin = aList[i];
        if (nMax < aList[i])
            nMax = aList[i];
    }

    printf("MIN: %d, MAX: %d\n", nMin, nMax);
}


2022-09-20 20:18

if(i==0) nMin = aList[0]; nMax = aList[0];

This part is not tied up in blocks, so it doesn't work properly. Please tie it up in blocks as shown below.

if(i==0) {
    nMin = aList[0];
    nMax = aList[0];
};

The simplified (?) modification code is as follows.

#include <stdio.h>

int main(void) {
    int aList[5] = {1,5,2,4,3};
    int nMin = 0, nMax = 0;

    //printf("Please input five numbers: ");
    for(int i=0;i<5;i++){
        int inputValue;
        //scanf("%d", &inputValue);
        inputValue = aList[i];
        nMin = nMin>inputValue|!i?inputValue:nMin;
        nMax = nMax<inputValue|!i?inputValue:nMax;
    }
    printf("MIN: %d, MAX: %d\n", nMin, nMax);
}

Bit operators and trigonometric operators were used.

Thank you.


2022-09-20 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.