GATE Exam | Aptitude Questions | GATE Syllabus | GATE Result | Mock Test | GATE Preparation
0 votes
for loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of
an iterative loop, it is recommended to use 'for' loop.
Syntax:
for(initialization;condition;increment/decrement)
{
//block of statements
increment or decrement
}
Program: Program to illustrate for loop
#include<stdio.h>
int main() {
 int i;
 for (i = 1; i <= 5; i++) {
  //print the number
  printf("\n %d", i);
 }
 return 0;
}
Output:
1
2
3
4
5
Explanation:
The loop repeats for 5 times and prints value of 'i' each time. 'i' increases by 1 for every cycle of loop.
while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single
statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is
present.
Syntax:
#include<stdio.h>
int main() {
 int i = 0, flag = 0;
 int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 };
 //This loop is repeated until the condition is false.

 while (flag == 0) {
  if (a[i] == 54) {
   //as element is found, flag = 1,the loop terminates
   flag = 1;
  }
  else {
   i++;
  }
 }
 printf("Element found at %d th location", i);
 return 0;
}
Output:
Element found at 5th location
Explanation:
Here flag is initialized to zero. 'while' loop repeats until the value of flag is zero, increments i by 1. 'if' condition
checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop terminates.
asked in Programming by anonymous

Related questions

The best answer to any question