Friday, 27 December 2013

finding a number is even or odd using c

Q: Write a C program to Find whether a Number is Odd or Even?

Finding Odd or Even Using % operator.

#include<stdio.h>

int main(int argc, char * argv[]){
        int num=0;
        printf("\nInput a Number for Test:");
        scanf(" %d",&num);
        if(num%2 == 0){
                printf("%d IS EVEN\n",num);
        }
        else{
                printf("%d IS ODD\n", num);
        }
        return 0;
}
Compiling and Running Under Linux

rajesh@ubuntu:~/rajesh/c$ gcc iseven.c -o isev
rajesh@ubuntu:~/rajesh/c$ ./isev

Input a Number for Test:20
20 IS EVEN
rajesh@ubuntu:~/rajesh/c$ ./isev 

Input a Number for Test:11
11 IS ODD
Finding Odd or Even Using bit-wise operator.

#include<stdio.h>

int main(int argc, char * argv[]){
        int num=0;
        printf("\nInput a Number for Test:");
        scanf(" %d",&num);

        if(!(num&0x01)){
                printf("%d IS EVEN\n",num);
        }
        else{
                printf("%d IS ODD\n", num);
        }
        return 0;
}
Compiling and Running Under Linux

rajesh@ubuntu:~/rajesh/c$ gcc iseven1.c -o isev1
rajesh@ubuntu:~/rajesh/c$ ./isev1

Input a Number for Test:20
20 IS EVEN
rajesh@ubuntu:~/rajesh/c$ ./isev1 

Input a Number for Test:7
7 IS ODD
Finding Odd or Even Using bit-wise operator.Getting Input from Command Line.

#include<stdio.h>

int main(int argc, char * argv[]){
        int num=atoi(argv[1]);

        if(!(num&0x01)){
                printf("%d IS EVEN\n",num);
        }
        else{
                printf("%d IS ODD\n", num);
        }
        return 0;
}
Compiling and Running Under Linux

rajesh@ubuntu:~/rajesh/c$ gcc iseven2.c -o isev2
rajesh@ubuntu:~/rajesh/c$ ./isev2 12
12 IS EVEN
rajesh@ubuntu:~/rajesh/c$ ./isev2 13
13 IS ODD

No comments:

Post a Comment