Describe Selection – if and switch using C++

Describe Selection – if and switch using C++.

- if is decision making control and its general for is :
if (this condition is true)
   execute this statement;
- The keyword if tells the compiler that what follows, is a decision control instruction. The condition following if is always enclosed in parenthesis. The statement(s) are executed if the condition is true.
- Example :
cout << “\n Enter number:”;
cin >> no;
if (no < 10)
   cout<< “Entered number is less than 10”;
- There is another variation to if statement : if-else
if (no < 10)
   cout << “No is less than 10”;
else if (no == 10)
   cout << “No is equal to 10”;
else
   cout << “No greater than 10”;
Switch :
- It is used to make choice between multiple options. When a decision is to be made depending upon value of an expression and the programmer knows the possible values it is going to take.
- The syntax is :
switch (integer expression)
{
   case constant1:
       do this;
   case constant2:
       do this;
   case constant3:
       do this;
   default:
       do this;
}
- Consider following program code :
cout << “\n Enter number:”;
cin >> no;
switch (no)
{
   case 1:
       cout << “I am in case 1”;
       break;
   case 2:
       cout << “I am in case 2”;
       break;
   case 3:
       cout << “I am in case 3”;
       break;
   default:
       cout << “I am lost!”;
}
- If user enters no 1, 2 or 3, this code will print the appropriate message. For any other no, it will go to the default case and print “I am lost!”
- The advantage of switch is that it leads to more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch. Thus switch statements are very useful in menu driven programs.
Explain Loops – While loop, Do-while loop, for loop
Explain Loops – While loop, Do-while loop, for loop - Loops are used to carry out certain instruction(s) in continuation for a fixed no of times.....
What are Vectors and Deques?
What are Vectors and Deques? - Vector is one type of standard container provided by C++ library...
Vector vs. deques
Vector vs. deques - Vector supports dynamically expandable array....
Post your comment
Discussion Board
C++ STRUCTURES
Yeah!! its precisely understandable .But i need more programs for more learning!
From DODOMA UNIVERSITY -TANZANIA
DAUDI NJALE 01-30-2013