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
Click For 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.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 22 ·
Replies
22
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
4K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 17 ·
Replies
17
Views
3K
Replies
69
Views
9K
Replies
1
Views
2K