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?
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?
CodePudding user response:
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.
CodePudding user response:
The statement is easier to understand with parentheses :
while((std::cout << A[--N] << ' ') && N);
The space character ' '
is fed to the std::cout
stream and has nothing to do with the logic operator &&
.
The unary operator --
will decrement N before any access to it.
The loop will stop when N reach 0, which will make the &&
logic operation evaluate to false.