Wednesday, March 4, 2020

FLOW-CONTROL STRUCTURES


Tools needed:
1.    PC running Windows Operating System (OS)
2.    DevC++ (installed)

Turn on the PC and log into it using your student account information.

Note:
The information and concepts discussed in this lab manual are in sufficient detail but are still not exhaustive. It is assumed that all these concepts are already taught to you in your ITC theory class.

1.    Relational and Logical Operators

To know how values of two variables (usually of the same type) are related to each other, relational operators are used. Relational operators are:

< 
Less than
<=
Less than or equal to
> 
Greater than
>=
Greater than or equal to
==
Equal to
!=
Not equal to

Relational operators are used in conjunction with flow control structures as explained later in this lab manual.

For now, understand that a 'relational statement' (or condition) evaluates to a result of type bool. That is, a relational statement is evaluated either as true or false. The value true is represented by a 1 and false by 0.

For example, look at the following unusual chunk of code:

int x = 100;
x = x > 10;
cout << x << endl;

Guess what would be the value printed on the console window.

Write code in DevC++ and verify!

Sometimes multiple relational statements are needed to be grouped together to form one test expression or condition. To do so, logical operators are used. Logical operators are:

&&
Logical AND
||
Logical OR
!
Logical Not

While the true essense of grouping relational statements would be clear in subsequent sections, look at the following chunk of code:

int x = 100;
x = (x > 10) && (x <= 90);
cout << x << endl;

Guess what would be the value printed on the console window now.

Write code in DevC++ and verify!

How about this one:

int x = 100;
x = !(x > 10) && (x >= 90);
cout << x << endl;

Guess what would be the value printed on the console window now.

In order to resolve relational statements grouped together in logical test expressions, this is how to proceed.

First resolve each relational statement alone to see whether they are true or false. For example in the case above, x > 10 is true but !(true) is false. x >= 90 is true. Now (false AND true) by rules of boolean logic is false which is represented by value 0.
If the logical AND operator is replaced with the logical OR operator the overall value will be true because x >= 90 will be true.

2.    if, if-else, if-else if-else control structure

A C++ code is executed in series one statement (or line) at a time. At times we do not wish some statements to get executed at all times but only when a certain condition is met during the running of the code.

To control the flow of execution of the code, we use some control structures, viz., if-else and switch-case, which are elaborated below.

Using relational and logical operators we prepare a test expression which is tested at runtime and can either be true or false. Based on whether the test expression is true or false certain code sections are executed or skipped.







if statement:
The syntax is:

if( testexpr )
{
      //statements to execute if testexpr is true
}

The if statement 'evaluates' the testexpr inside the paranthesis which evaluates in a bool value (i.e., either true represented as a bool value of 1 or false represented as 0).
If the testexpr evaluates to true, the statements inside the body of if are executed. If the testexpr evaluates to false, the statements inside the body of if are skipped.

if-else statement:
The syntax is:

if( testexpr )
{
      //statements to execute if testexpr is true
}
else
{
      //statements to execute if testexpr is false
}

If the testexpr evaluates to true, the statements inside the body of if are executed. If the testexpr evaluates to false, the statements inside the body of else if are executed.

Note that the body of an if or else statement is marked by braces { and }. In case no braces are used, only one statement following the if statement is included in the body.
For example in the code below:

if( x > 0 )
      x += 10;
      y --;

if value of variable x is greater than 0, only then value of x is incremented by 10 but the value of y will always be decremented by 1 whatever the value of x is, since the statement y--; lies outside the body of if statement despite the indentation.
The same is true for else.

if-else if-else statements:
The syntax is:

if( testexpr1 )
{
      //statements to execute if testexpr1 is true
}
else if ( testexpr2 )
{
      //statements to execute if testexpr2 is true
}
else if ( testexpr3 )
{
      //statements to execute if testexpr3 is true
}
else
{
      //statements to execute if no condition is true
}

3.    Nested control structures

The above form is also called Nested if-else becasue if you look closely 'else if' is not a single keyword, rather the already taught keywords else and if separately. This means the if after else is in the body of else, and the subsequent else is the else that belongs to the last if.

Our usual way of indenting the body of if and else will make this clear. For example the chunk of pseudocode below is exactly the same as the previous one but clearly elaborates the nesting:

if( testexpr1 )
{
      //statements to execute if testexpr1 is true
}
else
      if ( testexpr2 )
      {
            //statements to execute if testexpr2 is true
      }
      else
            if ( testexpr3 )
            {
                  //statements to execute if testexpr3 is true
            }
            else
            {
                  //statements to execute if no condition is true
            }

