For Loop in C#

For Loop in C# with Examples

In this article, I am going to discuss For loop in C# Language with Examples. Please read our previous articles, where we discussed Do While Loop in C# with Examples. At the end of this article, you will understand what for loop is and when and how to use for loop in C# Language with Examples.

For Loop in C#:

For loop is the type of loop that is also used for repetition and it is the most commonly used loop. If we know the number of times, we want to execute some set of statements or instructions, then we should use for loop. For loop is known as Counter Controlled loop. Whenever counting is involved for repetition, then we need to use for loop.

Let’s take an example and try to understand what it means by counting. Suppose you are preparing coffee. You don’t know how to prepare coffee; somebody has given you instructions and you’re following them. You are making coffee for 4 people.

Now the question is how much sugar you should add? You should add the sugar and mix it, again add the sugar and mix, and so on until coffee becomes sweet enough. So, how many times you should add sugar to coffee? It has no fixed answer because you will add sugar to coffee until it becomes sweet enough. So, this is not based on counting.

Now somebody gives you instructions that add 4 tablespoons of sugar to the coffee. So, this is based on counting. There are many examples in daily life. We do things a fixed number of times. So, when you have to repeat the steps based on counting, then use for loop.

For Loop Flowchart

For Loop Flowchart

Let us take the example of printing numbers up to some given number using for loop. Let us first understand the flow chart for this example.

For loop in C# Language with Examples

First, we will take the input as far as we want to print the number. So, we want to print numbers to a certain point. For that, we need a counter, so here we have ‘i’ as a counter. And we have initialized ‘i’ to 1. So ‘i’ starts from one onwards.

Then condition will check ‘if (i <= n)’ (n is the input). If the condition is true then print the value of ‘i’ and modify ‘i’ as ‘i = i + 1’. Again, the condition will be checked, if it is true then repeat the same steps which we discussed above, or if it is false the loop will be stopped, and control will come out of the loop.

Syntax to use For Loop in C# Language:

The for loop is a repetitive, structure that allows the execution of instructions for a specific amount of time. It has four stages.

  1. Loop initialization
  2. Condition evaluation
  3. Execution of instruction
  4. Increment/Decrement

Now let’s have a look at the for loop syntax:

Syntax to use For Loop in C# Language

Explanation:
  1. Loop Initialization: Loop initialization happens only once while executing the for loop for the first time, which means that the initialization part of for loop only executes once.
  2. Condition Evaluation: Conditions in for loop are executed for each iteration and if the condition is true, it executes the C# instruction if false it comes out of the loop.
  3. Execution of Instruction: After the condition is executed, control comes to the loop body i.e. C# instructions and it gets executed.
  4. Increment/Decrement: After executing the C# instructions for the loop increment/decrement part of for loop executed, and again it will go to the condition evaluation stage.

So why there are 3 parts? Because in for loop, first, we have to initialize the counter then condition, and then the increment/decrement of the counter so that the loop executes statements again and again. In for loop, Initialization, condition, and addition / updation are together in one place. Now let us see this in the code part.

Example to Print Numbers From 1 to n Using For Loop in C#:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter one Integer Number:");
            int number = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= number; i++)
            {
                Console.WriteLine(i);
            }
            Console.ReadKey();
        }
    }
}
Output:

Example to Print Numbers From 1 to n Using For Loop in C#

Note: In for loop, we can skip initialization, we can initialize a variable before for loop. So, Initialization is optional in for loop.

Infinite Loop in C#:

We can place the increment/decrement statement in the body part. If we don’t give any increment/decrement statement in for loop or in the body then what happens? It will be an infinite loop. Infinite is a non-ending loop. Let’s understand this with the below example.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            int i = 1;
            for (; i <= number; )
            {
                Console.WriteLine("Hello C#");
            }
            Console.ReadKey();
        }
    }
}
Output:

Infinite Loop in C#

You can see that it will go on printing “Hello C#” because here counter is not updated and the termination condition will never reach so it will continue printing “Hello C#” until you exit the program.

Can we run for loop without condition in C#?

Let us see this with an example:

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 1;
            for (;; )
            {
                Console.WriteLine("Hello C#");
                i++;
            }
        }
    }
}
Output:

Can we run for loop without condition in C#?

Again, it will be an infinite loop. Because this time we have written increment/decrement statement but haven’t mentioned any termination condition in for loop. So here ‘i’ value keeps increasing and printing “Hello C#”.

We can write a custom if statement inside for loop as:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 1;
            for (;; )
            {
                Console.WriteLine("Hello C#");
                i++;
                if (i > 5)
                    break;
            }
            Console.ReadKey();
        }
    }
}
Output:

blank

Nested for Loop in C#:

In C# Nested for loop, one or more for loops can be included in the body of the loop. In the nested for loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the number of iterations in the inner loop. The syntax to use nested for loop is given below.

Nested for Loop in C#

Example to Understand Nested For Loop in C#:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i; //for outer loop counter
            int j; //for inner loop counter
            for (i = 1; i <= 5; i++)
            {
                for (j = 1; j <= 10; j++)
                {
                    Console.Write($"{j} ");
                    
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}
Output:

blank

Points Remember while working with for loop in C#

When we are working with for loop always execution process will start from the initialization block. After the initialization block, the control will pass to the condition block. If the condition is evaluated as true then control will pass to the statement block.

After execution of the statement block, the control will pass to the iteration block, from iteration it will pass back to the condition. Always repetition will happen beginning condition, statement block, and iteration only. The initialization block will be executed only once when we are entering the loop the first time.

When we are working with for loop everything is optional but mandatory to place 2 semicolons (;;). While we are working with for loop if the condition part is not given then it will repeat infinite times because the condition part will replace it as non-zero. So it is always true as like for(; 1; )

Whenever we are working with for loop it repeats in an anticlockwise direction. In for loop also the pre-checking process will occur i.e. before the execution of the statement block (body of the for loop), the condition part will be executed

For Loop Programs using C# Language:

Let us see some more examples using for loop in C# language.

Program to enter a number and check whether that no is the perfect number or not using for loop in C#

If the sum of all factors is equal to that number, then it is called a perfect number.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number, i, sum = 0;
            Console.Write("Enter a Number :");
            number = Convert.ToInt32(Console.ReadLine());

            for (i = 1; i <= number / 2; i++)
            {
                if (number % i == 0)
                    sum += i;
            }
            if (sum == number && number != 0)
                Console.WriteLine($"{number} is a Perfect Number");
            else
                Console.WriteLine($"{number} is not a Perfect Number");

            Console.ReadKey();
        }
    }
}
Output:

Program to enter a number and check whether that no is the perfect number or not using for loop in C#

Program to check whether a number is Armstrong no or not using for loop C# Language

If the sum of all individual cube values is equal to that number, then it is called the Armstrong number.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number, rem, temp, sum = 0;
            Console.Write("Enter a Number :");
            number = Convert.ToInt32(Console.ReadLine());

            for (temp = number; temp != 0;)
            {
                rem = temp % 10;
                sum += (rem * rem * rem);
                temp /= 10;
            }
            if (sum == number && number != 0)
                Console.WriteLine($"{number} is an Armstrong number");
            else
                Console.WriteLine($"{number} is not an Armstrong number");

            Console.ReadKey();
        }
    }
}
Output:

Program to check whether a number is Armstrong no or not using for loop C# Language

Program to enter a number and check whether it is a prime number or not using for loop in C# Language

The number which is divisible by 1 and itself is called a prime number.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number, i;
            Console.Write("Enter a Number :");
            number = Convert.ToInt32(Console.ReadLine());

            for (i = 2; i < number; i++)
            {
                if (number % i == 0)
                    break;
            }
            if (i == number && number >= 2)
                Console.WriteLine($"{number} is a Prime Number");
            else
                Console.WriteLine($"{number} is not a Prime Number");

            Console.ReadKey();
        }
    }
}
Output:

blank

Program to print the Fibonacci series up to a given number using for loop in C# Language
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number, number1 = 0, number2 = 1, temp;
            Console.Write("Enter a Number :");
            number = Convert.ToInt32(Console.ReadLine());

            if (number >= 1)
            {
                Console.Write($"{number1} {number2}");
                temp = number1 + number2;

                for (; temp <= number;)
                {
                    Console.Write($" {temp}");
                    number1 = number2;
                    number2 = temp;
                    temp = number1 + number2;
                }
            }
            else
                Console.WriteLine("please enter a number greater than zero");

            Console.ReadKey();
        }
    }
}
Output:

Program to print the Fibonacci series up to a given number using for loop in C# Language

Note: Foreach Loop in C# works with collections. So, we will learn foreach loop once we learn array and collections in C#.

In the next article, I am going to discuss Jump Statements in C# with Examples. Here, in this article, I try to explain For Loop in C# with examples. I hope you enjoy this For Loop in C# Language with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.