Program to Find Divisor of a Number

C++C++Beginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") subgraph Lab Skills cpp/variables -.-> lab-96239{{"`Program to Find Divisor of a Number`"}} cpp/data_types -.-> lab-96239{{"`Program to Find Divisor of a Number`"}} cpp/operators -.-> lab-96239{{"`Program to Find Divisor of a Number`"}} cpp/conditions -.-> lab-96239{{"`Program to Find Divisor of a Number`"}} cpp/for_loop -.-> lab-96239{{"`Program to Find Divisor of a Number`"}} end

Include necessary libraries and set up the main function

  • Include the iostream library for input and output
  • Include the stdlib library for system functions like clrscr() and getch()
  • Begin the main function
  • Declare a variable n1 to store the input number and another variable i to 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 cout function to display the message to prompt the user for input
  • Use the cin function to get the input number from the user and store it in the n1 variable
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 = 1 and goes up to n1
  • Check if the input number is divisible by i using the modulo (%) operator
  • If the input number is divisible, print i as 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.

Other C++ Tutorials you may like