C# Tutorial : Lesson 3 - Programming Constructs

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > .NET (VB, C# & J#)

C# Tutorial : Lesson 3 - Programming Constructs

turbopowerdmaxsteel
Conditional Branching

By branching we imply, having different paths for execution. Conditions are used to determine which statements need to be executed. Suppose, you have a program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.

C# provides the following conditional constructs:-

if .. else

Syntax:-
if ( < condition > )
{
statements
}
else
{
statements
}

The else part is optional and can be omitted. The working of if .. else construct is very simple and follows the pattern - If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, the execution flow continues to the proceeding statements.

Here’s an example:-

CODE
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
    Console.WriteLine("You are not permitted in here.");
}
else
{
    Console.WriteLine("You may come in.");
}


Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 - Console.WriteLine("You are not permitted in here."); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed.

The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:-

CODE
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian = false))
{
    Console.WriteLine("You are not permitted in here.");
}
else
{
    Console.WriteLine("You may come in.");
}


At line 4 the user's response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian = false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message - You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message - You may come in will be displayed.

A number of conditions can be chained by using else if as follows:-

CODE
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
    Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
    Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
    Console.WriteLine("Welcome Programmer");
}
else
{
    Console.WriteLine("Welcome dear Customer");
}


In this case, if the salary supplied by the user is greater than 250000, the message - Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message - Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.

switch .. case Construct
Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.

Syntax:-
switch (< expression >)
{
case Expression_1;
statements
break;

case Expression_2;
statements
break;

….

}

break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.

Example:-

CODE
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
    case 1:
        Console.WriteLine("January");
        break;

    case 2:
        Console.WriteLine("February");
        break;

    case 3:
        Console.WriteLine("March");
        break;

    case 4:
        Console.WriteLine("April");
        break;

    case 5:
        Console.WriteLine("May");
        break;

    case 6:
        Console.WriteLine("June");
        break;

    case 7:
        Console.WriteLine("July");
        break;

    case 8:
        Console.WriteLine("August");
        break;

    case 9:
        Console.WriteLine("September");
        break;

    case 10:
        Console.WriteLine("October");
        break;

    case 11:
        Console.WriteLine("November");
        break;

    case 12:
        Console.WriteLine("December");
        break;

    default:
        Console.WriteLine("There are only 12 Months.");
        break;
}


Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months. will be displayed.

Multiple Values can be made to lead to the same block of statements by excluding the break statement.

CODE
Console.WriteLine("Enter a number  (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
    case 2:
    case 3:
    case 5:
    case 7:
        Console.WriteLine("The number is prime.");
        break;
    case 1:
    case 9:
        Console.WriteLine("The number is odd.");
        break;
    case 4:
    case 6:
    case 8:
        Console.WriteLine("The number is Even");
        break;
    default:
        Console.WriteLine("The number is not in range.");
        break;
}



Looping

A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 - 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 - 1000? Using the computer’s iterative power is a much better approach.

C# supports 3 kinds of loops which are discussed below:-

The for loop
This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-

for(< initialization >;< condition >;< increment/decrement >)
{
statements
}

To print numbers within a range, say 1 - 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.

CODE
for(int I = 1; I <= 1000; I++)
{
    Console.WriteLine(I);
}


Lets break the for statement down:-
Initialization: int I = 1
Condition: I <= 1000
Increment: I++

All the parts here are optional and can be left out. So, you can initialize the variable I, above the for statement and leave out the initialization block. The code would look like this (; I <= 1000; I++). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).

Another variation of a for statement is the empty loop which does not contain any body: for(int I = 1; I <= 1000; I++);

Such a for statement is followed by the semicolon.

The while loop
The for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the while statement.

Syntax:-
while(< condition >)
{
statements
}

We don’t have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.

CODE
bool Continue = true;
while(Continue == true)
{
    int A;
    Console.WriteLine("Please Enter a Number");
    A = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Continue (True/False)");
    Continue = Convert.ToBoolean(Console.ReadLine());
}


We have declared a boolean variable Continue which we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user’s choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the while loop would keep on executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 - 1000 using while.

CODE
int I = 1;
while(I <= 1000)
{
    Console.WriteLine(I);
    I++;
}


The do while loop
The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable continue stores the user’s choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.

CODE
bool Continue;
do
{
    int A;
    Console.WriteLine("Please Enter a Number");
    A = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Continue (True/False)");
    Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);


Note: The while part in the do while loop needs to be terminated with the semicolon.

Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

Previous Tutorial - Lesson 2 - Variables & Operators

Next Tutorial - Lesson 4 - Object Oriented Programming

Lesson: 1 2 3 4 5 6 7

 

 

 


Reply

iGuest
I need this program
Write a pgm to identify whether a character entered by a user is a vowel or a consonant

-reply by darlee

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. what is the syntax of switch case in c#.net - 1.01 hr back. (1)
  2. c# constructs - 2.65 hr back. (1)
  3. c# programming tutorial expressions and syntax - 6.25 hr back. (1)
  4. c# check if number entered is zero - 8.58 hr back. (1)
  5. multiple while conditions in one loop c# - 10.70 hr back. (1)
  6. c# switch case range of numbers - 12.42 hr back. (1)
  7. for loop c# multiple conditions - 12.43 hr back. (1)
  8. c# convert.toboolean example - 18.11 hr back. (1)
  9. if condition in c#.net - 20.71 hr back. (1)
  10. what is programming constructs in c# - 21.18 hr back. (1)
  11. what are the 3 looping statement of c programming - 24.55 hr back. (1)
  12. operators and programming constructs - 28.93 hr back. (1)
  13. construct in class c# - 29.68 hr back. (1)
  14. identify the vowels using else if statement - 48.95 hr back. (2)
