dimanche 17 octobre 2021

Please help me understand the logic behind this code

I have been doing problems for while loop in c++ and i got stuck on this problem. Googled the answer to see what i had to do but now i dont understand the logic behind it and why it works.

Here is the problem:

A sequence consists of natural numbers and ends with 0. Determine the value of the second largest element in the sequence, that is, the element that will be the largest if you remove the largest element from the sequence.

Examples-> Input 1: 4, 4, 2, 3, 0 Output 1: 4 ; Input 2: 2 1 0 Output 2: 1

This is the code:

#include <iostream>
using namespace std;
int main() {
    int n, max, smax = 0;
    cin >> n;
    max = n;
    while (n != 0) {
        cin >> n;
        if (n > max) {
            smax = max;
            max = n;
        }
        else if (n > smax) {
            smax = n;
        }
    }
    cout << smax;
    return 0;
}

So, from my understanding max is n so the statement if n > max will never be True. Unless value for max resets with each loop and is 0, but then its always going to be true so there is no point for the second if statement.

Im sure i dont understand how the while loop works and i would like for someone to clear it up for me. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire