factore of 20 in c+
To find the factors of 20 in C++, you can use the following code:
#include <iostream>
int main() {
int number = 20;
std::cout << "The factors of " << number << " are: ";
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
std::cout << i << " ";
}
}
std::cout << std::endl;
return 0;
}
Explanation of each step:
#include <iostream>
: This is a preprocessor directive that includes the iostream library, which is needed for input and output operations in C++.int main()
: This is the main function where the program execution starts.int number = 20;
: Declares and initializes a variablenumber
with the value 20. This is the number for which we want to find the factors.std::cout << "The factors of " << number << " are: ";
: Outputs a message to the console indicating that the program will display the factors of the given number.for (int i = 1; i <= number; i++) {
: A for loop that iterates from 1 to the given number.if (number % i == 0) {
: Checks if the current value ofi
is a factor of the given number using the modulo operator (%
).std::cout << i << " ";
: If the current value ofi
is a factor, it is outputted to the console.std::cout << std::endl;
: Outputs a new line to the console.return 0;
: The main function ends and returns 0, indicating successful program execution.
This code will display the factors of 20 as: "The factors of 20 are: 1 2 4 5 10 20".