Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive print within std::cout

The input is N spaced integers. You have to read the input and print the input backwards. Source:(https://www.hackerrank.com/challenges/arrays-introduction/problem?isFullScreen=false)

One of the solutions is:

#include <iostream>
int main() {
    int N,i=0;
    std::cin>>N;
    int *A = new int[N];
    while(std::cin>>A[i++]);
    // We have now iterated through the input and stored the 
    // integers in a dynamically allocated array.


    // This line apparently prints out the Array (size N) backwards.
    while(std::cout<<A[--N]<<' ' && N);
    delete[] A;
    return 0;
}

How does while(std::cout<<A[--N]<<' ' && N); print out the array A backwards?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How does it know to stop running the while loop?

What does the expression ' ' && N do? My intuition of && tells me that it should equate to TRUE or FALSE, but what does ' ' have to do with Boolean?

>Solution :

The << operator (even though it’s overloaded for output streams and is no longer a bitwise shift) has higher precedence than the && operator. Thus, we can add parentheses to your while statement to make it clearer:

    while ( (std::cout << A[--N] << ' ') && N )
        ;

The expression within the added parentheses will, on each loop, decrement the value of N (so, on the first loop, that will be reduced to the original value minus 1 – which is the index to the last element of the allocated array), output the integer element at that index, then output a space. The result of that ‘chained’ operation will be a reference to std::cout; that has an operator bool(), which returns true if the output succeeded and false in the event (unlikely, in the given code) of failure. That (probably) true value is then combined with the result of converting N to a Boolean value – and that conversion will yield true1 for an non-zero value and false` for zero … so the loop will stop when the index has been decrement to zero (referencing the first element of the array).

When that N has reached zero, we no longer need to run the (empty) loop, because the output will already have been performed by the expression on the left of the && operator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading