how to check is some number is divisible by 3 in c++
To check if a number is divisible by 3 in C++, you can use the modulo operator (%). The modulo operator returns the remainder of the division between two numbers. If the remainder is 0 when dividing the number by 3, then the number is divisible by 3.
Here is an example code snippet that checks if a number is divisible by 3:
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number % 3 == 0) {
std::cout << "The number is divisible by 3." << std::endl;
} else {
std::cout << "The number is not divisible by 3." << std::endl;
}
return 0;
}
Explanation:
The code begins by including the necessary header file,
iostream
, which provides input and output functionalities.The
main()
function is the entry point of the program.We declare an integer variable
number
to store the user input.The
std::cout
statement is used to prompt the user to enter a number.The
std::cin
statement is used to read the user input and store it in thenumber
variable.The
if
statement checks if the number is divisible by 3. The modulo operator%
is used to find the remainder of the division betweennumber
and 3. If the remainder is 0, then the number is divisible by 3.If the condition in the
if
statement is true, the program prints the message "The number is divisible by 3." usingstd::cout
.If the condition in the
if
statement is false, the program prints the message "The number is not divisible by 3." usingstd::cout
.Finally, the
return 0;
statement indicates that the program has finished executing.
By running this code and entering a number, you can determine if the number is divisible by 3 or not.