Similar Topics

Keywords : c, tutorial, lesson, 3, programming, constructs

  1. C# Tutorial : Lesson 9 - Constructors & Destructors
    (0)
  2. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  3. C# Tutorial : Lesson 7 - Creating Value Types & Reference Types - Part II
    (1)
    foreach statement This statement is explicitly used to traverse through arrays. The
    benefit of using foreach over the normal for statement is that it is not needed to check the
    size of the array while using the former. Syntax:- foreach(type identifier in expression) {
    statement 1; statement 2; .... } Suppose we have an array StudentNames containing the name of all
    the students in a class. We need to display the name of each one of them on screen. First we will
    see how it can be done using the for loop. CODE string[] StudentNames = new s....
  4. C# Tutorial : Lesson 6 - Creating Value Types & Reference Types - Part I
    (0)
    Value Types & Reference Types In C#, Variables are either value types or reference types
    depending on what they store, values or references. By reference we imply that the variable holds
    the memory address of another location where the actual value is stored. All built in data types -
    Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The
    following is a diagrammatic representation of these two types. In this picture there are two
    variables Num1 and Num2. Both of these being integer variables store the values directly.....
  5. C# Tutorial : Lesson 5 - Encapsulation & Abstraction
    (0)
    Encapsulation & Abstraction Two concepts that go together in the object oriented approach
    are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of
    an object, while Encapsulation is the hiding of the non-essential features. Think of a person
    driving a car. He does not need to know the internal working of the engine or the way gear changes
    work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much
    turning the steering wheel needs, etc (Abstraction). Consider the example from ....
  6. C# Tutorial : Lesson 4 - Object Oriented Programming
    (2)
    Object Oriented Programming Object Oriented Programming is a methodology modeled on real
    life. It comprises of the basic unit, an object, being used in implementing a program. Think of all
    the objects around you - cars, buses, birds, trees, etc. You will find countless ones of them,
    everywhere you go. In order to tackle this huge number, we started classifying them, thus came the
    term Class. Class A class is a composition of the theoretic characteristics (attributes and
    properties) of an object and the things it can do - behaviors, methods and features. Tak....
  7. C# Tutorial : Lesson 2 - Variables & Operators
    (0)
    Variables A Variable is a named location that stores a value. Although variables are
    physically stored in the RAM, their actual memory address is not known to the programmer. We can use
    the variables via the name we give them. These are the rules for naming a variable:- The name must
    begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9)
    or underscore (_) Special Characters such as ? - + * / \ ! @ # $ % ^ ( ) { } , ; :
    . cannot be used in the variable name. A variable name must not be the same a....
  8. C# Tutorial : Lesson 1 - Hello World Program
    (0)
    This is the first installment of my venture to explain the bits and pieces of C# that I have managed
    to learn at NIIT. In this lesson we would be creating the Hello World application. STEP 1 : Create
    a New Console Application in Visual C# The IDE automatically adds the following code:- CODE
    using System; using System.Collections.Generic; using System.Text; namespace HelloWorld {
        class Program     {         static void Main(string[] args)         {         }
        } } Lets take a look at the first 3 lines. All of these lines begin with t....
  9. Lesson #3 - Basic Math Operators And Random #s
    Lesson #3 - Basic Math Operators and Random #s (0)
    In this lesson I will cover how to use basic math operations, well addition really but you can also
    use subtraction , division and multiplication . I would also like to note that when doing
    division, if variabes of int type are used you will not get any remainders (i.e. n.345984). To be
    able to work with real numbers, numbers with decimals, you can use float. Below is a way to declare
    a float and assign it a value: float floatNumber; float Number = 28.47f; Aside from
    generating random numbers and basic math operations, we will also incorporate an if statement a....
  10. Lesson #2 - Switch Statement In C#
    Using the Switch Statement in C# (1)
    In the previous lesson we demonstrated did a basic input output application which asked your your
    name and replied with a general greeting using the name you entered. In this lesson we are going
    to learn about a conditional statement called the switch statement. Usually if and if else
    statements are taught before switch statements. Although these are very useful, I find the switch
    to be easier and more fun to use. The program written below is very similar to the previous
    program where the user is asked to enter their name, however now the program will loo....
  11. Lesson #1 - Introduction To C#
    Console Application (0)
    This tutorial will help get you started with C# Sharp. These tutorials will assume that you are
    using the Visual Studio environment. If you are just curious to test out some code, then you can
    copy and paste this code into your CS file, however, before doing so, make sure to name your project
    the same as the namespace on the code. But since this first program is fairly easy, it will not
    hurt to type it out. It is fairly easy and short. Also, this program is highly commented so it
    should be easy to follow along. Comments will have 2 forward slashes before them '....

    1. Looking for c, tutorial, lesson, 3, programming, constructs

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for c, tutorial, lesson, 3, programming, constructs
advertisement




C# Tutorial : Lesson 3 - Programming Constructs



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE