In: Computer Science
(1) Explain that a counter-controlled loop is useful when you know how many times a set of statements needs to be executed.
(2) Discuss the implementations of the Fibonacci Number program at the end of this section to consolidate the students’ understanding of the while loop repetition structures.
Counter controlled loop:
The loop which is controlled by counter variable.
For example if we want to print 1 to 10 numbers, we can use while loop or for loop .
WHILE loop:
Initially we have to assign initial value to counter variable, and condition is placed in while loop upto what value we have to continue loop. Inside the loop we have to increment or decrement the counter variable.
//C Code for printing 1 to 10 numbers using while loop
int main() { int counter =1; //Initally counter=1 while(counter<=10) // loop runs until value of counter is less than or equal to 10 { printf(" %d ",counter); counter++; }//loop exits when the value of counter becomes 11. }//close main function |
Another example to print message "Hello" for 5 times
counter=1; while(counter<=5) { printf("Hello"); counter=counter+1; } |
2) Printing n th Fibonacci number
Fibo(n)=Fibo(n-2)+Fibo(n-1),
N th Fibonacci number is sum of its two previous fibonacci numbers in the series
Initially first Fibonacci number A=1, Second Fibonacci Number B=2 , then third Fibonacci number C is A+B.
To compute 4th Fibonacci number, we have to update the values of A and B
put B value in A, Put C value in B and new Fibonacci number is A+B
int main() int A=1,B=2,C, counter=1; while(counter<=10) { C=A+B; printf("%d ", C); // Now update A and B values A=B; B=C; counter=counter+1; } return 0; } |
For any queries, post in comment section.