Developer community
0 votes
123 views
asked by Guru (24.6k points) 29 51 79 | 123 views

1 Answer

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:

12345

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.
answered by Guru (39.1k points) 10 22 34

Related questions

0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 79 | 41 views
0 votes
1 answer
asked by sara Guru (24.6k points) 29 51 79 | 1.2k views
0 votes
1 answer
0 votes
0 answers
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users