Introduction
In this lab, we will write a C++ program to find the divisors of a given number. A divisor of a number is a positive integer that divides the number without leaving a remainder.
In this lab, we will write a C++ program to find the divisors of a given number. A divisor of a number is a positive integer that divides the number without leaving a remainder.
main
functioniostream
library for input and outputstdlib
library for system functions like clrscr()
and getch()
main
functionn1
to store the input number and another variable i
to use in the for-loopsystem("clear")
to clear the screen#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int n1, i;
system("clear");
cout<<"Enter the number to find it's divisors : ";
cin>>n1;
cout<<"\nThe divisors are :\n";
for(i = 1 ; i <= n1 ; i++)
{
if(n1 % i == 0)
{
cout<<"\t"<<i ;
}
}
return 0;
}
cout
function to display the message to prompt the user for inputcin
function to get the input number from the user and store it in the n1
variablecout<<"Enter the number to find it's divisors : ";
cin>>n1;
i = 1
and goes up to n1
i
using the modulo (%
) operatori
as the divisorfor(i = 1 ; i <= n1 ; i++)
{
if(n1 % i == 0)
{
cout<<"\t"<<i ;
}
}
In this lab, we learned how to find the divisors of a given number using a C++ program. We used a for-loop to iterate over all possible divisors and checked if the input number is divisible by the current divisor. We also learned how to read input from the user, compile and run the program, and display the output in the console.