So far we’ve seen sequential flow of our programs. Next we saw decision control statements like if, if else, else if etc. Now lets learn about loop control statements present in C programming language.
In this video tutorial lets learn about while loop in particular.
Related Read:
Programming Interview / Viva Q&A: 5 (Infinite or Indefinite while loop)
#include < stdio.h > int main() { while(pre_test_condition) statement1; return 0; }
Here while is the keyword. Inside parenthesis we need to write the condition. These conditions must evaluate to Boolean value. i.e., true(non-zero number) or false(0);
The ‘body of while’ loop keeps executing until the condition is true. Control exits while loop once the condition is false.
#include < stdio.h > int main() { while(pre_test_condition) { statement1; statement2; } return 0; }
Enclose the statements with curly braces if there are multiple statements within while loop or body of while loop.
while loop in C programming Language
#include < stdio.h > int main() { int count = 1; while(count <= 5) { printf("%d\n", count); count = count + 1; } printf("End of loop\n"); return 0; }
Output:
1
2
3
4
5
End of loop
In above C source code, variable count is initialized to 1. Inside while condition we check if variable count is less than or equal to 5. Until variable count is less than or equal to 5, the while loop keeps executing. Inside body of the while loop we increment the value of count by 1 upon each execution of the loop. The condition is checked on execution of the loop. Once variable count is more than 5, the condition becomes false count <= 5 (once count value is 6, the condition becomes false), the execution control exits while loop.
Note: Here the loop execution counter is called ‘loop counter’ or ‘index variable’.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert