Determine Even or Odd Numbers in C++

Beginner

Introduction

In this lab, you will learn how to determine whether the entered number is even or odd through if-else statements. You will learn to write a C++ program that will take the input number from the user and check whether it is even or odd using the % operator.

Include Libraries

In the first step of the C++ program, we will include the required libraries that will help us to run the C++ program. Add the below code to the ~/project/main.cpp file:

#include<bits/stdc++.h>
using namespace std;

Define Function to Check Number

In the second step of the program, we will create a function to determine if the entered number is even or odd. This function should take an integer as input and should print whether the number is even or odd. Add the below code to the ~/project/main.cpp file:

void check_number(int num){
    if(num%2==0){
        cout<<num<<" is an even number";
    }
    else{
        cout<<num<<" is an odd number";
    }
}

Take Input from User

In the third step of the program, we will take the input number from the user and pass it to the function created in step 2. Add the below code to the ~/project/main.cpp file:

int main(){
    int num;
    cout<<"Enter the number you want to check:-";
    cin>>num;
    check_number(num);
    return 0;
}

Compile and Execute the Code

In the fourth step of the program, we will compile and execute the main.cpp file to get the output. We will compile the code using the GCC compiler and then execute the compiled code. Run the below commands in the terminal to compile and execute the code.

$ g++ ~/project/main.cpp -o main
$ ./main

Now, provide the number input when asked for the number to check.

Summary

In this lab, you have successfully learned how to determine whether the entered number is even or odd through if-else statements. You have learned to write a C++ program by defining a function that will take the input number from the user and check whether it is even or odd using the % operator. Finally, you have compiled and executed the code in the terminal to see the output.

Other Tutorials you may like