Monday, March 20, 2023

Even Odd Number Program in Apex

How to Print Even Odd number in Salesforce  Apex


In this program, we check even odd number in Apex.


Here is the logic of even and odd number program =(( n%2)==0).

 operator '%' that isn't valid in Apex.

so we use math.mod(x,y) means math.mod(n,2)

Write a class for printing Even and Odd number is Salesforce Apex.

public class EvenOddNum {


    public void printEvenOdd(Integer n){

           if((math.mod(n, 2))==0){

                 system.debug('Even Number');

            }

             else{

                  system.debug('Odd Number');

             }

         }

    }


To Execute-

//EvenOddNum Obj = new EvenOddNum();

//obj.printEvenOdd(10);   //Even Number

//obj.printEvenOdd(7); // Odd Number



In this above program, we need to use if else statement for checking even or odd number.

If you enter n (can be a any natural number) then output should be Even or Odd.

In this program we use math.mod(x , y) for chcking logic and compare with zero (0)
                               ((n%2)==0) // % is a modulus. 

                               operator '%' that isn't valid in Apex.

                                so we use math.mod(x,y) means math.mod(n,2)


      In this logic any number should be divided by 2 means Remainder should be zero and we          compare this Remainder with  zero and we get output as a Even.
  Any number is divided by 2 and reminder is other than zero number and compare reminder  with zero  that means condition is not satisfied  that means it is a Odd number.

 Logic for Even Number
Suppose n=10;
(n%2)==0 
10/2=0  // Remainder is zero 
compare remainder(0) with ==0 . (0 == 0)
This condition is satisfied means 
If this value comapre with zero and condition is match means it is a Even Number
 

 Logic for Odd Number
Suppose n=11;
(n%2)==0
11/2=1 // Remainder is 1 
compare remainder(1) with ==0 (1 != 0)
Condition is not satisfied means it is Odd Number
If this value comapre with zero and condition is not match means it is a Odd Number




Even Odd Number Program in Apex

How to Print Even Odd number in Salesforce  Apex In this program, we check even odd number in Apex. Here is the logic of even and odd number...