Note how the if-elses are nested within elses!

Nesting can go as deep as is required. There is no limit on the level of nesting.

If the testexpr1 evaluates to true, the statements inside the body of if are executed. If the testexpr1 evaluates to false, the single statement inside the body of else is executed, which in itself is an if-else statement, and so on.

Nesting can be done within if body as well, if required.

For example look at the case below:

if( testexpr1 )
{
      //statements to execute if testexpr1 is true
      if( testexpr11 )
      {
            //statements to execute if testexpr11 is true
            if( testexpr111 )
            {
                  //statements to execute if testexpr111 is true
            }
      }
}

4.    ternary operator (? :)

Sometimes for simpler conditions ternary operator is used for better readability. For example look at the code:

if( a < b )
      max = b;
else
      max = a;

Which can be written more compactly as:

max = a < b ? b : a;

to mean the same thing. Alternatively:

a < b ? max = b : max = a;

carries the same behaviour.

5.    switch-case control structure

if-else statement allows us to check multiple test expressions or conditions through the use of logical operators. However, in cases where we need to check the value of a single variable instead of nested if-elses, use of a switch-case control structure is preferrable.

For example to test a varaible n for various values, switch-case syntax is as follows:

switch( n )
{
      case constant1:
            //code to be executed if n is equal to constant1
            break;
      case constant2:
            //code to be executed if n is equal to constant2
            break;
      case constant3:
            //code to be executed if n is equal to constant3
            break;
      .
      .
      .
      default:
            //code to be executed if n doesn't match any constant
}
When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block of code associated with the case statement until the end of switch block, or until the break statement is encountered.
The break statement is used to prevent the code running into the next case.
If break statement is not used, all cases after correct case are executed. Sometimes this may be desirable.


Give special attention to few important aspects of coding as mentioned below before moving to actual coding tasks.

Operator precedence:
In case multiple operators are used in a single statement without parantheses then the order in which the operations will be performed depends on the precedence of the operators.
The following table illustrates operators in the order of their precedence.

Operators
Precedence
!, +, - (unary operators)
First
*, /, %
Second
+, -
Third
<, <=, >, >=
Fourth
==, !=
Fifth
&&
Sixth
||
Seventh
= (assignment operator)
Last

So in the following code:

int x; x = !x > 10 && x >= 90;

First of all the unary operation of logical NOT will be performed on the variable x. If value of x is 100 (true in bool), !x will result in false (i.e. 0 in int). All this is because x taken as a relational operation implicitly typecasts int to bool.
After !, the precedence of > and >= is same so the operator on the left will be evaluated. Below is given a step by step procedure to highlight evaluation of operators in order.

x = !x > 10 && x >= 90;
x = !true > 10 && x >= 90;
x = false > 10 && x >= 90;
x = 0 > 10 && x >= 90;
x = false && x >= 90;
x = false && true;
x = false;
x = 0;




To do something against rules of precedence, parantheses are used. For example:

x = !(x > 10) && x >= 90;

Relational statements to test a range of values of a variable:
A C++ statement of the form in an if statement would produce unexpected results:

if ( 0 < x < 10 )

First try to find the values (or range of values of variable x) for which the condition would be true. Then write a sample code and verify your answer.

The correct way of writing the statement would be:

if ( 0 < x && x < 10 )

Verify!

Comparing floating point numbers for equality:
When comparing a floating point number with a specific value caution is needed. Floating point values are rounded off and stored in floating point data types based on their size. Sometimes a slight change in floating point value does not affect the stored bits at all (remember a learning in one of the previous labs).

Thus trying to check a whether a variable f results into the value of p after some computation as:

if ( f == 3.14159 )

would produce unexpected results if the value of f is not exactly 3.14159 or not stored as 3.14159!

Based on the precision requirements of the problem, instead of trying to match for a specific value, check whether the value falls within a range of acceptable values or not. For example, expecting the answer to be correct to 3 decimal places, the following code should be written to check if f equals the desired value or not.

if ( f > 3.1415 && f < 3.1417 )



To test the concepts discussed in this lab manual write C++ code for as many of the following tasks as possible.

Practice Tasks:

Task # 1: Code file name lab5_1.cpp
Write a program that can check whether the number entered by user is positive, negative or zero. Perform this task using if/else statement and switch case.

CODE:

