Odd or Even in C++ - How to Find Out (and Other Multiples)

C++ tutorialIn this tutorial from our C++ e-book, we will learn how to find out if a given number is odd or even (as well as how to use other multiples than 2).

Odd or Even in C ++

Now that we've learned about the IF/ELSE conditional statement test as well as the mathematical operators, let's learn how to use the remainder division operator (%) to check and find out if a given number is odd or even.

Even numbers are actually numbers that are multiples of 2.
That is, they are formed by the number 2 multiplied by any other integer.

See some examples:
2x1 = 2
2 x 2 = 4
2x3 = 6
2 x 4 = 8
...

That is, to know if a number stores a pair value, just test if its remainder of division by 2 is equal to 0. The conditional test that represents this is:
  • (num % 2 == 0)

If such an operation returns true, it is even.
Otherwise (ELSE), it is because the number is odd (it is always odd or even).

Here's what our C ++ code looks like from a program that asks the user for an integer and says whether it's even or odd:
#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Type a number: ";
    cin >> num;

    if (num%2==0)
        cout <<"It's even"<<endl;
    else
        cout <<"It's odd"<<endl;
    return 0;
}

Multiple of 3

As we said, the even number is nothing more than a multiple of 2.
There are also multiples of 3, 4, 5, ...

For example, multiple numbers of 3 are:
3x1 = 3
3x2 = 6
3x3 = 9
3x4 = 12

To find out if a given number is a multiple of 3, just check the rest of the division of any number by 3, here's how our code looks:
#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Type a number: ";
    cin >> num;

    if (num%3==0)
        cout <<"Multiple of 3"<<endl;
    else
        cout <<"Not a 3 multiple"<<endl;
    return 0;
}

Multiple numbers

Make a program that receives two integers: num1 and num2.
Then verify that num1 is a multiple of num2.

#include <iostream>
using namespace std;

int main()
{
    int num1, num2;

    cout << "First number : ";
    cin >> num1;

    cout << "Second number: ";
    cin >> num2;

    if (num1%num2==0)
        cout <<num1<<" is multiple of "<<num2<<endl;
    else
        cout <<num1<<" is not a multiple of "<<num2<<endl;
    return 0;
}

No comments:

Post a Comment