Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.611220'
Loops: For loop: Print multiplication table
Loops: For loop: Print multiplication table
Task: Generate a multiplication table:
Write a C program that uses nested for loops to generate a multiplication table. The size of the table (number of rows and columns) should be determined by the user. Display the multiplication table using printf().
Hint:
Solution
#include
int main() {
int numRows, numCols;
printf("Enter the number of rows in the multiplication table: ");
scanf("%d", &numRows);
printf("Enter the number of columns in the multiplication table: ");
scanf("%d", &numCols);
if (numRows <= 0 || numCols <= 0) {
printf("Invalid number of rows or columns. Please enter positive integers.\n");
return 0;
}
int row, col;
for (row = 1; row <= numRows; row++) {
for (col = 1; col <= numCols; col++) {
printf("%d\t", row * col);
}
printf("\n");
}
return 0;
}
Explanation
In this example, the program prompts the user to enter the number of rows and columns in the multiplication table and stores them in the numRows and numCols variables, respectively. It performs input validation to ensure valid numbers of rows and columns. The program uses nested for loops to generate the multiplication table. The outer for loop controls the rows of the table, and the inner for loop controls the columns. Inside the nested loops, the program multiplies the current row number (row) by the current column number (col) to calculate the value for each cell in the table. It then uses printf() to display the calculated value followed by a tab character (\t) to separate the values in each column. After printing all the values in a row, the program moves to the next line using printf("\n") to start a new row. The program repeats this process for each row and column until the outer for loop terminates.