C programming Q/A

Q4) You are given a non-negative sequence of numbers, ending with a -1. You can assume that there are at least two numbers before the ending -1. You have to output the second largest element of the sequence. If there is no second largest element in the sequence then output 0. Note : -1 is not a part of input. It only signifies that input has ended.

    
    #include 

int main() {
  int n, largest = 0, second_largest = 0;
  while (scanf("%d", &n) && n != -1) {
    if (n > largest) {
      second_largest = largest;
      largest = n;
    } else if (n > second_largest && n != largest) {
      second_largest = n;
    }
  }
  printf("%d\n", second_largest);
  return 0;
}
    
Previous Post Next Post