Skip to main content

Command Palette

Search for a command to run...

Determining Even and Odd Numbers in C++

Published
3 min read

Introduction

One of the basic tasks in programming is determining whether a given number is even or odd. This simple yet fundamental problem helps beginners understand conditional statements and the modulo operator. In this blog post, we will write a C++ program to determine if a number is even or odd.

The Concept

A number is even if it is divisible by 2 without a remainder. Conversely, a number is odd if it is not divisible by 2, which means there will be a remainder of 1. The modulo operator (%) is used to find the remainder of a division operation. If the remainder when dividing by 2 is zero (num % 2 == 0), the number is even; otherwise, it is odd.

The Code

Let's dive into the code. Below is a simple C++ program to determine if a number entered by the user is even or odd.

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    string result = (num % 2 == 0) ? "Even" : "Odd";

    cout << "The number " << num << " is " << result << "." << endl;

    return 0;
}

Explanation

  1. Header Inclusion: We include the iostream library, which allows us to use input and output streams.

     #include <iostream>
    
  2. Namespace Declaration: We use the standard namespace to avoid prefixing std:: before every standard library usage.

     using namespace std;
    
  3. Main Function: The entry point of our C++ program is the main function.

     int main() {
    
  4. Variable Declaration: We declare an integer variable num to store the user's input.

     int num;
    
  5. User Prompt: We prompt the user to enter a number.

     cout << "Enter a number: ";
    
  6. Input Handling: We read the input from the user and store it in the num variable.

     cin >> num;
    
  7. Even/Odd Check: We use the ternary operator to check if the number is even or odd. If num % 2 equals 0, result is assigned "Even"; otherwise, it is assigned "Odd".

     string result = (num % 2 == 0) ? "Even" : "Odd";
    
  8. Output Result: We print the result to the console.

     cout << "The number " << num << " is " << result << "." << endl;
    
  9. End of Program: The program ends with a return statement.

     return 0;
    

Conclusion

This simple program demonstrates the use of basic input/output operations, the modulo operator, and the ternary conditional operator in C++. By understanding and practicing these fundamental concepts, beginners can build a solid foundation in C++ programming. This small exercise is a stepping stone towards more complex programs and applications.

Happy coding!

More from this blog

Untitled Publication

13 posts