Как работает for c
Перейти к содержимому

Как работает for c

  • автор:

The for Loop


C# for loop is very common in programming. This loop is ideal for performing a fixed number of iterations when the programmer needs to iterate over a block of code a specific number of times. C# for loop uses in-built syntax for initializing, incrementing, and testing the value of a counter variable that determines how many times the loop will execute.

In this tutorial, you’ll:

  • Learn about the for loop, It’s syntax and execution order used for definite iteration (number of repetitions specified in advance)
  • You will cover different variations of for loop.
  • Jumping out of a loop or loop iteration prematurely
  • See how to stop the current iteration and start the next iteration without breaking out of the loop.
  • Then you will explore infinite and nested loops
  • Finally, you will learn the use of for loop with array and list.

When you’re finished, you should have a good understanding of how to use definite iteration in C#.

Once you’ve read this article, I’d recommend you to check out my free C# Quick Start Guide Here, where I explained most of the topics in detail with YOUTUBE videos. Read this article Here.

Edit, and test all the CODE examples used in this article with C# online editor: Code Playground


The structure of a C# for loop is as follows:

You begin C# for loop syntax with the “ for “ keyword followed by a set of parentheses. Within the parentheses are three different parts separated by two semicolons. These parts control the looping mechanism. Let’s examine each.

  1. Initializer: The first part declares and initializes the counter variable. It happens only once before the loop begins.
  2. Condition: The second part is the Boolean expression that determines when the loop stops. If the expression returns true, the code within the loop’s body executes. Otherwise, the loop stops.
  3. Iterator: The third part is something that uses a C# unary operator. This piece of code increments/decrements the counter variable initialized in the first part of the C# for statement and is executed at the end of each iteration.

Note: C# unary operator provides increment (++) and decrement ( ) operator.

Execution Order

The first part is the initialization expression, which normally allows you to set up an iterator (also known as “loop variable”) to its starting value. Initialization is the first action performed by the loop only once, no matter how many times the loop statements are executed. After that is the termination expression, this is some boolean condition to inform the loop when to stop. As long as this expression is true, the body of the loop will repeat. The loop’s body is surrounded by the braces immediately following the for statement. Finally, at the end is the update expression that increments/decrements an iterator variable. This statement takes effect at the bottom of the loop, just before the condition is checked.


The semantic of C# for loop is slightly more complicated than while and do-while loops: Initialization occurs only once before the loop begins, and then the condition is tested, which evaluates to true or false. If the condition is true, the code inside the loop’s body executes. In the end, increments/decrements the iterator each time through the loop after the body statement executes.

The condition is rechecked. If the condition is still true, the whole process starts over again. This logic repeats until the condition becomes false. In that case, C# exits the for loop and the next first statement after the loop continues.

Example: C# for Loop

Here is an example of a simple for loop that displays numbers 1 through 5 in the console window:

Curly braces are optional if the body of the loop contains only one statement.

A semicolon ( ; ) separates the three parts. The initialization part is int i = 1 ; the test part is i<=5 , and the increment part is i++ , which uses an increment operator ( ++ ). That means the value of i will go from 1 to 5. Within the body of the loop is a single statement, which is the call to Console.WriteLine method to print out the value of i variable in the console window.

This is what happens when above for loop executes:

  • The initialization expression int i = 1 is executed, which declares the integer variable i and initializes it to 1.
  • The expression i <= 5 is tested to return true or false. If the expression is true, continue with Step 3. Otherwise, the loop is finished.
  • The statement Console.WriteLine(i); is executed.
  • The update expression i++ is executed, which increases the counter variable value i by 1.
  • Back to Step 2.
  • Steps 2–4 are repeated as long as the condition is true.

If you run the above example, the output looks like this:

You can alternatively decrement the counter variable. Look at the following code:

I have initialized i variable with the value 5. The loop iterates as long as i is greater than or equal to 1. At the end of each iteration, i is decremented by 1. It will display numbers going down from 5 to 1.

Variations of for Loop

C# for loop has several variations; some may seem awkward ��. I want to show you alternatives; otherwise, rearranging the parts of a for statement like this is discouraged.

C# for loop with two variables: You can split first and third parts into several statements using the * comma operator *( , ). Here is an example in which I have used multiple initialization statements and multiple iterator statements all at the same time. There are two counters, counter i++ moves up from 1 and the counter j— moves down from 100:

You can perform multiple tests using compound conditions.

Another option is to leave out one or more parts from the for statement. Let’s leave out the initialization part if an int value has been declared before the loop.

You can move around the third part of the for statement, which is i++ . Let's move the last part in the loop's body.

Note: The third part of the for loop runs after testing the first two parts.

Two semicolons are mandatory and must be used as placeholders to separate the three parts.

The break Keyword With for Loop

What if you want to jump out of a loop in the middle, before a for loop condition becomes false?

