How to determine if a number is even or odd with AMPScript?

All we need is an easy explanation of the problem, so here it is.

I have a global variable called @Count. I also have a for loop that increases the @Count by 1 each time I cycle through the loop. Is there a way for me to detect with AMPScript whether @Count is an odd or even number?

%%[

/* SET GLOBAL COUNT VARIABLE */
SET @Count = 0

/* INCREASE THE COUNT BY 1 EACH TIME */
FOR @i = 1 TO @increaseCount DO
  SET @Count = Add(@Count,1)
NEXT @i

/* DO SOMETHING IF COUNT IS EVEN OR ODD NUMBER */
IF @Count == "even" THEN
  BLANK
ELSEIF  @Count == "odd" THEN
  BLANK
ENDIF

]%%

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I’d suggest using the MOD() AMPScript function. If @sum is evenly divisible by 2 then it’s even, otherwise it’s odd:

%%[

var @i, @sum, @max
set @sum = 0
set @max = 10

FOR @i = 1 TO @max DO
  SET @sum = Add(@sum,1)
NEXT @i

IF mod(@sum,2) == 0 THEN
  output(concat("<br>", @sum, " is even"))
ELSE
  output(concat("<br>", @sum, " is odd"))
ENDIF

]%%

Method 2

Try using MOD(@Count, 2) == 1. Here is the documentation for the MOD function. If it’s 0, you’re even. If it’s 1, you’re odd.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply