Friday, 18 February 2011

Chapter 8 Iteration Statements

Iteration is to repeat or loop a certain block of code. the number of time this iteration will take place depends on the condition specified by the programmer. every loop must have a proper ending else it becomes an infinite loop.
The following statements can be used to create loop or iterations
  1. do
  2. for
  3. foreach
  4. while

do statement

The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false.Unlike the while statement, a do-while loop is executed once before the conditional expression is evaluated.
At any point within the do-while block, you can break out of the loop using the break statement. You can step directly to the while expression evaluation statement by using the continue statement; if the expression evaluates to true, execution continues at the first statement in the loop. If the expression evaluates to false, execution continues at the first statement after the do-while loop.
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of do while statement, it will ask for your name 
 *                 and number of times you want to print it
 *                 
 *                
 */
namespace HelloWorld
{
    class dowhileexample
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your name : ");
            string myname = Console.ReadLine();
            Console.Write("How many times do you want your name to be printed : ");
            int num = int.Parse(Console.ReadLine());
            int i = 0;

            do
            {
                Console.WriteLine("Printing  {0} {1} of {2} times", myname, i, num);
                i = i + 1;
            } while (i < num);
            Console.ReadKey(false);
        }

    }
}

As you can see it is quite simple program, it starts with asking the user for his name and the number of times you want to print it. Then it initializes a variable i to zero. After this the loop starts by printing a message, then it increments the variable i, the last step is to check if the variable i is less than the variable num, if the condition is true then the loop is repeated else the loop finishes and the program exits.

for statement

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is handy for iterating over arrays and for sequential processing
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of for statement, it will print the table of the number 
 *                 you input
 *                 
 *                
 */
namespace HelloWorld
{
    class forexample
    {
        static void Main(string[] args)
        {
            Console.Write("The number for which you want the table : ");
            int num = int.Parse(Console.ReadLine());
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("{0} * {1} = {2}", num, i, num * i);
            } 
            
            Console.ReadKey(false);
        }

    }
}

Another simple example.The for statement executes the enclosed statement or statements repeatedly as follows:

  • First, the initial value of the variable i is evaluated.
  • Then, while the value of i is less than or equal to 10, the condition evaluates to true, the Console.WriteLine statement is executed and i is reevaluated.
  • When i is greater than 10, the condition becomes false and control is transferred outside the loop. Because the test of conditional expression takes place before the execution of the loop, therefore, a for statement executes zero or more times.All of the expressions of the for statement are optional

foreach statement

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of foreach statement, it will print the all the names
 *                 from the string array
 *                
 */
namespace HelloWorld
{
    class foreachexample
    {
        static void Main(string[] args)
        {
            string[] namearray = new string[] { "sudeep", "sanjeev", "ashish", "tia", "aanchal" };
            foreach (string name in namearray)
            {
                Console.WriteLine(name);
            }
            Console.ReadKey(false);
        }
    }
}

Sample Output

while statement

The while statement executes a statement or a block of statements until a specified expression evaluates to false.Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times. This differs from the do loop, which executes one or more times.
A while loop can be terminated when a break, goto, return, or throwstatement transfers control outside the loop. To pass control to the next iteration without exiting the loop, use the continuestatement.

No comments:

Post a Comment