You are on page 1of 8

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

4. Control Statements
Control statements are used to change the normal top-down sequence or linear sequence of program execution. If a block of statements has to be skipped we use the control statements to bypass this block. Similarly, if a block of statements has to be repeated many times, we use control statements that will cause this repetition to take place. C# has the following types of control statements: 1. Selection statements: a. If statement b. If … else statement c. Switch … case statement d. ? : operator 2. Iterative statements a. for loop b. while loop c. do loop d. foreach statement In this section we discuss the selection statements.

if statement:
The if statement executes a given set of statements based on the condition given by the programmer. Syntax: if (boolean expression) statement-1 If boolean expression is true, then statement-1 is executed, otherwise statement-1 is skipped.

if – else statement:
The if – else statement is an extension of the simple if statement. Syntax: if (boolean expression) statement-1 else statement-2 If boolean expression is true, then statement-1 is executed, otherwise statement-2 is executed. Statement-1 and statement-2 may be a single statement or a set of statements. In case it is a set of statements, then these are enclosed in between the pair of braces { and }.

Page 1 of 8

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

Nesting of if statements:
Nesting is the inclusion of one statement within another. If one if statement is placed inside another if statement we say that the if statements are nested. Nesting can be done in the if section or in the else section. Example: if (condition1) { //action statements-1 } else { if (condition2) { //action statements - 2 } else { //action statements - 3 } } A complete if …else statement is nested within the else section of the outermost if statement. This nested if statement is shown in bold in the above code. If condition-1 is true, the first if statement is true and action statements-1 are executed after which control exits the outermost else statement. If condition-2 is false, control passes to the first if condition inside the else (i.e. condition-2 is checked). If condition-2 is true, then action statements -2 are executed and control exits the if …else structure. This corresponds to the case: condition-1 false and condition-2 true. If condition-2 is false, control passes to the action statements-3. After executing action statements-3, control exits from the if…else structure. This is equivalent to the case: condition-1 false and condition2 false.

Stacking if statements
Stacking if statements combines the else part with another if statement. The following example illustrates this:

Page 2 of 8

Control Statements

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

4. Programming in C# Example: if (cond-1) { action-1 } else if (cond-2) { action-2 } else { action-3 } action-4 }

Switch-case statement:
The switch case statement is a selection statement. It is used when there are a number of possible values to be tested and multiple if-else statements become difficult to use. Syntax : switch (value) { case result1: // do statements for result 1 break; case result2: // do statements for result 2 break; case result3: // do statements for result 3 break; ..... default: // do statements for default case break }

Control Statements

Page 3 of 8

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

We observe the following in switch – case statement: 1. There is no condition to check. 2. A value is used to branch to the appropriate code. 3. Two case statements cannot have the same value. 4. The value mentioned in the switch statement may be a variable or an expression. 5. The value is compared to each value in the case statement. If the value matches, the code corresponding to that case is executed. 6. If the value does not match any of the values given in case statement, then control flows to the default case. 7. If default case is not mentioned, then control goes to the statement immediately after the switch statement. 8. Each case is terminated by the break statement. This statement signifies the end of the code of that case. If break statement is not given, compiler generates an error. Fallthrough in switch statement: In C, C++, and Java, break statement may be omitted in a case block. The control moves to the next block without any errors. This is called as “fallthrough”. But in C#, this fallthrough is not permitted if the case block contains executable code. However, if the code block is empty, then falltrough is permitted in C#. If we want two consecutive case blocks to be executed one after the other, we must force control to go to the next case by using the goto statement

Iterative statements
Iterative statements are used to repeat a statement a number of times. E.g., if we want to print numbers from 1 to 10, or find all prime numbers between 1 to 100, we will use the technique of iteration. C# has the following types of iteration statements: Iterative statements 1. while for loop 2. do loop 3. for loop 4. foreach statement

while loop :
The format of the while loop is: Initialization while (condition) { body of the loop } Page 4 of 8 Control Statements

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

4. Programming in C# 1. The condition is checked first. 2. This loop is called an entry-controlled loop; the condition is checked first, and if it is true, control passes into the body of the loop and statements inside the loop are executed. 3. If the condition is initially false, the body of the loop is not executed at all. 4. After each iteration, control goes back to check if the condition is true. 5. There must be some statement in the body of the loop that makes the condition eventually false, otherwise the loop will continue forever. 6. When the condition becomes false, control passes to the statement after the while loop. Example: The following program prints the value of n using the while loop
class WhileTest { static void Main() { int n = 1; while (n < 6) { Console.WriteLine("Current value of n is {0}", n); n++; } } }

Program 1: To reverse a number entered by the user.
// Reverse a number entered by the user using System; namespace reverse { class reverse { static void Main() { int num, revnum = 0, d; Console.WriteLine("Enter a number"); num = int.Parse(Console.ReadLine()); while (num > 0) { d = num % 10; revnum = revnum * 10 + d; num = num / 10; }

// get the least significant digit // reverse partially // drop the least significant digit

Console.WriteLine("Reversed number is {0}", revnum); Console.ReadLine(); } } }

