Control statements - For/foreach - DotNet and DataBase

Friday, 6 July 2018

Control statements - For/foreach





For/foreach are the looping statements which execute the function based on the number of times defined.

Syntax
---------
for(datatype variable; condition; increment/ decrement operator)
{
statements;
}


Example
-----------
Let us suppose we want to execute one statement more than one times for loop more suitable.
For example, we want to print numbers 10 numbers we have to write the  for loop as below

            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("i Value is :"+i);           
            }
                Console.Read();


the above code prints the 10 numbers from 1 to 10.


Foreach
----------

Foreach statement is also used to execute the same code number of times defined, but the difference is forach works on a collection.
Let us suppose we have an array which has "n" number of elements.
To print those elements we don't need to use increment/ decrement operator and condition also not required.

CLR takes these all responsibilities.

Syntax
---------

           foreach (var item in collection)
            {
                 statements;
            }

Example
-----------

            int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            foreach (var item in a)
            {
                Console.WriteLine(item);
            }
            Console.Read();

Practice</>

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.