Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

Loops in C#

In this article, we will learn about for loop in C# and different ways to use them in a program.

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 maybe large enough (say 10000).

The best solution to such problem is loop. Loops are used in programming to repeatedly execute a certain block of statements until some condition is met.

In this article, we’ll look at for loop in C#.


C# for loop

The for keyword is used to create for loop in C#. The syntax for for loop is:

for (initialization; condition; iterator) {
	// body of for loop
}

How for loop works?

  1. C# for loop has three statements: initialization, condition and iterator.
  2. The initialization statement is executed at first and only once. Here, the variable is usually declared and initialized.
  3. Then, the condition is evaluated. The condition is a boolean expression, i.e. it returns either true or false.
  4. If the condition is evaluated to true:
    1. The statements inside the for loop are executed.
    2. Then, the iterator statement is executed which usually changes the value of the initialized variable.
    3. Again the condition is evaluated.
    4. The process continues until the condition is evaluated to false.
  5. If the condition is evaluated to false, the for loop terminates.

Example 1: C# for Loop


using System;
namespace Loop {
	class ForLoop {
		public static void Main(string[] args) {
			for (int i = 1; i <= 5; i++) {
				Console.WriteLine("C# For Loop: Iteration {0}", i);
			}
		}
	}	
}

When we run the program, the output will be:

C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

In this program,

  • initialization statement is int i = 1
  • condition statement is i <= 5
  • iterator statement is i++

When the program runs,

  • First, the variable i is declared and initialized to 1.
  • Then, the condition (i <= 5) is evaluated.
  • Since, the condition returns true, the program then executes the body of the for loop. It prints the given line with Iteration 1 (Iteration simply means repetition).
  • Now, the iterator (i++) is evaluated. This increments the value of i to 2.
  • The condition (i <= 5) is evaluated again and at the end, the value of i is incremented by 1. The condition will evaluate to true for the first 5 times.
  • When the value of i will be 6 and the condition will be false, hence the loop will terminate.

Example 2: for loop to compute sum of first n natural numbers


using System;
namespace Loop {
	class ForLoop {
		public static void Main(string[] args) {
			int n = 5,sum = 0;
			for (int i = 1; i <= n; i++) {
				// sum = sum + i;
				sum += i;
			}
			Console.WriteLine("Sum of first {0} natural numbers = {1}", n, sum);
		}
	}
}

When we run the program, the output will be:

Sum of first 5 natural numbers = 15

Here, the value of sum and n are initialized to 0 and 5 respectively. The iteration variable i is initialized to 1 and incremented on each iteration.

Inside the for loop, value of sum is incremented by i i.e. sum = sum + i. The for loop continues until i is less than or equal to n (user’s input).

Multiple expressions inside a for loop

We can also use multiple expressions inside a for loop. It means we can have more than one initialization and/or iterator statements within a for loop. Let’s see the example below.

Example 3: for loop with multiple initialization and iterator expressions


using System;
namespace Loop {
	class ForLoop {
		public static void Main(string[] args) {
			for (int i = 0, j = 0; i + j <= 5; i++, j++) {
				Console.WriteLine("i = {0} and j = {1}", i,j);
			}         
		}
	}
}

When we run the program, the output will be:

i = 0 and j = 0
i = 1 and j = 1
i = 2 and j = 2

In this program, we have declared and initialized two variables: i and j in the initialization statement.

Also, we have two expressions in the iterator part. That means both i and j are incremented by 1 on each iteration.


For loop without initialization and iterator statements

The initialization, condition and the iterator statement are optional in a for loop. It means we can run a for loop without these statements as well.

Example 4: for loop without initialization and iterator statement

using System;
namespace Loop {
	class ForLoop {
		public static void Main(string[] args) {
			int i = 1;
			for ( ; i <= 5; ) {
				Console.WriteLine("C# For Loop: Iteration {0}", i);
				i++;
			}
		}
	}
}

When we run the program, the output will be:

C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

In this example, we haven’t used the initialization and iterator statement.
This loop now works like a while loop which we will discuss about later.

The variable i is initialized above the for loop and its value is incremented inside the body of loop. This program is same as the one in Example 1.

Similarly, the condition is also an optional statement. However if we don’t use test expression, the for loop won’t test any condition and will run forever (infinite loop).


C# while loop

The while keyword is used to create while loop in C#. The syntax for while loop is:

while (test-expression) {
	// body of while
}

How while loop works?

  1. C# while loop consists of a test-expression.
  2. If the test-expression is evaluated to true,
    1. statements inside the while loop are executed.
    2. after execution, the test-expression is evaluated again.
  3. If the test-expression is evaluated to false, the while loop terminates.

Example 5: while loop

using System;
namespace Loop {
    class WhileLoop {
        public static void Main(string[] args) {
            int i = 1;
            while (i <= 5) {
                Console.WriteLine("C# For Loop: Iteration {0}", i);
                i++;
            }
        }
    }
}

When we run the program, the output will be:

C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

Initially the value of i is 1.

When the program reaches the while loop statement,

  • the test expression i <=5 is evaluated. Since i is 1 and 1 <= 5 is true, it executes the body of the while loop. Here, the line is printed on the screen with Iteration 1, and the value of i is increased by 1 to become 2.
  • Now, the test expression (i <=5) is evaluated again. This time too, the expression returns true (2 <= 5), so the line is printed on the screen and the value of i is now incremented to 3..
  • This goes and the while loop executes until i becomes 6. At this point, the test-expression will evaluate to false and hence the loop terminates.

Example 6: while loop to compute sum of first 5 natural numbers

using System;
namespace Loop {
    class WhileLoop {
        public static void Main(string[] args) {
            int i = 1, sum = 0;

            while (i <= 5) {
                sum += i;
                i++;
            }
            Console.WriteLine("Sum = {0}", sum);
        }
    }
}

When we run the program, the output will be:

Sum = 15

This program computes the sum of first 5 natural numbers.

  • Initially the value of sum is initialized to 0.
  • On each iteration, the value of sum is updated to sum+i and the value of i is incremented by 1.
  • When the value of i reaches 6, the test expression i<=5 will return false and the loop terminates.

C# 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. It is the exact opposite in do…while loop, i.e. condition is checked after the body is executed.

This is why, the body of do…while loop will execute at least once irrespective to the test-expression.

The syntax for do…while loop is:

do {
	// body of do while loop
} while (test-expression);

How do…while loop works?

  1. The body of do...while loop is executed at first.
  2. Then the test-expression is evaluated.
  3. If the test-expression is true, the body of loop is executed.
  4. When the test-expression is false, do...while loop terminates.

Example 7: do…while loop

using System;
namespace Loop {
    class DoWhileLoop {
        public static void Main(string[] args) {
            int i = 1, n = 5, product;

            do {
                product = n * i;
                Console.WriteLine("{0} * {1} = {2}", n, i, product);
                i++;
            } while (i <= 10);
        }
    }
}

When we run the program, the output will be:

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

As we can see, the above program prints the multiplication table of a number (5).

  • Initially, the value of i is 1. The program, then enters the body of do..while loop without checking any condition (as opposed to while loop).
  • Inside the body, product is calculated and printed on the screen. The value of i is then incremented to 2.
  • After the execution of the loop’s body, the test expression i <= 10 is evaluated. In total, the do...while loop will run for 10 times.
  • Finally, when the value of i is 11, the test-expression evaluates to false and hence terminates the loop.

Task

In the editor below, perform the different tasks as directed.

Start solving Loops in C# on Interview Code Editor
Hints
  • Hint 1
  • Solution Approach
  • Complete Solution

Discussion


Loading...
Click here to start solving coding interview questions
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test