Friday, 10 January 2014

make comparison between numbers in c

Making Comparison Between Two Numbers/Integers

Result of Comparison Can be
1.Equal
2.Less Than
3.Greater Than

1. Comparison For Equality

Using equality operator(==)


int is_equal(int a, int b){
        return (a==b);
}

Using EX-OR bitwise Operator(^)


int is_equal(int a, int b){
        return (!(a^b));
}

Using Pre-Processor Macro(Preferred Method)


#define IS_EQUAL(A,B) (!(A^B))

OR


#define IS_EQUAL(A,B) (A==B)

Complete Program Using all above code snippet


#include <stdio.h>
#define IS_EQUAL(A,B) (A==B)
#define IS_EQUAL1(A,B) (!(A^B))

int is_equal(int a, int b){
        return (a==b);
}

int is_equal1(int a, int b){
        return (!(a^b));
}

int main(int argc, char *argv[]){
        printf("isequal=%d\n", is_equal(10,10));
        printf("isequal=%d\n", is_equal1(10,10));
        printf("isequal=%d\n", IS_EQUAL(10,10));
        printf("isequal=%d\n", IS_EQUAL1(10,10));
        return 0;
}

2. Comparison For Smaller or Lesser Number

Using less than operator(<)


int is_less(int a, int b){
        return (a<b);
}

Using Pre-Processor Macro(Preferred Method)


#define IS_LESS(A,B) (A<B)

Complete Program using above methods


#include <stdio.h>
#define IS_LESS(A,B) (A<B)

int is_less(int a, int b){
        return (a<b);
}

int main(int argc, char *argv[]){
        int num1,num2;
        num1=20;
        num2=10;
        if(is_less(num1,num2))
                printf("%d is less than %d\n", num1, num2);
        if(IS_LESS(num1,num2))
                printf("%d is less than %d\n", num1, num2);
        if(num1<num2)
                printf("%d is less than %d\n", num1, num2);
        return 0;
}

3. Comparison For Greater or Larger Number

Using less than operator(>)


int is_less(int a, int b){
        return (a>b);
}

Using Pre-Processor Macro(Preferred Method)


#define IS_LESS(A,B) (A>B)

Complete Program using above methods


#include <stdio.h>
#define IS_LESS(A,B) (A>B)

int is_less(int a, int b){
        return (a>b);
}

int main(int argc, char *argv[]){
        int num1,num2;
        num1=20;
        num2=10;
        if(is_less(num1,num2))
                printf("%d is greater than %d\n", num1, num2);
        if(IS_LESS(num1,num2))
                printf("%d is greater than %d\n", num1, num2);
        if(num1>num2)
                printf("%d is greater than %d\n", num1, num2);
        return 0;
}


No comments:

Post a Comment