Interview Questions
- What are the different parts of a for loop?
- Can comma be used in a for loop?
- Is for (;;); a valid loop?
- What is the use of a break statement in a loop?
- What is the use of a continue in a loop?
What are the different parts of a for loop?
Below example shows all the different parts of the for loop. Initialization, Condition Check and Increment.
#include <stdio.h> #include <stdlib.h> int main() { for ( int i = 0; //Initialization i< 25; //Condition Check i++ // Increment ){ printf("i:%d",i); //Body of For Loop } }
Can comma be used in a for loop?
Below example shows a comma used in a for loop. In the below example Initialization and Increment parts of the for loop use the comma operator.
#include <stdio.h> #include <stdlib.h> int main() { for ( int i = 0,j=100; //Initialization i< 25; //Condition Check i++,j-- // Increment ){ printf("i:%d j:%d",i,j); //Body of For Loop } }
Is for (;;); a valid loop?
Yes. It is an infinite loop.
What is the use of a break statement in a loop?
break statement moves the execution out of the loop. Consider the example program below: We want to find how many numbers in the array are less than hundred. We already know that the array is sorted in increasing order. Once we find a number greater than 100, we can be sure that rest of the numbers in the array are even bigger. So, we do not need to check them. Once we find a number greater than 100, we break out of the loop.
#include <stdio.h> #include <stdlib.h> int main() { int sortedNumbers[] = { 23, 45, 51, 77, 99, 101, 107, 111 }; int countLessThanHundred = 0; for (int i = 0; i < 8; i++) { if (sortedNumbers[i] > 100) break; countLessThanHundred++; } printf("countLessThanHundred:%d",countLessThanHundred);//countLessThanHundred:5 }
What is the use of a continue in a loop?
continue causes the next iteration of the enclosing for, while, or do loop to begin. So, execution shifts to the condition check of the loop. Look at the example below. The array here is unsorted. We want to find how many numbers are less than 100.
#include <stdio.h> #include <stdlib.h> int main() { int unSortedNumbers[] = { 45, 15, 91, 101, 99, 90, 107, 11 }; int countLessThanHundred = 0; for (int i = 0; i < 8; i++) { if (unSortedNumbers[i] > 100) continue; countLessThanHundred++; } printf("countLessThanHundred:%d",countLessThanHundred);//countLessThanHundred:6 }