Program to Display Factors of a Number - (C# Basic Programs)
Finding the factors of a given number is a common programming exercise that is helpful in many applications, such as calculating prime numbers and solving mathematical problems. In this tutorial, we will discuss a program in C# programming language to display the factors of a number.
Syntax
The syntax for finding the factors of a number in C# is as follows:
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
Console.Write(i + " ");
}
}
Example
using System;
namespace FactorOfNumber
{
class Program
{
static void Main(string[] args)
{
int number;
Console.Write("Enter a positive integer: ");
number = int.Parse(Console.ReadLine());
Console.Write("Factors of " + number + " are: ");
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
{
Console.Write(i + " ");
}
}
Console.ReadKey();
}
}
}
Output:
Enter a positive integer: 24
Factors of 24 are: 1 2 3 4 6 8 12 24
Explanation
In this program, we first prompt the user to input a positive integer. We then use a for loop to iterate over all possible factors of the given number. If the current index i is a factor of the number (determined by checking if the remainder after dividing number by i is zero), we print it to the console.
Use
The program to display factors of a number is useful in many real-world applications, such as calculating prime numbers, finding factors of large numbers in cryptography, and solving mathematical problems.
Summary
In this tutorial, we have discussed a program in C# programming language to display the factors of a given number. We have seen the syntax, example, explanation, and use of a program to display factors of a number. By practicing these exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.