Checking for Odd or Even

CCBeginner
Practice Now

Introduction

The lab aims to help students understand a program implemented using bitwise operators to determine if a number is odd or even. Additionally, it also provides a method to check if a number is odd or even without using the modulus operator.

Bitwise Operator

  1. Begin by explaining to the students what the bitwise operator is.
  2. Explain how the program checks for odd and even numbers using bitwise operators.
    • If a number is odd, it has a 1 in the least significant bit (LSB).
    • If a number is even, it has a 0 in the least significant bit (LSB).
  3. Provide the code implementation to the students and ask them to copy the code into their main.c file in the ~/project/ directory.
  4. The code implementation should be as follows:
#include<stdio.h>

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int x;
    for(x = 0; x <= 10; x++)
    {
        if(x&1) // if number is odd
            printf("\t\t\t%d is odd\n",x);
        else if(!(x&1)) // ! is used inside if to reverse the boolean value
            printf("\t\t\t%d is even\n",x);
    }

    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Finding Odd or Even without using Modulus Operator

  1. Explain to the students that it is possible to find if a number is odd or even without using the modulus operator.
  2. Briefly describe to them how this is achieved.
    • If a number is even, then dividing it by 2 and multiplying it again by 2 should result in the original number.
    • If a number is odd, then dividing it by 2 and multiplying it again by 2 should not result in the original number.
  3. Provide the code implementation to the students and ask them to copy it into their main.c file in the ~/project/ directory.
  4. The code implementation should be as follows:
#include<stdio.h>

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int n;
    printf("Enter a number:  ");
    scanf("%d",&n);

    if((n/2)*2 == n)
        printf("\n\n\t\t %d is Even\n", n);
    else
        printf("\n\n\t\t %d is Odd\n", n);

    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Test

  1. Ask the students to test both code implementations.
  2. Run the code and check whether the output is as expected.

Summary

Students are now familiar with two methods of checking whether a number is odd or even. They can implement these techniques in any C program to achieve their desired functionality.

Other C Tutorials you may like