HomeCSharpC# Program to Find the Factors of the Given Number

C# Program to Find the Factors of the Given Number


This C# program is designed to calculate and display the factors of a specified positive integer. Factors are the numbers that evenly divide the given number without leaving a remainder.

Problem Statement

You are tasked with writing a program that finds all the factors of a given positive integer number. Factors are the positive integers that evenly divide the given number without leaving a remainder.

C# Program to Find the Factors of the Given Number

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a number: ");
        int number = int.Parse(Console.ReadLine());

        Console.WriteLine("Factors of " + number + " are:");
        FindFactors(number);

        Console.ReadLine();
    }

    static void FindFactors(int num)
    {
        for (int i = 1; i <= num; i++)
        {
            if (num % i == 0)
            {
                Console.WriteLine(i);
            }
        }
    }
}

How it Works

  1. User Input: The first step is to get the value of n from the user or from some data source.
  2. Initialization: Initialize a loop variable, usually called i, to start at 1. This variable will be used to check each number from 1 to n to see if it’s a factor.
  3. Factor Checking Loop: Enter a loop that iterates from i = 1 to i = n. For each iteration of the loop, do the following:a. Check if n is divisible by i (i.e., n % i == 0). If the remainder of the division is 0, it means that i is a factor of n.b. If i is a factor, print or store the value of i because it’s one of the factors of n.c. Increment the value of i to move to the next number in the loop.
  4. Loop Termination: Continue the loop until i reaches n. This ensures that all numbers from 1 to n are checked for being factors.
  5. Display Factors: After the loop completes, you have found all the factors of n. You can display these factors to the user or use them for further calculations.
  6. Program Ends: The program ends, and you have successfully found and processed the factors of the given number n.

Input/ Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...