The break keyword does that. C# break operator causes the for loop to stop immediately before it completes the current iteration and passes control to the first statement immediately after the loop. With a break statement, you’re stopping only the block of code the break is in.

When the counter reaches 4, the condition ( i==4 ) tests to true. The break keyword doesn't just skip the rest of the iteration 4; it stops altogether and resumes execution immediately following the loop. Loop skipped the values 4 and 5.

The continue Keyword With for Loop

What if you want to stop executing the current iteration of the loop and skip ahead to the next iteration?

You can do this with the continue keyword. C# continue operator stops the current iteration, without breaking out of the loop entirely, it just jumps ahead to the next iteration of the loop. The continue statement passes control straight to the for statement to start over. Let’s look at this more closely with an example.

In the above code example, the loop prints out all the numbers except one. It skips 4 due to the continue statement. When the loop hits condition ( i==4 ), it immediately skips Console.WriteLine(i) and goes directly to the for statement to check the condition. If the condition is still true, the loop then continues with the next cycle through the loop.


Infinite for Loop

Whenever you don’t give a condition to the for loop, it automatically becomes an infinite for loop, meaning the loop block executes endlessly. Use the double semicolon ( ;; ) in for loop to make it run infinite times.

All three parts of the for statement are optional, except two semicolons for(;;) . If the missing part is a condition, C# assumes no condition as a 'true' condition, thus creating an infinite or endless loop. Let's look at the following infinite for loop example with the double semicolon.

Note: To stop an endless loop, press CTRL + C on the keyboard. I mean, you press and hold down the CTRL key, and while holding it down, press the C key.

You can use the following code to see how an infinite for loop can be stopped with a break statement. The counter increments while you are trapped in the endless loop. Once the counter is greater than or equal to 4, you break out of the for loop with the break keyword ��.

Nested for Loops

A loop placed within another loop’s body is a nested loop. The outer loop must completely contain the inner loop. In the following image, the outer for loop entirely contains the inner for loop within its body. With each iteration of the outer loop triggers the inner loop which executes multiple times until the condition becomes false.

In the following code example, there are two for loops, one within the other. The outer for loop will use int i=1 and the inner for loop will use int j=0 as their initialization statements. To control the loop iterations, I have declared and initialized integer variable numberOfTimes. If you set the numberOfTimes to 2, then each for loop will iterate 2 times.

In the following example, the break statement exits inner for loop and returns control to the outer for loop, rather than breaking out of all the loops entirely. To exit both loops simultaneously, you must use two separate break keywords, one for each loop:

Difference Between for Loop and while Loop

To write a while loop, you initialize an iterator variable, and as long as its condition is true, you continue to execute the body of the while loop. To avoid an infinite loop, the body of the while loop must update the iterator variable. This loop requires more external variables to control.

Unlike the while loop that relies on an external variable, the for loop contains all the loop elements in one convenient place.

Array with for Loop

You can use a for loop when you need to loop through an array until a specific condition is reached (for example, end of an array). Here’s an example that shows how you can iterate through the items of an array using C# for loop:

The first statement declares a string array called fruitsArray which contains a list of fruits. You use the Length property of the fruits array to determine how many items an array contains, which is needed for the loop iterations. To access the array items individually, you need to use the value of i as an indexer inside the square brackets like this fruitsArray[i] . The value of i will go from 0 to 3. Finally, as you loop over each item in the array, its value is printed to the console window.

List With for Loop

You can use a for loop when you need to loop through a list until it reaches a termination condition (for example, end of a list). Following example shows how you can iterate all the items of a list using C# for loop:

The first statement declares a list named fruitsList that contains 4 fruits. You need Count property to find out the total number of fruits in the list, which is needed for the loop iterations. To access the list items individually, you need to use the value of i as an indexer inside the square brackets like this fruitsList[i] . The value of i will go from 0 to 3. As you loop over each item in the list, its value is printed to the console window.

for loop

Executes init-statement once, then executes statement and iteration-expression repeatedly, until the value of condition becomes false. The test takes place before each iteration.


[edit] Syntax

  • an expression statement (which may be a null statement » ; «).
  • a simple declaration, typically a declaration of a loop counter variable with initializer, but it may declare arbitrary many variables or structured bindings (since C++17) .
  • an alias declaration.
  • an expression which is contextually convertible to bool. This expression is evaluated before each iteration, and if its value converts to false , the loop is exited.
  • a declaration of a single variable with a brace-or-equals initializer. The initializer is evaluated before each iteration, and if the value of the declared variable converts to false , the loop is exited.

[edit] Explanation

The above syntax produces code equivalent to:

while ( condition ) <
iteration-expression ;

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.

As is the case with while loop, if statement is a single statement (not a compound statement), the scope of variables declared in it is limited to the loop body as if it was a compound statement.

[edit] Keywords

[edit] Notes

