Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • If statement for even/odd numbers

    Hello, Im working with the following code:

    Code:
    forvalues x = 1/4 {
    
    if `x' == 1 | `x'==3 {
        local test "hello"
    }
    
    if `x' == 2 | `x'==4 {
        local test "bye"
    }
    
    
    display "`test'"
    
    
    }
    You see how I have to list out the even numbers and odd numbers to tell stata how to act, I want to simply do something like this ( if `x' == even ) or ( if `x'==odd). How can I implement something like this?
    Thanks,
    Jad

  • #2
    You need the mod() function. Mod checks to see what the remainder is when the first number is divided by the second number. If you divide by 2 and the remainder is 1, the number is odd. (Remember, 1 is equivalent to true.) If the remainder is 0, the number is even, (and 0 corresponds to false).

    Code:
    forvalues x = 1/10 {
        if mod(`x', 2) {
            display "odd"
        }
    
        else {
            display "even"
        }
    }
    Last edited by Daniel Schaefer; 26 Apr 2024, 14:36.

    Comment


    • #3
      Code:
      forvalues x = 1/4 {
          
      di cond(mod(`x', 2), "hello", "bye")
      
      }

      On what you can do with mod(,) see e.g.

      SJ-7-1 pr0031 . Stata tip 43: Remainders, selections, sequences, extractions
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox
      Q1/07 SJ 7(1):143--145 (no commands)
      tip for uses of the modulus


      SJ-11-3 dm0058 . . . . . . . . Speaking Stata: Fun and fluency with functions
      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox
      Q3/11 SJ 11(3):460--471 (no commands)
      a tour of easily missed or underestimated Stata functions


      Comment


      • #4
        Code:
        forvalues x = 1/4 {
            if mod(`x', 2) == 1 {
                local test "odd"
            }
        
            if mod(`x', 2) == 0 {
                local test "even"
            }
            display "`test'"
        }

        Comment


        • #5
          What we tell you three times is true. See for example in https://www.statalist.org/forums/for...ete-forum-post that statement being exemplified, explained and endorsed.

          Comment


          • #6
            Thanks everyone!

            Comment

            Working...
            X