#include <iostream>
using namespace std;
int main ()
{
            int n;
            cout <<"Enter any number :";
            cin>> n;
           
{
            if( n==0 )
           
{
            cout <<"The entered number is zero";
           
}
}
if( n>0 )
           
{
            cout <<"The entered number is positive";
           
}
else
if (n<0)
{
   
            cout <<" The entered number is negative";
           
}

return 0;
}





Task # 2: Code file name lab5_2.cpp
Write a program to check whether an integer value entered by user is even or odd. Perform this task using if/else statement and switch case.

CODE:

#include <iostream>
using namespace std;
int main ()
{
            int n,i;
            cout <<"Enter any number any number:";
            cin>> n;
/*          if( n%2==0 )
{
            cout <<"The entered number is even ";
           
}
else
{
            cout <<"The entered number is odd";
           
}
*/
            i=n%2==0;
            switch( i )
{
            case 0:
                        cout <<"entered number is odd";
                        break;
   case 1:
                        cout <<"the entered number is even";
                        break;
           
            default:
                        cout <<"invalid:";
}
return 0;
}



Task # 3: Code file name lab5_3.cpp
Write a program that can find maximum between three numbers entered by user. Perform this task using if/else statement and switch case.
#include <iostream>
using namespace std;
int main ()
{
            int n,i,m,l;
            cout <<"Enter 1st number:";
            cin>> n;
            cout <<"Enter 2nd number:";
            cin>> m;
            cout <<"Enter 3rd number:";
            cin>> l;
if( m>n&&m>l )
{
            cout <<"greatest number is: "<<m;
}
else
            if (  n>m&&n>l )
            {
            cout <<"Greatest number is: "<<n;
            }
            else
                        if ( l>m&&l>n )
                        {
                        cout <<"greatest number is: "<<l;
                        }
                        else
                        {
                                    cout <<"invalid";
                        }


return 0;
}



Task # 4: Code file name lab5_4.cpp
Write a program to check whether a char value entered by user is a vowel or consonant. Use switch-case.

#include <iostream>
using namespace std;
int main ()
{
char alpha;
cout<<"enter an alphabet :";
cin>>alpha;
switch (alpha)
{
case 'a':
            cout <<"The  entered alphabet is a vowel";
     break;
     case 'A':
            cout <<"The  entered alphabet is a vowel";
     break;
     case 'E':
            cout <<"The  entered alphabet is a vowel";
     break;
     case 'I':
            cout <<"The  entered alphabet is a vowel";
     break;
     case 'O':
            cout <<"The  entered alphabet is a vowel";
     break;
     case 'U':
            cout <<"The  entered alphabet is a vowel";
     break;
case 'e':
            cout <<"The  entered alphabet is a vowel";
             break;
case 'o':
            cout <<"The  entered alphabet is a vowel";
             break;
case 'i':
            cout <<"The  entered alphabet is a vowel";
             break;
case 'u':
            cout <<"The  entered alphabet is a vowel";
             break;
           
            default:
                        cout <<"aplhabet is consonant";
}
           
return 0;
}


Task # 5: Code file name lab5_5.cpp
Write a program to ask user to enter an operator (either +, -, * or /) and then two floating point numbers. Then based on which operator is entered by the user, output the result of the operation. Use switch-case.
If the user enters some other char, the program outputs an error message and quits.
#include <iostream>
using namespace std;
int main ()
{
char ch;
int n,m;
cout<<"enter an operator :";
cin>>ch;
cout <<"Enter 1st number:";
            cin>> n;
            cout <<"Enter 2nd number:";
            cin>> m;
            switch (ch)
{
case '+':
            cout <<n+m<<endl;
     break;
case '-':
            cout <<n-m<<endl;
             break;
case '*':
            cout <<n*m<<endl;
             break;
case '/':
            cout <<n/m<<endl;
             break;
           
            default:
                        cout <<"wrong input";
}
return 0 ;
}



Task # 6: Code file name lab5_6.cpp
Write a program that inputs value of y. If y is greater than 5 then 4 will be assigned to another variable x or else the value 8 will be assigned to x.(Use ternary operator)

#include <iostream>
using namespace std;
int main ()
{
            int y,x;
            cout <<"Enter any number :";
            cin>> y;
            if( y>5 )
{
            x=4;
            cout <<"as y>5 Then x=4";
           
}
else
{
            x=8;
            cout <<" as y<5Then x=8";
           
}
return 0;
}



No comments:

Post a Comment

Functions & BASIC FILE I/O

A.    Files : For storage of data for later use, files are used. Files are stored on the Hard Disk Drive (HDD). There are two types of f...