Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

For Loops in Fundamentals

User image

Published by

sanya sanya

Published at: 27th Jul, 2023
1.975 mins read

What is a "for" loop?

A "for" loop is a control flow statement in programming that allows you to repeatedly execute a block of code based on a specific condition. It provides a compact way to initialize variables, define the loop condition, and update the variables with each iteration.

Syntax and Code:

The syntax of a "for" loop in C++ is as follows:

for (initialization; condition; update) {

// code to be executed

}

- The initialization step is executed only once at the beginning and is typically used to initialize a loop counter.

- The condition is evaluated before each iteration. If it evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.

- The update step is performed at the end of each iteration and is usually used to update the loop counter.

Example of a "for" loop that prints the numbers from 1 to 5:

#include

using namespace std;

int main() {

for (int i = 1; i <= 5; i++) {

cout << i << " ";

}

return 0;

}

Output:

1 2 3 4 5

Conversion into while:

You can convert a "for" loop into a "while" loop by preserving the initialization, condition, and update steps of the "for" loop.

- Initialization: Place the initialization statement before the loop.

- Condition: Use the condition as the while loop condition.

- Update: Place the update statement at the end of the loop body.

Example:

#include

using namespace std;

int main() {

int i = 1; // Initialization

while (i <= 5) { // Condition

cout << i << " ";

i++; // Update

}

return 0;

}

When to use a "for" loop?

A "for" loop is typically used when you know the number of iterations in advance or when you want to iterate over a range of values. It is especially useful when you need to iterate a specific number of times or when you want to control the loop with a counter.

A "for" loop is used in various scenarios, such as:

- Iterating over an array or a collection of elements.

- Performing a task, a fixed number of times.

- Implementing numerical algorithms or mathematical computations.

- Processing input or output in a structured manner.

Library

WEB DEVELOPMENT

FAANG QUESTIONS