cout << ( row % 2 ? "<" : ">" );

Hello,

I'm stumped on this.
cout << ( row % 2 ? "<" : ">" );
I think that the question mark means that there's a cout if/else with < and >. Is that right? So it would function like below?

if (row%2)
cout << "<";
else
cout >> ">";

If that's the case, what does the row%2 mean? Is that like a check for a remainder?
The whole program is below.


#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int row = 3;
int col;

while ( row >= 1 )
{
col = 1;
while ( col <= 4)
{
cout << ( row % 2 ? "<" : ">" );
++col;
}
cout << endl;
--row; // decrement row
}
}



Thanks
Last edited on
You are right.

So it would function like below?

if (row%2)
cout << "<";
else
cout >> ">";


Yes, it is.

Is that like a check for a remainder?


Yes, it is.
oh wait a minute, you can't right cout like this cout >> can you? I think I screwed up. Also, does that mean if there is no remainder, than the output is "<" ?
row%2 returns 0 if row is even and 1 if row is odd. When you use a number in the if condition it treats 0 as false and everything else as true.

1
2
3
4
if row is odd
	cout << "<";
else
	cout >> ">";
So you can write cout like cout >> ?
It is a typo. Shall be of course

cout << ">";

I copied and pasted what you wrote.:)
Last edited on
Oh ok, I see.
I'm a little confused by the second while loop. It's just going to get the same answer every time isn't it? Just wondering what the point is.

while ( col <= 4)
{
cout << ( row % 2 ? "<" : ">" );
++col;

1 is less than 4 with output of >
then you add 1
2 is less than 4 with output of >
then you add 1
3 is less than 4 with output of >

so the loop will just create a line that says >>>> or <<<< depending on the 1st answer. Am I anywhere in the ballpark?
It looks like you have desccribed.: depending of the oddness of row either "<<<<" or ">>>>" is outputed.
yah usually there is a point to these basic programs. I guess I just don't see the point of this one. As long as I understand it correctly, that's all that matters. Thanks
So, just to double check,

For this -
if (row%2)
cout << "<";
else
cout >> ">";

The first one will always be odd, and else will be even?
bump?
If row is an even number than "<" will be printed". If not, then ">" will be printed. Although, that is only if the remainder of row % 2 is 0. It's not an even number if the remainder isn't 0. You should change your code to something like this.

1
2
3
4
if(row % 2 == 0)
      std::cout << '<';
else
      std::cout << '>';

 
std::cout << (row % 2 == 0?"<":">") << std::endl;
Last edited on
One again shall be

if (row%2)
cout << "<";
else
cout << ">";

The first one depends on the value of row. If the initial value of row is equal to 3 then row %2 is not equal to zero that is it is odd.
@vlad from moscow

http://codepad.org/Wuywz0sM

Wouldn't you have to check if the remainder is 0?
thanks a bunch
Topic archived. No new replies allowed.