Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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

  • #2
    Regular Coder cs_student's Avatar
    Join Date
    Oct 2009
    Location
    ~/
    Posts
    195
    Thanks
    2
    Thanked 22 Times in 22 Posts
    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.

  • Users who have thanked cs_student for this post:

    mariemac (12-03-2010)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •