This blog will take various topics of C# programming and provide easy examples for understanding the concepts.

Saturday, December 30, 2006

Conditional Statements and Looping

Most of the programming languages provide for conditional constructs, to enable the developer to provide for decision making in the program and respond to multiple scenarios.

The IF Statement:

Assuming you are writing a program, which:

1) Asks the user his age

2) If the age is > 30 the program outputs "You are so old"

3) If the age is < 30 the program outputs "You are so young"

Type this program in your favourite text editor:

Compile the program using the csc compiler . The syntax is : csc SampleIfStatement.cs

To Run the program, call the program with one paramter as the age:

The IF Statement with ELSE IF:

There are situationns wherein you may want to handle more than 1 situations in your code. Normally if there
were too many possibilities , you would go for the SWITCH statement which will take it later on. But if there

are just 2/4 possibilities , you may use the IF statement with the ELSE IF flavour.

Let us take an example to get a more clear idea for this construct:

Type this code in your favourite editor:

Compile and run the program:

Switch Case Statement

The Switch statement can be used to control the flow of the program by passing control to one of the case statements which evaluates to true in the scenario.

For example you want to write a program which does the following:

1) Take the input of the user

2) If the user enters 1 : output "You selected Option 1: Add User"

3) If the user enters 2: output "You selected Option 2: Delete User"

4) If the user enters 3: output "You selected Option 3: Modif User"

5) If the user enters any other number : output "You selected to Exit"

Edit the Program for Switch Case Statement:

Compile and run the program:

No comments: