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
- User Input: The first step is to get the value of
nfrom the user or from some data source. - Initialization: Initialize a loop variable, usually called
i, to start at 1. This variable will be used to check each number from 1 tonto see if it’s a factor. - Factor Checking Loop: Enter a loop that iterates from
i= 1 toi=n. For each iteration of the loop, do the following:a. Check ifnis divisible byi(i.e.,n % i == 0). If the remainder of the division is 0, it means thatiis a factor ofn.b. Ifiis a factor, print or store the value ofibecause it’s one of the factors ofn.c. Increment the value ofito move to the next number in the loop. - Loop Termination: Continue the loop until
ireachesn. This ensures that all numbers from 1 tonare checked for being factors. - 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. - Program Ends: The program ends, and you have successfully found and processed the factors of the given number
n.
Input/ Output
