Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views11 pages

Visual Programming Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Visual Programming Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT-2

CONTROL STATEMENTS

2.1 Introduction to control statements


2.2If , if else and if else ladder
2.3 Switch statement
2.4 For loop
2.5 Do while loop
2.6 While loop
2.7 Loop control statements

Introduction to Control Statements:


The control statements are used to control the flow of execution of the program. For
example, If, If-else, Switch-Case, while-do statements. If you want to execute a specific
block of instructions only when a certain condition is true, then control statements are useful.
If you want to execute a block repeatedly, then loops are useful.

C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition)
{
//code to be executed
}

C# If Example
publicclassSample
{
publicstaticvoid Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
} Output:
It is even number
C# IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
Else
{

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


1
//code if condition is false
}
C# If-else Example
publicclassSample
{
publicstaticvoid Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
Output:
It is odd number
C# IF-else-if ladder Statement
The C# if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}

C# If else-if Example
publicclassIfExample
{
publicstaticvoid Main(string[] args)
{
int num = 55;
Console.WriteLine("Given number ="+num);
if (num < 0 || num > 100)
{

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


2
Console.WriteLine("wrong number");
}
elseif (num >= 0 && num < 50)
{
Console.WriteLine("Fail");
}
elseif (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
elseif (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
elseif (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
elseif (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
elseif (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}
Output:
Given number =55
D Grade

C# switch Statement
Switch statement can be used to replace the if...else if statement in C#. The advantage of
using switch over if...else if statement is the codes will look much cleaner and readable with
switch.
The syntax of switch statement is:
switch (variable / expression)
{
case value1:
// Statements executed if expression (or variable) = value1
break;
case value2:
// Statements executed if expression (or variable) = value1
break;
... ... ...
... ... ...
default:
// Statements executed if no case matches
}

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


3
 The switch statement evaluates the expression (or variable) and compare its value
with the values (or expression) of each case (value1, value2, …). When it finds the
matching value, the statements inside that case are executed.
 But, if none of the above cases matches the expression, the statements
inside default block are executed. The default statement at the end of switch is similar
to the else block in if else statement.
 However, a problem with the switch statement is, when the matching value is found,
it executes all statements after it until the end of switch block. To avoid this, we
use break statement at the end of each case. The break statement stops the program
from executing non-matching statements by terminating the execution of switch
statement.

Example 1: C# switch Statement


classSwitchCase
{
publicstaticvoid Main(string[] args)
{
charch;
Console.WriteLine("Enter an alphabet");
ch = Convert.ToChar(Console.ReadLine());
switch (Char.ToLower(ch))
{
case 'a':
Console.WriteLine("Vowel");
break;
case 'e':
Console.WriteLine("Vowel");
break;
case 'i':
Console.WriteLine("Vowel");
break;
case 'o':
Console.WriteLine("Vowel");
break;
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
Output:
Enter an alphabet
j
Not a vowel
In this example, the user is prompted to enter an alphabet. The alphabet is converted to
lowercase by using ToLower() method if it is in uppercase.Then, the switch statement checks
whether the alphabet entered by user is any of a, e, i, o or u.If one of the case

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


4
matches, Vowel is printed otherwise the control goes to default block and Not a vowel is
printed as output.Since, the output for all vowels are the same, we can join the cases as:

Example 2: C# switch Statement with grouped cases


classSwitchCase
{ publicstaticvoid Main(string[] args)
{ charch;
Console.WriteLine("Enter an alphabet");
ch = Convert.ToChar(Console.ReadLine());
switch (Char.ToLower(ch))
{
case'a':
case'e':
case'i':
case'o':
case'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
The output of both programs is same. In the above program, all vowels print the
output Vowel and breaks from the switch statement. Although switch statement makes the
code look cleaner than if...else if statement, switch is restricted to work with limited data
types. Switch statement in C# only works with:
 Primitive data types: bool, char and integral type
 Enumerated Types (Enum)
 String Class
 Nullable types of above data types

Example 3: Simple calculator program using C# switch Statement


classSwitchCase
{
publicstaticvoid Main(string[] args)
{
char op;
double first, second, result;
Console.Write("Enter operator (+, -, *, /): ");
op = Convert.ToChar(Console.ReadLine());
Console.Write("Enter first number: ");
first = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second number: ");
second = Convert.ToDouble(Console.ReadLine());
switch (op)
{
case'+':
result = first + second;

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


5
Console.WriteLine("{0} + {1} = {2}", first, second, result);
break;
case'-':
result = first - second;
Console.WriteLine("{0} - {1} = {2}", first, second, result);
break;
case'*':
result = first * second;
Console.WriteLine("{0} * {1} = {2}", first, second, result);
break;
case'/':
result = first / second;
Console.WriteLine("{0} / {1} = {2}", first, second, result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
}
}
Output:
Enter first number: -13.11
Enter second number: 2.41
Enter operator (+, -, *, /): *
-13.11 * 2.41 = -31.5951
The above program takes two operands and an operator as input from the user and performs
the operation based on the operator. The inputs are taken from the user using
the ReadLine() method. The program uses switch case statement for decision making.
Alternatively, we can use if-else if ladder to perform the same.

C# for loop
In programming, it is often desired to execute certain block of statements for a specified
number of times. A possible solution will be to type those statements for the required number
of times. However, the number of repetitions may not be known in advance (during compile
time) or maybe large enough (say 10000). The best solution to such problem is loop. Loops
are used in programming to repeatedly execute a certain block of statements until some
condition is met. The for keyword is used to create for loop in C#. The syntax for ‘for’
loop is:
for (initialization; condition; iterator)
{
// body of for loop
}

How for loop works?


 C# for loop has three statements: initialization, condition and iterator.
 The initialization statement is executed at first and only once. Here, the variable is
usually declared and initialized.
 Then, the condition is evaluated. The condition is a boolean expression i.e., it returns
either true or false.
 If the condition is evaluated to true:

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


6
 The statements inside the for loop are executed.
 Then, the iterator statement is executed which usually changes the value of the
initialized variable.
 Again, the condition is evaluated.
 The process continues until the condition is evaluated to false.
 If the condition is evaluated to false, the for loop terminates.

Example 1: C# for Loop


class ForLoop
{ public static void Main(string[] args)
{ for (int i = 1; i <= 5; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}

When we run the program, the output will be:


C# For Loop: Iteration 1
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5

In this program,
 initialization statement is int i=1
 condition statement is i<=5
 iterator statement is i++

When the program runs,


 First, the variable i is declared and initialized to 1.
 Then, the condition (i<=5) is evaluated.
 Since, the condition returns true, the program then executes the body of the for loop.
It prints the given line with Iteration 1 (Iteration simply means repetition).
 Now, the iterator (i++) is evaluated. This increments the value of i to 2.
 The condition (i<=5) is evaluated again and at the end, the value of i is incremented
by 1. The condition will evaluate to true for the first 5 times.
 When the value of i will be 6 and the condition will be false, hence the loop will
terminate.

Example 2: for loop to compute sum of first n natural numbers


namespace Loop
{ class ForLoop
{ public static void Main(string[] args)
{ int n, sum = 0;
Console.WriteLine("Enter any number: ");
n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


7
sum = sum + i;
}
Console.WriteLine("Sum of first {0} natural numbers = {1}", n, sum);
}
}
}
When we run the program, the output will be:
Enter any number:
5
Sum of first 5 natural numbers = 15

C# while loop
The while keyword is used to create while loop in C#. The syntax for while loop is:
while (test-expression)
{
// body of while
}

How while loop works?


 C# while loop consists of a test-expression.
 If the test-expression is evaluated to true, statements inside the while loop are
executed.
 After execution, the test-expression is evaluated again.
 If the test-expression is evaluated to false, the while loop terminates.

Example 1: while Loop


class WhileLoop
{ public static void Main(string[] args)
{ int i = 1;
while (i <= 5)
{
Console.WriteLine("Iteration "+i);
i++;
}
}
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Example 2: while loop to compute sum of first 5 natural numbers


class WhileLoop
{ public static void Main(string[] args)
{ int i = 1, sum = 0;
while (i <= 5)
{
sum += i;

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


8
i++;
}
Console.WriteLine("Sum = {0}", sum);
}
}
When we run the program, the output will be:
Sum = 15

 This program computes the sum of first 5 natural numbers.


 Initially the value of sum is initialized to 0.
 On each iteration, the value of sum is updated to sum+i and the value of i is
incremented by 1.
 When the value of i reaches 6, the test expression i<=5 will return false and the loop
terminates.

C# do...while loop
 The do and while keyword is used to create a do...while loop. It is similar to a while loop,
however there is a major difference between them.
 In while loop, the condition is checked before the body is executed. It is the exact
opposite in do...while loop, i.e. condition is checked after the body is executed.
 This is why, the body of do...while loop will execute at least once irrespective to the test-
expression.
 The syntax for do...while loop is:
do
{
// body of do while loop
} while (test-expression);

How do...while loop works?


 The body of do...while loop is executed at first.
 Then the test-expression is evaluated.
 If the test-expression is true, the body of loop is executed.
 When the test-expression is false, do...while loop terminates.

Example 3: do...while loop

class DoWhileLoop
{ public static void Main (string [] args)
{ int i = 1, n = 5, product;
do
{
product = n * i;
Console.WriteLine("{0} * {1} = {2}", n, i, product);
i++;
} while (i <= 10);
}
}
}

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


9
When we run the program, the output will be:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

 As we can see, the above program prints the multiplication table of a number (5).
 Initially, the value of i is 1. The program, then enters the body of do……while loop
without checking any condition (as opposed to while loop).
 Inside the body, product is calculated and printed on the screen. The value of i is then
incremented to 2.
 After the execution of the loop’s body, the test expression i <= 10 is evaluated. In total,
the do...while loop will run for 10 times.
 Finally, when the value of i is 11, the test-expression evaluates to false and hence
terminates the loop.

Control Statement
A control statement allows the loop to change its course from its normal sequence. The C#
programming language offers the following basic loop control statements.

Continue Statement
Continue statement in C# is used to execute the next iteration of the loop while skipping any
code in between. The syntax of the continue statement is “continue;”
class Program
{ static void Main(string[] args)
{ for (int i = 1; i <= 8; ++i)
{ if (i == 5)
{
continue;
}
Console.Write(i);
}
}
} Output:
1234678
Break Statement
Break statement in C# is used for the following reasons:
 It is used to terminate a loop so that the program can continue with the next
loop statement. In nested loops it can be used to stop the execution of the inner
loop, thereby providing the program control to the next statement after the
current code.
 It can be used to terminate a statement in the Switch Case.
The syntax of the break statement is “break;”

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


10
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; ++i)
{
if (i == 5)
{
break;
}
Console.Write(i);
}
}
}

Output:
1234

Er Ranjeet Kumar Singh @Visual Programming (Unit-2)


11

You might also like