Please note, this is a STATIC archive of website technosmarter.com from July 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

C# for loop


In this lesson, we are going to learn C# for a loop. In the C programming or PHP for loop , we are discussed for loop with example. Here, we will create example of for loop in C#.

C# for loop -


A for loop is a control structure to execute the block of code till the specified number. In simple word, we use C# for loop to execute the same code repetitively. We specify the limit of number for a loop. A compiler executes the code until the specified number ended.

 

Let's understand the C# for loop with syntax.


for (initialization; condition; increment)
{
code to be executed;
}

syntax - 

Initialization

- Where the value begins. (ex. a=1)

Condition
- Specify condition here. (ex. a<19)

Increment
- Value of a variable will be increment until the condition is true.

Let's create an example in C# programming.

C# for loop example -
In this example, we are going to print a table from 0 to 15. This the simplest way to execute the same code on condition.

 


using System;

namespace forLoop{

   public class Program {
   
      public static void Main(string[] args) {
      
		 for (int a = 0; a < 16; a = a+1)
		  {
			  Console.WriteLine(a);
		  }
		 
         Console.ReadLine();
      }
   
   }
}

Output

 
4
8
12
16
20
24
28
32
36
40

In the above C# example, we specified the initial value of variable 0. We created a condition a<16(a less than 16 ) it means, the variable value should below 16 and we incremented variable value. In every loop, the value of variable increments by 1. 

The compiler executes the code when the condition evaluates to true if the condition evaluates to false, the compiler gets exit from the loop.

In the above C# for loop example, we printed a table from 0 to 15 number. In this way, we can execute code much time within specified numbers.

Let's create another example of for loop using C# programming.
In this example, we will execute the code many times but until the specified number.


using System;

namespace forLoop{

   public class Program {
   
      public static void Main(string[] args) {
          int b=4; 
		  int mul;
		 for (int a = 1; a <=10; a = a+1)
		  {
			 mul=b*a; 
			  Console.WriteLine(mul);
		  }
		 
         Console.ReadLine();
      }
   
   }
}

Output-

4
8
12
16
20
24
28
32
36
40
 

In the above C# example, we printed a table of four. We made logic and increased the value of the variable in every loop. In this way, you can execute the code specified time using C# loop.

 


Please Share

Recommended Posts:-