Source Code
#include <iostream>
using namespace std;
int main()
{
int num; // Declare a variable to hold the number
cout << "Enter a number: "; // Prompt the user to enter a number
cin >> num; // Read the number from the standard input stream
if (num % 2 == 0) // Check if the number is even
cout << num << " is even" << endl; // Print "even" if the number is even
else
cout << num << " is odd" << endl; // Print "odd" if the number is odd
return 0;
}
Code Explanation
This program declares a variable num
of type int
to hold the number entered by the user. It then uses the cout
object to print a prompt asking the user to enter a number, and the cin
object to read the number from the standard input stream.
To check if the number is even, the program uses the modulo operator %
to find the remainder when num
is divided by 2. If the remainder is 0, the number is even (since it is divisible by 2). If the remainder is not 0, the number is odd.
The program uses an if
statement to check the value of the remainder and print the appropriate message using the cout
object.
What is if-else statment?
In C++, the if-else
statement is a control flow statement that allows you to execute a block of code conditionally. It has the following syntax:
if (expression)
{
// code to execute if expression is true
}
else
{
// code to execute if expression is false
}
The if
clause specifies a condition, and the code inside the {}
brackets following the if
clause is executed if the condition is true. The else
clause specifies an alternative block of code to execute if the condition is false.
For example, consider the following code:
int num = 5;
if (num > 0)
{
cout << "num is positive" << endl;
}
else
{
cout << "num is negative or zero" << endl;
}
In this example, the condition num > 0
is evaluated as true, so the code inside the if
clause is executed, and the program prints "num is positive"
to the standard output stream.
If the value of num
were negative or zero, the condition would be false, and the code inside the else
clause would be executed, printing "num is negative or zero"
to the output stream.
Leave a Reply