Hello my friends. To get to know what is “counter controlled repetition” we should first get to know the terms related to it.
What is a counter?
A counter is a counting mechanism. A counter is a variable to which a value is set and used along with while statement or other conditional statement. Unless and until the condition remains true the value of the counter keeps increasing/decreasing/changing until the condition becomes false. It is advised to initialize the counter accordingly while declaring.
Consider the following program:
int counter=1, n,product;
printf(“The a number whose mathematical table you want: “);
printf(“\nThe table generated is given below.”);
printf(“%d * %d = %d\n”,n,counter,product);
Here, while statement is a control statement. It has been used to check the condition weather counter is less the or equal then 10 or not(counter<=10). Until this statement is true the following block of statement will execute. This is called looping.
Take the first loop here i.e., counter=1, then the condition while(counter<=10) will hold true and the block of code will execute and it will generate the product i.e., product=n*counter. Let us assume 5 as the value of ’n’ given as input to generate the table of 5. Then the first loop execution of code will be this 5*1 = 5(since, n(5)*counter(1) will give 5 which will assigned to product). And the output of the first loop execution will be like this:
5*1 = 5
Also there is one more statement in the block – counter=counter+1. It is evident from the statement that it has been made to increment the value of the counter by 1. So, at the end of the execution of the first block the value of the counter will increase and the value of counter will be 2 now. It will again go to while statement and check the condition. If the while condition will hold true it will keep executing the block of code until the condition will become false i.e., the value of counter will become 11. At this point the block will not be executed and execution control will be passed to the next block of code or the next statement in the program for execution.
The output of the program:
The a number whose mathematical table you want:5
The table generated is given below.
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