In this example, a mutiplication table will be generated for any given number by the user as an input. The result will be then displayed on the console.
#include <stdio.h> #include <math.h> int main() { int num; printf("Please enter a number: "); scanf("%d", &num); printf("\n"); for(int i=1; i<=10; i++) { printf("%d * %d = %d\n", num, i, num*i); } return 0; }
First, a variable num will be declared which will store the number entered by the user. In this program we want to generate a multiplication table for any given number till 10. For this purpose, we require for-loop. The syntax for for-loop is following,
for (initialization statement; terminating condition; increment/decrement) {
statements;
}
The for-loop will continue to work until the terminatig condition is not fulfilled. For-loop is mostly used in conditions where we exactly know the terminating condition. In this example, i is the initialization stametement, i<=10 is the terminating condition and i++ is the increment. The number num will be passed to the for-loop. The i will start from 1 beacuse i is equal to 1 in the beginning. Then in the next line num will be multiplied to the i and and the result be dislpayed on the console. The for-loop will again check for the termnating condition and if i is not greater than 10 the whole process will continue until the terminating condition is not satisfied.
Output
Please enter a number: 5 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50