Home > Blockchain >  high numbers and their position
high numbers and their position

Time:01-18

I`m trying to write the program that will find first three highest numbers in array and their position.

This is my code. But for some reasons the position of two last numbers is 0 and I cant understand why. Can someone explain where is my problem? Thank you in advice!

int main(){

    int idx1 = 0;
    int idx2 = 0;
    int idx3 = 0;
    int first = 0;
    int second = 0;
    int third = 0;
    int num;
    int numbers;
    int array[1000];

    printf("Print the number of numbers: ");
    scanf("%d", &num);
    printf("Print your numbers: ");
    for(int i = 0; i < num; i  ){
        scanf("%d", &numbers);
        array[i] = numbers;
        if(array[i] > first){
            third = second;
            second = first;
            first = array[i];
            idx1 = i;
        }else if(array[i] > second){
            third = second;
            second = array[i];
            idx2 = i;
        }else if(array[i] > third){
            third = array[i];
            idx3 = i;
        }
    }
    printf("%d %d %d\n", first, second, third);
    printf("%d %d %d", idx1, idx2, idx3);
}

CodePudding user response:

At least in the if statements

    if(array[i] > first){
        third = second;
        second = first;
        first = array[i];
        idx1 = i;
    }else if(array[i] > second){
        third = second;
        second = array[i];
        idx2 = i;

you forgot to change idx3 and idx2 for the first if statement and idx3 for the second if statement.

Pay attention to that as the element type of the array is int then the user can enter negative numbers. In this case your code will not work.

  • Related