Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-02-2010, 06:53 PM   PM User | #1
mariemac
New to the CF scene

 
Join Date: Nov 2010
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
mariemac is an unknown quantity at this point
modulus % as a relational operator

Being triyng to get my head around a use for the modulus operator % and where it can be used .
It was suggested that it can be used in evaluating a statement in a if else loop

Code:
 if (int  % 6 == 0)
{
do this 
else 
do that .
as someone who has never come across the modulus operator before can someone explain how this works and if it is possible to code the same test without using the modulus .
much obliged for any input on this
mariemac is offline   Reply With Quote
Old 12-02-2010, 07:38 PM   PM User | #2
cs_student
Regular Coder

 
cs_student's Avatar
 
Join Date: Oct 2009
Location: ~/
Posts: 195
Thanks: 2
Thanked 22 Times in 22 Posts
cs_student is an unknown quantity at this point
The modulus thing can be used in many different ways. You can generally do it other ways (though it may not be as intuitive or easy). ie, if you want to see if something is even or odd.

Using the mod operator
Code:
int x = 193586
if(x % 2 == 0)
    System.out.println("Even");
else
    System.out.println("Odd");
You could also create a recursive method that would determine.
(I just came up with this off the top of my head so it might not work quite right).
Code:
public boolean even(int num, int current) {
    if(current > num)
        return false;
    else if(current == num)
        return true;
    else return even(num, current * 2);
}

System.out.println(even(193586, 2));
While you can certainly do things differently, it is generally easier to use the modulus operator.
__________________
Get GNU/Linux - Play Ogg - Vim
Using Arch Linux x86_64, Xorg + xmonad
cs_student is offline   Reply With Quote
Users who have thanked cs_student for this post:
mariemac (12-03-2010)
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:14 PM.


Advertisement
Log in to turn off these ads.