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.
Include necessary libraries and set up the main function
- Include the
iostreamlibrary for input and output - Include the
stdliblibrary for system functions likeclrscr()andgetch() - Begin the
mainfunction - Declare a variable
n1to store the input number and another variableito use in the for-loop - Use the function
system("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;
}
Get the input from the user
- Use the
coutfunction to display the message to prompt the user for input - Use the
cinfunction to get the input number from the user and store it in then1variable
cout<<"Enter the number to find it's divisors : ";
cin>>n1;
Find the divisors of the input number
- Use a for-loop that starts from
i = 1and goes up ton1 - Check if the input number is divisible by
iusing the modulo (%) operator - If the input number is divisible, print
ias the divisor
for(i = 1 ; i <= n1 ; i++)
{
if(n1 % i == 0)
{
cout<<"\t"<<i ;
}
}
Summary
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.



