Home > Mobile >  Find two largest numbers in input
Find two largest numbers in input

Time:10-26

I need to make a program that will perform the following task:

Enter N natural numbers. Complete the input with 0. Output the number of the maximal number.

I have already done this, and you can see the code below:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;

printf("Start enter numbers, bruh (please end input with 0):\n");

scanf("%d", &num);
while (num != 0) {
    if (num >= max) {
        max = num;
        max_place = i;
    }
    i  ;
    scanf("%d", &num);
}

if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place   1);

return 0;
}

The teacher then made the task more difficult – the program needs to print the maximum number and the next maximum after it of the entered numbers.

How can I do it?

CodePudding user response:

If you can use arrays and sort use that way. if not, this is in your code

int main(void) {
    int i = 0, num, max_place = -1, second_max_place = -1;
    int max = -2147483647;
    int second_max = -2147483647;
 
    printf("Start enter numbers, bruh (please end input with 0):\n");
 
    scanf("%d", &num);
    while (num != 0) {
        if (num == 0) break;
        if (num >= max) {
            second_max = max;
            second_max_place = max_place;
            max = num;
            max_place = i;
        }
        if(num < max && num >= second_max){
            second_max = num;
            second_max_place = i;
        }
        
        i  ;
        scanf("%d", &num);
    }
 
    if (max_place == -1) printf("Numbers were not entered");
    else{
        printf("\nMax number was on %d place, bruh", max_place   1);
        printf("\nSecond Max number was on %d place, bruh", second_max_place   1);
    } 
 
    return 0;
}
  • Related