Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print first m multiples of n in C#
To print the first m multiples of a given number n in C#, we use a loop to iterate and calculate each multiple. This is useful for displaying multiplication tables or generating sequences.
Syntax
Following is the basic syntax for printing multiples using a loop −
for (int i = 1; i <= m; i++) {
Console.WriteLine(n * i);
}
Where n is the number whose multiples we want to find, and m is the count of multiples to print.
Using For Loop
The most straightforward approach is to use a for loop to generate the first m multiples −
using System;
public class Demo {
public static void Main() {
int n = 6, m = 5;
Console.WriteLine("First " + m + " multiples of " + n + ":");
for (int i = 1; i <= m; i++) {
Console.WriteLine(n + " x " + i + " = " + (n * i));
}
}
}
The output of the above code is −
First 5 multiples of 6: 6 x 1 = 6 6 x 2 = 12 6 x 3 = 18 6 x 4 = 24 6 x 5 = 30
Using While Loop
Alternatively, we can use a while loop to achieve the same result −
using System;
public class Demo {
public static void Main() {
int n = 7, m = 4;
int counter = 1;
Console.WriteLine("First " + m + " multiples of " + n + ":");
while (counter <= m) {
Console.WriteLine(n * counter);
counter++;
}
}
}
The output of the above code is −
First 4 multiples of 7: 7 14 21 28
Using Array to Store Multiples
We can also store the multiples in an array and then display them −
using System;
public class Demo {
public static void Main() {
int n = 9, m = 6;
int[] multiples = new int[m];
// Store multiples in array
for (int i = 0; i < m; i++) {
multiples[i] = n * (i + 1);
}
// Display the multiples
Console.WriteLine("First " + m + " multiples of " + n + ":");
for (int i = 0; i < m; i++) {
Console.WriteLine(multiples[i]);
}
}
}
The output of the above code is −
First 6 multiples of 9: 9 18 27 36 45 54
Comparison
| Approach | Memory Usage | Best Use Case |
|---|---|---|
| For Loop | Low | Simple display of multiples |
| While Loop | Low | When loop condition is complex |
| Array Storage | Higher | When multiples need to be reused |
Conclusion
Printing the first m multiples of n in C# can be accomplished using for loops, while loops, or by storing values in arrays. The for loop approach is most commonly used for its simplicity and readability when generating sequential multiples.
