Wednesday, September 13, 2017

Lesson 07: Looping Constructs in C#

Looping Constructs in C#

Sometimes programmers are required to execute a piece of code a number of times until a certain condition is met; and for such kind of operations C# provides looping statements also known as iteration statements at developers’ disposal.

In C#, we have four ways to accomplish looping construct: for loop, while loop, do while loop and for each loop. The first three are discussed in this tutorial while the remaining will be explained in the coming lessons.

The For Loop

The for loop comprises three parts - initializer, condition and iterator; and its general form is given as follows:

for(initializer; condition; iterator) 

Below picture depicts the flow chart of a for loop construct.



The following steps briefly explains how the for loop gets its job done.

Step 1: First the initializer statement is executed; it is executed only once per life time of the for loop construct.

Step 2: Next, the conditions is tested and it is evaluated to a boolean value – true or false value.

Step 3: Based on the result of the above condition, if the output of the condition is true, the body of the for loop is executed; otherwise, the entire for loop is skipped.

Step 4: After each execution of the body of the for loop, the control executes the iterator statement to increment the value of the counter; the condition is tested based on the new value of the counter and if the result of the condition is true the body of the for loop is executed; otherwise, the controls jumps to the next statement after the for loop. In this manner, the body of the for loop gets executed as long as the condition is evaluated to true.


Vital Notes:
(i)          The curly braces of the body of the for loop are optional if the body contains only one statement; however, for the sake of readability it is always a good programming practice to use the curly braces – even if the body of the for loop contains a single statement to be executed.

(ii)          The for loop always executes 0 or more times, for the condition part of the loop is tested before the statement(s) within the body of the loop get(s) executed.

The following for loop statement prints the number i 10 times to the output console.
      
for (int i = 0; i < 10; i++) {
                Console.Write(i + "\t");
   }

Output: 0   1       2       3       4       5       6       7       8       9

The following program calculates the average mark of a student using for loop statement.

/*
 * Author: Temesghen Tekeste
 * The for loop construct in C#.
 * mail: mail.temesghen.tekeste@gmail.com
 * */
using System;

namespace ForLoopDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("WELCOME TO STUDENT AVERAGE MARK CALCULATOR:\n");
            //Declaring variables and intializing variablles
            double studentMark = 0.0;
            double studentAverageMark = 0.0;
            int numberOfSubjects = 0;

            Console.Write("Enter the number of subjects:");
            //Temporary Variable used to hold string value of the number of subjects
            String tempNumberOfSubjects = Console.ReadLine();
            //Parsing the stirng value to the appropriate integer type
            numberOfSubjects = Int32.Parse(tempNumberOfSubjects);

            for (int i = 1; i <= numberOfSubjects; i++) {
                Console.Write("Enter student mark " + i + ":");
                string tempstudentMark = Console.ReadLine();
                studentMark += Double.Parse(tempstudentMark);
             }

            studentAverageMark = studentMark / numberOfSubjects;
            Console.WriteLine();
            Console.WriteLine("Total Student Mark: {0} ",studentMark);
            Console.WriteLine("Average Student Mark: {0} ",studentAverageMark);


            Console.Read();
        }
    }
}
Sample Output:




Download Source code


The While Loop

Just like the for loop, the while statement executes 0 or more statements, for the condition of the loop is checked before the body of the loop gets executed.

Generally, the while statement begins by initializing a counter or loop guard; then, the condition is tested and its output is either true or false – boolean value. If the condition is evaluated to true, the body of the while is executed and then the control jumps to reevaluate the condition. If the condition is evaluated to false, the entire loop is skipped.

The general form of a while loop is as follows:

ininializer
while ( condition )
    statement

The flow chart of the while loop is the same as that of a for loop.

Vital Notes
(i)          The loop guard or the counter is changed inside the body of the while loop; throughout the life time of the while loop, the condition is evaluated to false and this enables the control to execute the next statement following the while loop.

(ii)          It is always wise to remember the value of the loop guard should be evaluated to a value in a way that makes the condition to evaluate to false so that the control skips the entire while loop and jumps to the next statement after the while loop, or else an infinite loop would be created.

(iii)          You can use sentinel value – value that signals end of data entry. Here the user enters some value that informs the program to go out of the while loop.

The following example prints the numbers 0 to 9 to the output console using the while loop construct.

           int i = 0;
           while (i < 10) {
                Console.Write(i + "\t");
                i++;
                       }

Output: 0       1       2       3       4       5       6       7       8       9

The following program calculates the average mark of a student using while loop statement that is guarded using a sentinel value.

/*
 * Author: Temesghen Tekeste
 * The while loop construct in C#.
 * mail: mail.temesghen.tekeste@gmail.com
 * */
using System;

namespace WhileLoopDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("WELCOME TO STUDENT AVERAGE MARK CALCULATOR:\n");
            //Declaring variables and intializing variablles
            double studentMark = 0.0;
            double totalStudentMark = 0.0;
            double studentAverageMark = 0.0;
            int numberOfSubjects = 0;

            Console.Write("Enter student mark "", or negative number to quit: ");
            string tempstudentMark = Console.ReadLine();
            studentMark = Double.Parse(tempstudentMark);

            //Any negative number is used as a sentinel value in order to quit out of the while loop
            while (studentMark > 0.0)
            {
                totalStudentMark += studentMark;
                numberOfSubjects++;
                Console.Write("Enter student mark " + ", or negative number to quit: ");
                tempstudentMark = Console.ReadLine();
                studentMark = Double.Parse(tempstudentMark);
               
            }

            studentAverageMark = totalStudentMark / numberOfSubjects;
            Console.WriteLine();
            Console.WriteLine("Total Student Mark: {0} ", totalStudentMark);
            Console.WriteLine("Number of subjects: {0}", numberOfSubjects);
            Console.WriteLine("Average Student Mark: {0} ", studentAverageMark);

            Console.Read();
        }
    }
}

Sample Output:
Download Source code

The Do While Loop

Unlike the while loop, the body of the do while loop is executed at least once, for the condition of the loop is tested after the body the loop gets executed.


The general form of the do while loop is:

do
{
         body
}(condition);

Here is the flow chart of the do while loop:
The following example prints the numbers 1 to 10 to the output console using the do while loop construct.
            int i = 0;
            do
            {
                Console.Write(++i + "\t");
         } while (i < 10);

Output: 1       2       3      4      5       6      7     8     9     10

Question: Please convert the sentinel controlled while loop into a do while loop.

References:
Loops: msdn
C# Loops: tutorialpoint
For Loop:infocodify.
http://www.infocodify.com/csharp/csharp_while_loops

No comments:

Post a Comment