Loops
Loops
In programming, it is often desired to execute certain block of statements for a specified number of times. A possible solution will be to type those statements for the required number of times.
However, the number of repetition may not be known in advance (during compile time) or
Repetitions maybe large enough (say 10000).
The best solution to such problem is loop.
There are 3 types of loops available in C#: for, while and do while
The do while loop is the same as while loop except that it executes the code block at least once
For Loop
The Syntax for a for
loop is:
How for loop works?
C# for loop has three statements:
initialization
,condition
anditerator
.The initialization statement is executed at first and only once. Here, the variable is usually declared and initialized.
Then, the condition is evaluated. The condition is a boolean expression, i.e. it returns either
true
orfalse
.If the condition is evaluated to true: The statements inside the for loop are executed.
Then, the iterator statement is executed which usually changes the value of the initialized variable.
Again the condition is evaluated. The process continues until the condition is evaluated to
false
.If the condition is evaluated to false, the for loop terminates.
Example
The following code prints the output shown:
Exercise
Print the multiples of 4 between the numbers 30 and 50, both inclusive?
Hint: You can use modulus operator %
and ==
operator
Expected output
Exercise
Print the sum of first 10 natural numbers
Expected output:
While loop
Unlike for loops, while loops do not allow you to declare or assign the variable used in the conditions. The while keyword is used to create while loop in C#.
The syntax for while loop is:
Example
When we run the program, the output will be:
Do while loop
The do and while keyword is used to create a do-while loop. It is similar to a while loop, however there is a major difference between them:
In while loop, the condition is checked before the body is executed. So it will execute at least once
The syntax for do...while loop is:
Example
Output
Continue statement
In C#, we use the continue statement to skip a current iteration of a loop. When our program encounters the continue statement, the program control moves to the end of the loop. It is useful in certain conditions where we no longer want to process anything based on a current condition. It works on all 3 types of loops.
Example
Output
Break statement
In C#, we use the break statement to terminate the loop. As we know, loops iterate over a block of code until the test expression is false. However, sometimes we may need to terminate the loop immediately without checking the test expression. In such cases, the break statement is used.
Example
Output
Last updated