Here's a Python code to generate a multiplication table:
python
def generate_multiplication_table(size):
"""
Generates a multiplication table of the given size.
Args:
size (int): The size of the multiplication table (size x size)
Returns:
str: A formatted multiplication table as a string
"""
# Calculate the maximum width needed for formatting
max_product = size * size
max_width = len(str(max_product)) + 1
# Create the header row
header = " " * (max_width + 1)
for i in range(1, size + 1):
header += f"{i:>{max_width}}"
table = header + "\n"
# Create the separator line
separator = "-" * (max_width + 1)
for _ in range(size):
separator += "-" * max_width
table += separator + "\n"
# Generate each row of the table
for i in range(1, size + 1):
row = f"{i:>{max_width}}|"
for j in range(1, size + 1):
product = i * j
row += f"{product:>{max_width}}"
table += row + "\n"
return table
# Example usage
if __name__ == "__main__":
try:
size = int(input("Enter the size of the multiplication table: "))
if size <= 0:
print("Please enter a positive integer.")
else:
print("\nMultiplication Table:")
print(generate_multiplication_table(size))
except ValueError:
print("Invalid input. Please enter a positive integer.")
How to Use:
Run the program
Enter the size of the multiplication table you want (e.g., 10 for a 10×10 table)
The program will display a nicely formatted multiplication table
Features:
Automatically adjusts column width based on the largest product