0

Could anyone explain this ? Help me to understand this statement

This code is c++ and it will display a Christmas Tree I just copied from google /* ---------------------------------------- */ #include <iostream> using namespace std; int main() { int n = 5; for( int i = 1; i <= n; i++ ) { for( int k = i; k <= n - 1; k++ ) { cout << " "; } for( int j = 1; j <= i; j++ ) { if( j % 3 == 0 ) { cout << "o "; } else if( j % 3 == 1 ){ cout << "* "; } else { cout << "# "; } } cout << endl; } } /* ---------------------------------------- */ I am confuse with this statement ( j % 3 == 0 ) and ( j % 3 == 1 ) . I understand the j (var) it will loop and count 1 2 3 4 5 but the following code I dont really understand the % 3 == 0 and % 3 == 1 . Could anyone help me to understand this and give me some explaination bout this.

5th Sep 2018, 6:00 AM
Info Slash
Info Slash - avatar
3 Answers
+ 6
As Androidus told, % is modulus operator. It returns the remainder when two numbers are divided unequally. If the two numbers are divided equally it returns 0. For example: 11 % 2 = 1 6 % 3 = 0 6 % 10 = 6 -4 % 2 = 0 -7 % 9 = - 7
5th Sep 2018, 6:50 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
The '%' sign is called the modulo. It returns the rest of the division between 2 numbers. For example : - 4%3=1 - 5%3=2 - 6%3=0
5th Sep 2018, 6:29 AM
Alexandru Turculet
Alexandru Turculet - avatar
0
the display of the loop without number * * # * # o * # o * * # o * # /* ------------------------------------------------ */ I test the code many times the ( j % 3 == 0 ) statement, it has a { cout << "o "; } so I put the variable ( j ) in the { cout << j << "o "; } to identify where he is. And then I run the program it displays like this, there is a number three ( 3 ) in the printed text ( o ) so it means that he is placed on number three ( 3 ) in loop 1 2 3 4 5. * * # * # 3o * # 3o * * # 3o * # /* ------------------------------------------------ */ I put the variable in every printing text { cout } to identify each counting number of the loop and it will look like this 1* 1* 2# 1* 2# 3o 1* 2# 3o 4* 1* 2# 3o 4* 5# /* ------------------------------------------------ */ ( j % 3 == 0 ) lets say the ( j ) there is 5, then ( % ) modulo is 3, so the answer is 2 . ( 5 % 3 == 0 ) 5 % 3 = 2 ( 2 == 0 ) Im wondering why it is placed in 3 and not in 2 in the loop of 1 2 3 4 5. the answer 2 is followed by == 0 . ( 2 == 0 ) 2 is equal to 0 so 2 will become 0 ?
5th Sep 2018, 7:29 AM
Info Slash
Info Slash - avatar