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

Tuesday, April 18, 2017

Lesson 06: Blocks and Conditional Statements

Blocks and Conditional Statements

Blocks
A block is any number of C# statements that are surrounded by a pair of curly braces. Blocks define the scope of a variable and they can be nested inside other blocks. The following is a block that is nested inside the Main method.
public void Main (String[] args )
{
   int i, j, k;
   . . .
   {
      int b;
              
      . . .
   } // b is only defined up to here
}// i, j, and k are defined up to here

The if Statement
One of the notable features any software is its ability to make certain decisions throughout its lifecycle. For instance, a voting system has the ability to make a decision whether a person is eligible to vote or not based his or her age value; similarly, a student grade generating system has the potential to decide whether the student should be given an ‘A’, ‘B’, ‘C’, ‘D’ or ‘F’ based on the student’s mark.

Having this idea, in C#, to do such sort of decisions we have something called the if statement. The if statement allows a programmer to implement a decision based on a certain condition; thus, the if statement has two parts – a condition to test and a block of statement to be executed or not based on the truth value of the condition. If the condition is true the statements within the body of the block will be executed otherwise the control continues without executing the block statement. Here is a flowchart that represents a piece of code in a voting system that decides whether a person is eligible to vote or not based on his or her age. 


The above flowchart is represented in C# as follows:
            if (voterAge >= 18)
            {
                isEligible = true;
            }
In the above code snippet, if the condition is true, the block of code within the if clause is executed; otherwise, the block is skipped and execution continues to the line of code immediately after the if block.

We can branch an if statement using an else statement and the statement as a whole is called if – else statement. If the condition is true the true block is executed otherwise the else block or the false block is executed.

A more advanced version of the above voting scenario is illustrated as follows using if-else statement.

The above flowchart is represented in C# as follows:
            if (voterAge >= 18)
            {
                isEligible = true;
            }
            else
            {
                isEligible = false;
            }


The if statement has much more advanced version that has an if statement followed by an associated else-if statement. Here, if any one of the conditions evaluates to true, the code blocks associated with that statement is executed and then control leaves the code block related to the entire if construct. The following flowchart demonstrates such scenario.




The following program demonstrates full version of the above flowchart using the if --- else if statement in C#.

/*
 * Author: Temesghen Tekeste
 * The if --- else if statement in C#.
 * mail: mail.temesghen.tekeste@gmail.com
 * */
using System;

namespace DesionsAndConditions
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Grade Report Generating System");
            String output = "";
            Console.Write("Enter your mark:");

            //Converting/type casting the input to double
            double studentMark = Convert.ToDouble(Console.ReadLine());

            if (studentMark >= 90)
            {
                output += "Grade: A";
                output += "\nRemark: Outstanding";
            }
            else if(studentMark  >=80)
            {
                output += "Grade: B";
                output += "\nRemark: Very Good";
            }
            else if (studentMark >= 70)
            {
                output += "Grade: C";
                output += "\nRemark: Good";
            }

            else if (studentMark >= 60)
            {
                output += "Grade: B";
                output += "\nRemark: Poor";
            }
            else
            {
                output += "Grade: F";
                output += "\nRemark: Very Poor";
            }
            Console.WriteLine(output);
            Console.Write("Press any key to exit...");
            Console.ReadKey();

        }
    }
}


The switch Statement

In c#, the switch statement is used as an alternative to nested if else statement; in fact, it is best used when there are too many if else statements so that the code you write will not be cluttered.

A switch statement includes: switch section(s) and case label(s). The case labels are followed by one or more statements and they must be evaluated to bool, char, string, integral, enum or corresponding nullable type. We will discuss enum and strings in the coming lessons.
The following code snippet shows a general form of a switch statement.

            int switchExpression = 1;
            switch (switchExpression)
            {
                case 1 :
                    Console.WriteLine("You selected option 1 ");
                    break;
                case 2:
                    Console.WriteLine("You selected option 2");
                    break;
                case 3:
                    Console.WriteLine("You selected option 3");
                    break;
               case 4:
                    Console.WriteLine("You selected option 4");
                    break;
                default:
                    Console.WriteLine("You selected unspecified option");
                    break;

            }
The above code snippet that demonstrates the switch statement is evaluated as follows:


(1) The switch-expression is evaluated to int value which is hold inside a   variable called switchExpression; (2) If the value of the switch-expression matches a case label, the execution  starts from the matched case label and executes all statements until it reaches the break statement and then the
execution exits or breaks out of the switch block; and (3) If the value of the switch-expression does not match a case label,execution starts at the statement following the optional default label and executes any statement inside the default case.

The flowchart of the above switch code snippet is represented as follows:
 



The following program demonstrates the switch statement in C#.

/*
 * Author: Temesghen Tekeste
 * The switch statement in C#.
 * mail: mail.temesghen.tekeste@gmail.com
 * */

using System;

namespace SwitchDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Grade Report Generating System");
            String output = "";
            Console.Write("Enter your mark:");

            //Converting/type casting the input to double
            int studentMark = Convert.ToInt32(Console.ReadLine());
            //Determines which grade was entered
            switch (studentMark / 10)
            {
                case 10:
                case 9:
                    output = "Grade: A \nRemark: Outstanding!";
                    break;
                case 8:
                    output = "Grade: B \nRemark: Very Good!";
                    break;
                case 7:
                    output = "Grade: C \nRemark: Good!";
                    break;
                case 6:
                case 5:
                    output = "Grade: D \nRemark: You passed!";
                    break;
                case 4:
                case 3:
                case 2:
                case 1:
                case 0:
                    output = "Grade: F \nRemark: Very Failed!";
                    break;
                default:
                    output = "Grade: <ERROR> \nRemark: Grade could not be generated.";
                    break;

            }


            Console.WriteLine(output);
            Console.Write("Press any key to exit...");
            Console.ReadKey();
        }

    }
}