As part of the C++ forward progress guarantee, the behavior is undefined if a loop that has no observable behavior (does not make calls to I/O functions, access volatile objects, or perform atomic or synchronization operations) does not terminate. Compilers are permitted to remove such loops. While in C names declared in the scope of init-statement and condition can be shadowed in the scope of statement , it is forbidden in C++:

Как работает for c

In C programming, loops are responsible for performing repetitive tasks using a short code block that executes until the condition holds true. In this article, we will learn one such loop for loop.

What is for loop in C Programming?

For Loop in C Language provides a functionality/feature to recall a set of conditions for a defined number of times, moreover, this methodology of calling checked conditions automatically is known as for loop.

for loop is in itself a form of an entry-controlled loop. It is mainly used to traverse arrays, vectors, and other data structures.

for loop in c

Syntax of for loop in C

Structure of for Loop in C

for loop follows a very structured approach where it begins with initializing a condition then checks the condition and in the end executes conditional statements followed by an updation of values.

Цикл for в C#

В программировании порой необходимо выполнить набор инструкций определенное количество раз. Возможное решение — скопировать код. Но есть проблема: количество этих наборов мы можем либо не знать, либо их может быть очень много (10000, к примеру).

Решение проблемы — циклы. В программировании циклы используются для многократного выполнения блока кода. Цикл работает до тех пор, пока заданное условие истинно.

Цикл for

Для инициализации цикла используется ключевое слово for.

Синтаксис цикла

Как работает цикл for

  1. В цикле for три переменные: счетчик , условие и итератор .
  2. Объявление счетчика происходит в самом начале и лишь раз. Обычно он инициализируется сразу после объявления.
  3. Затем проверяется условие. Условие — булево выражение. То есть, возвращает true или false .
  4. Если условие определяется как true :
    • Выполняются инструкции внутри цикла.
    • После этого инициализируется итератор — обычно изменяется значение этой переменной.
    • Условие проверяется снова.
    • Процесс повторяется до тех пор, пока условие не будет определено как false .
  5. Если условие определится как false , цикл завершается.

Блок-схема работы цикла

Пример 1. Итерации цикла for


В этой программе:

  • счетчик — int = 1 ,
  • условие — i <= 5 ,
  • итератор — i++ ,

После запуска программы происходит следующее:

  • Объявляется и инициализируется переменная i . Ей присваивается значение 1.
  • После этого проверяется условие i <= 5 .
  • Если проверка условия возвращает `true`, выполняется тело цикла. Оно печатает строку «Цикл for C#: итерация 1».
  • Затем определяется значение итератора ( i++ ). Значение i увеличивается до 2.
  • Условие ( i <= 5 ) проверяется снова и значение i увеличивается на 1. Первые 5 итераций условие цикла будет оцениваться как true .
  • Когда значение i станет равняться 6, условие оценится как false . Следовательно, цикл завершится.
Пример 2. Вычисляем сумму первых n натуральных чисел


Сумма первых 5 натуральных чисел = 15

В этой программе объявляются две переменные — sum и n . Их значения равны 0 и 5 соответственно. Значение счетчика i в самом начале равно 1.

Внутри цикла значение переменной sum увеличивается на i — sum = sum + i . Цикл продолжается до тех пор, пока значение счетчика i меньше или равно n .

Давайте посмотрим, что происходит на каждой итерации цикла.

Изначально i = 1, sum = 0 и n = 5.


Значение i

i <= 5

Значение sum

То есть, финальное значение sum будет равняться 15.

Несколько выражений внутри цикла for

Внутри цикла for может быть несколько выражений. Это значит, что мы можем инициализировать несколько счетчиков и итераторов. Давайте разберем следующий пример.

Пример 3. Цикл for с несколькими выражениями


В этой программе мы объявили и инициализировали 2 переменных-счетчика — i и j .

В части итератора у нас также два выражения. То есть, на каждой итерации цикла i и j увеличиваются на 1.

Цикл for без объявления счетчика и итератора

Объявление счетчика, условия и итератора в цикле for не обязательно. Запустить цикл for мы можем и без них.

В таких случаях цикл for работает так же, как и while. Давайте рассмотрим.

Пример 4. Цикл for без объявления счетчика и итератора


В этом примере мы не объявляли счетчик и итератор.

Переменная i объявлена до цикла for и ее значение увеличивается внутри тела цикла. Эта программа практически идентична той, о которой мы говорили в первом примере.

Условие цикла также является необязательным параметром. Но без условия цикл будет бесконечным.

Бесконечный цикл for

Если условие выполнения цикла всегда true , то он будет выполняться бесконечно. Это называется бесконечным циклом.

Пример 5. Бесконечный цикл for

В этом примере i было присвоено значение 1. Условие — i > 0 . На каждой итерации цикла значение `i` увеличивается на 1. Из-за этого условие цикла никогда не примет значение false . Именно поэтому цикл будет выполняться бесконечно.

Инициализировать бесконечный цикл можно и заменой условия пробелом. Например:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *