Ask a Teacher
how to use modulus function in c program? |
1. The modulus operator is useful in a variety of circumstances. It is commonly used to take a randomly generated number and reduce that number to a random number on a smaller range, and it can also quickly tell you if one number is a factor of another. If you wanted to know if a number was odd or even, you could use modulus to quickly tell you by asking for the remainder of the number when divided by 2. #include <iostream> using namespace std; int main() { int num; cin >> num; // num % 2 computes the remainder when num is divided by 2 if ( num % 2 == 0 ) { cout << num << " is even ";
}
return 0; }
|