Control Statements

Page 5 of 8

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

Program 2: Program to count the number of digits in an integer.
//To count the number of digits in an integer using System; namespace CountDigits { class count { static void Main() { int num, ctr = 0; Console.WriteLine("Enter an integer"); num = int.Parse(Console.ReadLine()); while (num > 0) { num = num / 10; ctr = ctr + 1; } Console.WriteLine("No. of digits is {0}", ctr); Console.ReadLine(); // end of Main // end of class // end of namespace

} } }

Program 3: Program to print the average of 10 numbers entered by the user.
//Average of 10 numbers entered by the user using System; namespace AverageMany { class average { static void Main() { int num, sum = 0, ctr = 0; float avg; while (ctr < 10) { Console.WriteLine("Pls enter a number"); num = int.Parse(Console.ReadLine()); sum = sum + num; ctr++; } avg = (float)sum / ctr; Console.WriteLine("Average is {0}", avg); Console.ReadLine(); } } }

Page 6 of 8

Control Statements

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

4. Programming in C#

do - while loop :
The do-while loop is used when it is necessary to execute the body of the loop at least once. The general format of the do-while loop is : initialization do { body of the loop } while (condition); 1. After the initialization, control passes to the body of the loop and the statements in the loop are executed. 2. The condition specified in the while part is then checked. If the condition is true, the body of the loop is executed once again. 3. If the condition becomes false, the body of the loop is not executed and control passes to the statement after the do-while loop.. 4. There must be some statement in the body of the loop that makes the condition eventually false, otherwise the loop will continue forever. 5. Since the condition is checked at the bottom of the loop, the do-while loop is also called an exitcontrolled loop. 6. The body of the loop is executed at least once.

IMPORTANT QUESTIONS
1. 2. 3. 4. What is the use of control statements in programming languages? Explain the following selection statement: if … else in C# When is a switch – case statement used in C# programs? Explain the concept of “fallthrough”. Is the following if statement valid? If so, what is the value of x after this code executes? int x = 2; int y = 3; if (x == 2) if (y < 3) x = 5; else x = 9; In what way does the switch statement differ from the if statement? When is it preferable to use the switch statement? Explain nested if statements with the help of an example. Explain the concept of stacking of if statements with the help of an example. What is iteration? Which iteration statements are supported by C#? Page 7 of 8

5. 6. 7. 8.

Control Statements

Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

Prof. Mukesh N. Tekwani

Email: mukeshtekwani@hotmail.com

9. Explain the while loop. Draw the relevant flowchart. Give suitable examples. Under what condition will the while loop become an infinite loop? 10. What precautions must be taken in using the while loop? 11. Explain the do-while loop. Draw the relevant flow chart. Under what condition will the while loop become an infinite loop? 12. Explain the for loop. Draw the relevant flowchart. Give an example to illustrate the use of this loop. 13. Compare the looping structures while and for. 14. Compare the looping structures do and for.

PROGRAMMING EXERCISES
1. Write a program to add all the even numbers from 0 to 20. Use simple if and goto statements to form a loop of operations. 2. Write a program that accepts an integer between 1 and 7, and based on the input, it prints the day of the week. Assume Monday = 1, etc. If input is not in the range 1 to 7, print an appropriate error message and terminate the program. 3. Write a program to find the product of digits of an integer. E.g., if the integer is 2156, the output should give 2*1*5*6 i.e., 60. 4. Write a program to check whether a given digit d is present in an integer entered by the user. 5. Write a program to count the number of times a given digit d appears in an integer. 6. Write a program to count the number of odd and even digits in a number. 7. Write a program to print only the odd / even digits of an integer. 8. Write a program to print the following series: 2, 8, 18, 32, upto first 7 terms. 9. Write a program to compute the sum of squares of first 10 natural numbers. 10. Write a program to compute the sum of the first 10 odd / even natural numbers. 11. Write a program to print the average of n numbers entered by the user. User will also input the value of n.

Page 8 of 8

Control Statements