Introduction
Creating a multiplication table is a classic programming exercise, excellent for grasping the basics of loops and user input in C#. In this guide, we'll develop a program in C# that displays the multiplication table for a given integer.
Step-by-Step Process
We will break down the task into manageable steps, ensuring even beginners can follow along and understand each part of the program.
Step 1: Set Up the Development Environment
Make sure you have a C# development environment ready. This could be in Microsoft Visual Studio, Visual Studio Code, or any other IDE supporting C#.
Step 2: Start a New Console Application
- Open your IDE and create a new Console Application.
- Name your project, for example, MultiplicationTable.
Step 3: Writing the Code
We will write a program that asks the user for a number and then prints the multiplication table for that number up to 10.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number to display its multiplication table: ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Multiplication table of {number}:");
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"{number} * {i} = {number * i}");
}
}
}
Explanation:
- using System; is included to use the Console class.
- We declare a Program class and the Main method.
- Console.Write prompts the user to enter a number.
- The entered number is read using Console.ReadLine(), converted to an integer, and stored in the number variable.
- A for loop runs from 1 to 10. In each iteration, it calculates the product of the input number and the loop counter (i) and prints it in the format: [number] * [i] = [product].
Step 4: Compile and Run the Program
- Build and run your application.
- When prompted, enter a number.
- The console will display the multiplication table for the entered number up to 10.
Conclusion
This simple C# program demonstrates the use of loops, user input, and basic arithmetic operations. Such programs are not only great for learning but also serve as a foundation for building more complex logic in future projects.
Challenge for Practicing
Try enhancing the program by allowing the user to specify both the number and how far the multiplication table should go (e.g., up to 15 or 20 instead of 10). This modification will provide additional practice with user input and loops in C#.