C/C++ What does the modulus operator mean in a C++ if statement?

  • Thread starter Thread starter FallArk
  • Start date Start date
  • Tags Tags
    C++ If statement
AI Thread Summary
The discussion centers on understanding an if statement that utilizes the modulus operator. The expression checks if a specific element in the 'randoms' array, determined by the calculation (x * 3) + y, is odd. The modulus operator (%) returns the remainder of a division, so when used with 2, it indicates whether the number is odd (true) or even (false). If the element is odd, the code within the if statement will execute.
FallArk
Messages
127
Reaction score
0
I have run into an if statement as shown below:

if (randoms[(x * 3) + y] % 2)

I don't really understand what this means.
Thank you for helping!
 
Technology news on Phys.org
The [m]%[/m] symbol is the modulus operator, and so the expression [m]n % 2[/m] will be true if n is odd (there is a remainder when dividing by 2) and false if n is even (there is no remainder when dividing by 2).

So, the statement:

[m]if (randoms[(x * 3) + y] % 2)[/m]

Is looking to see if the [m]((x*3) + y)[/m]th element of the [m]randoms[/m] array is odd, and if so, execute some code.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top