7

C++ Programming Basics and Control Loops

LEARNING OBJECTIVES

At the end of this chapter, you should be able to

  • Write C++ programs with good grasp and understanding.

  • Understand data types and their usage.

  • Understand operators and their precedence and association rules.

  • Understand and use control loops.

7.1 Introduction

In this chapter, we introduce you to rich C++. We analyse the data types permitted by C++ language, together with various operators like logical operators and arithmetic operators. In Chapter 1, you have of course used these features, but in this chapter we will provide you with the underlying syntax and grammar of C++. We have shown the workings of various types of operators such as binary operators and unary operators and bitwise operators with sample programs. The precedence and association of operators are also presented.

7.2 Declaration of Variables

In C++ language, all variables must be declared before they are used. However, C++ gives a luxury of declaring just before you use them. A variable can consist of alphabets and digits. Either upper- and lowercase or mixtures of both cases are allowed. A variable cannot start with a digit. It can start with an _. The allowable characters in C++ language are alphabets A to Z, a to z, numbers 0–9 and the following special characters:

 

image

 

Tokens: A token is an atomic word that is recognized by the compiler and that cannot be broken further. It can be a single character or a group of characters that can be recognized by a C++ compiler.

Examples: Key words, Identifiers, Literals, Punctuations and Operators.

Keywords: Reserved and have special meaning in C++ language. A few of the important and commonly used keywords are:

 

image

 

  • Identifiers: Identifiers are names given to variables, function names, structure names, and so on. The valid variables are: basic_pay, hra, FindArea( ), d2000k, _std. The invalid variables and the reasons are:

    2found            cannot start with a digit

    basic-pay     illegal character

    My.pay            illegal character

    Your Age           blank space

  • Literals: They are also called literal constants. They do not change their value during running of the C++ program. C++ allows following literal constants. Integer constants, floating point constants, character constants, string literals, enumeration constants, and symbolic constants.

a) Integer Constants:

They can be subdivided into

Decimal integer constants: 0 10 −745 999

  • Unsigned integer constants can be specified by appending the letter U at the end. For example, 55556U or 55556u.
  • Long integer constants can be specified by appending the letter l s at the end. For example, 789654234L or 7896s.

Octal integer constants:

  • Only digits between 0 and 7 are allowed. All Octal numbers must start with 0 digit to identify as octal number.
  • Allowed octal constants: 0777, 001, 0117, 07565L (octal long)
  • Illegal octal constants are: 089 – 8 is illegal, 777 – does not start with 0
    : −0675.76              −. is illegal

Hexadecimal constants:

  • A hexadecimal number must start with 0x or 0X followed by digits 0 to 9 or alphabets a to f; both uppercase or lowercase are allowed.
  • Allowed hexadecimal constants are: 0xffff, 0xa11f, 0x65000UL.
  • Illegal hexadecimal constants are: 0x14.55, illegal character “.”

b) Floating point constants:

They are base −10 number that can be represented either in exponent form or decimal point representation.

Valid floating point constants are:

−0.01, 789.89765, 5E−5, 1.768E+9

Invalid floating point declarations are:

– 6 invalid . must contain exponent or float point.

– 5E+12.5 Invalid as exponent cannot be float.

– 6,789.00 Invalid character “,”

 

c) Character constants:

Character constants can be declared based on the character set followed in a computer. ANSI has standardized these values as shown below:

 

image

 

A character constant contains a single character enclosed within a pair of single quote marks. Examples of character constants are:

 

‘5’ ‘X’ ‘;’ ‘ ‘

 

Note that the character constant ‘5’ is not the same as the number 5. The last constant is a blank space. Character constants have integer values known as ASCII values. For example, the statement: cout<<’a’; would print number 97, the ASCII value of letter a. Since each character constant represents an integer value, it is also possible to perform arithmetic operations on character constants.

Special characters that cannot be printed normally, double quote (“) apostrophe (‘), question mark (?), backslash (), etc. can be represented by using escape sequences. An escape sequence always starts with followed by special character stated above. Table 7.1 provides details of escape sequences and special effects.

 

Table 7.1 Escape sequences and its special effects

Special Character Escape Sequence
Bell a
Back space b
Horizontal tab t
Vertical tab v
Form Feed f
New line n
Carriage return r
Double Quote
Apostrophe/Single Quote
Backslash \
Null 0
Octal number On
Hexadecimal number cHn

 

d) String constants:

String constants can contain any number of characters in sequence, but enclosed in double quotation marks.

 

“new delhi”, “14 Nov 1954”, an empty string is “”.

 

Please note that NULL character indicates NULL character and is used by C++ language to indicate the end of a string.

e) Enumeration constants:

Enumeration is a user-defined data type and its members are constants. It can be used effectively to associate integer values to variables. The syntax and example are shown below:

Syntax storage class enum variable { var1, var2, var3 ……..};

Examples are: enum bool { FALSE,TRUE};
         enum colors { RED,BLUE,GREEN};
         enum waitque { P0 , P1,P2=5,P6};

Then integer values assigned with above enum declarations are

              FALSE=0 TRUE=1
              RED=0, BLUE=1, GREEN=2
              PO=0,P1=1,P2=5,P6=6 and so on

We can create instances of enum variable and assign data as shown below:

         color color1,color2;
         color1=2; // means color1 will be GREEN

In C++ language, enumeration is a list of constant integer values. This enumeration type of declaration is useful when we want to assign constant integer values to names, for example, 0 and 1 to a variable. Consider the example shown below:

  enum bool { no, yes} ; no has a value 0 and yes has a value=1
  enum month {jan, feb, mar, apr};
  enum color { red , yellow=3 , green }; // red=0 , yellow=3 and green=4

f) Symbolic Constants:

A symbolic name substitutes a sequence of characters or numerical value that follows it:

             # define PI 3.14159
             # define MAX 50
             # define NAME thunder

Note that there is no semicolon at the end of the statement.

7.3 Data Types

What is a data type? Simply put, it defines a range of permitted values and operations that can be performed on the data type. Data types, also called intrinsic data types, supported by C++ language are shown in Figure 7.1. The ranges allowed for a 32 bit IBM PC and memory requirements are highlighted in Table 7.2.

 

Data type supported by C++ language

 

Figure 7.1 Data type supported by C++ language

 

Table 7.2 Ranges allowed for various data types for a PC

 

image

 

Data types can also be distinguished as

  1. Intrinsic or basic data types like int, char, float, double, etc. Intrinsic or basic data types are those that do not contain any other data type.
  2. Derived data types: array, pointer, etc.
  3. User-defined data types: Structure, Unions, etc.

Derived data types are: Arrays, functions, pointers, reference and constant.

User-defined data types are: Class, structure, union and enumeration.

The smallest, individually addressable memory unit is byte. A byte is 8 bits. From Table 2.1, observe that both short int and int have the same memory requirements of 2 bytes. Similarly, an unsigned int will have the same requirements of int. For an ordinary int, leftmost bit is reserved for sign bit. Therefore, balance bits are only 15 and hence range is only 2 ^ 15, i.e. 32767. Whereas unsigned int complete 16 bits ( 2 bytes ), i.e. a range of 2 ^ 16 = 65,535 are possible. Hence, unsigned int will have double the range of ordinary int.

A word about data type called void. It must be clearly understood that void is a data type. It is not “nothing” or NIL or NULL or 0. We can draw an analogy here for better understanding the concept of void. When dealing with gravitational force, g = 9.8 mt/sec 2 is a state. Similarly, g = 0 or –9 is also a state. Void is a data type which does not belong to any other data types, but is a data type of type void.

7.4 Declaration and Assignment Values to Variables

Declaration means mapping the association between the variables and data types. Following are valid declarations:

  int x , y , z;
  float radius=2.56 . //This is declaration and also assignment of value to the variable. We can also call this activity as definition.
  float radius[25] ; // declaration of array of data type float with size 25
  double root1=0.3123e-10; // we have used exponent form. 0.3123*10^10
  short x , y=0 , z; // you can declare variables as short or short int
  short int x , y=0 ,z; // Similarly long int can be declared as long int or long
  char text[] = “New Delhi”; // The string contains 9 characters. It will be stored
  in an array as shown below. Note that we have left blank for size of the array.

You could also declare specifying the size, but size to be correctly specified,

  taking care of null character as char text[10] = “New Delhi”
  name of the array : text : N e w D e l h i 
  Subscript value : 0 1 2 3 4 5 6 7 8 9
  text[0] contains character N
  text[9] contains null character()

7.5 Expressions

An expression can comprise any one of the following:

  1. A single character or a number.
  2. A single constant or a variable.
  3. A combination of variables or constants, interconnected by operators.
  4. A logical condition that is true (value 1) and false (value 0).

Examples of expressions are:

  root1=(-b+sqrt(d))/(2*a); x=y; ++i; x==y; x=oyez;

7.6 Operators

7.6.1 IO Operators << and >> , iostream objects cin and cout

Output operator << directs output stream to standard output device, i.e. display. It is tied to iostream object called cout. Similarly, input operator >> gets input from standard input device, i.e. keyboard and tied to iostream object called cin.

  Ex: cout<<”
 Enter values of num1 and num2 :”;
  cin>>num1>>num2;
  cout<<”
 The sum of two numbers = “<<num1+num2<<endl;
  Output : The sum of two numbers = sum of num1 and num2

7.6.2 Unary Operators

In unary operator, operator precedes a single operand. Unary operators are: - , ++ , -- . sizeof. Examples are :

   - 4.0 , -5*(A+B)
   ++ i , i++ , --i , i−

++, -- operators are called increment and decrement operators. If they precede the operand, then first the variable is incremented, then the operation is performed. If they follow the operand, then the operation is performed first, and the variable is incremented.

 

Example 7.1:    Operator1.cpp to Demonstrate Pre- and Postincrement Operators

int count = 1;
cout<<count; // output will be 1
cout<<++count;
/* count will be incremented by one and then operation of
print is performed. Output will be 2. Now, if you use*/
cout<<count++;
/* count will be printed first. Output is 2. Then count will
be incremented by 1 to 3.*/
cout<<count; // output will be 3.

7.6.3 Size of Operator

Will be useful for determining the size allocated for a data type by the computer.

char city[]=”New Delhi”;

 

Example 7.2:    Operator1.cpp to Demonstrate Sizeof Operators

cout<<”
Size of integer: ”<< sizeof(int));
cout<<”
Size of float :” << sizeof(float));
cout<<”
Number of characters in String constant city :” << sizeof city ;
Output of above statements would be
Size of integer : 2
Size of float : 4
Number of characters in String constant city:9

 

Example 7.3:    quadroots.cpp to Obtain Roots of Quadratic Expression

/*Example 7.3 quadroots.cpp A program to compute roots of a quadratic equation.
In this example observe, declaration, assignment, expressions, math function
This program finds the roots of a quadratic equation. Formula to compute the roots are (-b+sqrt(b*b-4*a*c))/(2*a) and (-b-sqrt(b*b-4*a*c))/(2*a)*/
  1. #include<iostream>
  2. using namespace std;
  3. #include<math.h> // for square root function. h stands for header file
  4. // function prototype
  5. void FindRoot(float a , float b , float c);
  6. void main()
  7. { // declare three variables as double precision numbers
  8. double a,b,c;
  9. // obtain the coefficients
  10. cout<<”
enter coefficiants of x^2 , x , and constant:”;
  11. cin>>a>>b>>c;
  12. // Call FindRoot function. We are sending a , b , c values as arguments
  13. FindRoot(a,b,c);
  14. }// end of main
  15. // function definition
  16. void FindRoot(float a,float b,float c)
  17. { double d,root1,root2;
  18. d = ((b*b)-(4*a*c));
  19. if(d>=0)
  20. {      cout<<”
 roots are real
”;
  21.        root1=(-b+sqrt(d))/(2*a);
  22.        root2=(-b-sqrt(d))/(2*a);
  23.        cout<<”
 root1=”<<root1<<endl;
  24.        cout<<”
 root2=”<<root2<<endl;
  25. }
  26. else
  27. {      cout<<”
 roots are imaginary
”;
  28.        cout<<”
root1=”<<-b/(2*a)<<sqrt(-d)/(2*a)<<endl;
  29.        cout<<”
root2=”<<-b/(2*a)<<sqrt(-d)/(2*a)<<endl;
  30. }
  31. }// end of function call
      /*Output:
      Enter coefficiants of x^2 , x , and constant:1 -3 2
      roots are real
      root1=2
      root2=1 */

7.6.4 Arithmetic Operators

The basic (also known as intrinsic) operators are

     + addition       − subtraction   * multiplication
   / division         % modulus ( remainder after division).

It may be noted that C++ language does not support exponentiation. Although we will use ^ symbol to denote exponentiation in expression, we have to use a library function call pow to calculate the exponentiation.

Type conversion: If the variable involved in an operation are of different type, then type conversion is carried out before the operation.

If the operation is between a float and double, the float will be converted to double and the result will result in double.

If the operation is between a float or double or long double and a char or int, then char or int will be converted to float or double or long double and the result will result in float or double or long double.

If the operation is between a int and long int, the int will be converted to long int and the result will result in long int.

If the operands are not float or long int, they will be converted to int.

Type Cast: Suppose, we want to declare the result in particular data type, we can type cast as shown below:

  int a , b;
  float x;
  x=(float)a/b; // a/b is integer division and the result is converted to float.

7.6.5 Relational and Logical Operators

The relational operators are: > >=< and <=.

These four relational operators have the same precedence. However, they have lower priority than arithmetic operators. The two more operators, known as equality operators = = and ! = have priority just below relational operators.

7.6.6 Logical Operators

These are && and ||. Evaluation of expressions connected by logical operators are done from left to right and evaluation stops when either truth or false hood is established. In the statement shown below:

  while ( (iflag==0) && ( text[i]!=’E’) )

first iflag == 0 is evaluated, if it is true, then only the second expression text[i]=!E is evaluated. In other words, evaluation stops as soon as truth or false is established.

7.6.7 Conditional Expressions: Question Mark Operator

Suppose you want to allot 10 additional bonus marks to students who put in 100 percent attendance and all others an additional 2 marks. This would result in statements like

   If ( attendance > 100)
   marks += 10; // this is a compound statement. It means 
   Marks=Marks +10
   Else
   marks +=2;

C++ language gives you facility of conditional operator, using which the above 4 lines can be coded as a single line:

  marks = (attendance > 100) ? marks + 10 : marks + 2;

The syntax is : z=exp1 ? expr 2 : exp3. Exp1 is evaluated first. If it is true, z is equated to the result of exp2 . Else z is equated to exp3.

 

Example 7.4:    Largest.pp to Find Greatest Number Using Conditional Operator

/*Example 7.4 Largest.pp to find largest of three numbers using ternery operator*/
  1. #include<iostream>
  2. using namespace std;
  3. void main()
  4. { int n1,n2,n3,max;
  5.   cout<<”Enter three numbers:”<<endl;
  6.   cin>>n1>>n2>>n3;
  7.   max=n1>n2?(n1>n3?n1:n3):(n2>n3?n2:n3);
  8.   cout<<”Greatest number is “<<max;
  9. }
     /* Output: Enter three numbers:
     67 54 98
     Greatest number is 98*/

Line No. 7:


         max=n1>n2?(n1>n3?n1:n3):(n2>n3?n2:n3);
         Firstly n1>n2 is evaluated.
           If n1>n2
            max=(n1>n3?n1:n3). If n1>n3 returns n1 else n3
           Else
           max=(n2>n3?n2:n3); If n2>n3 returns n2 else n3

7.6.8 Comma Operator

This operator is used to string together several expressions. For example, consider an expression x = ( y = 5 , y+1). The expression is evaluated from left to right.

  Firstly, y=5 hence x=5, then x=y+1, i.e. 6.
  For loop for ( int i=0, int z=1; i<=100; i++ ), two statements are initialized.

7.6.9 Bitwise Operators

Bitwise operators available in C language are

&  Bitwise AND . Used for masking operation. For example, if you want to mask the first four bits of a number ‘n’, then we will mask n with a number whose last four bits are 1s, i.e. 0001111. In Octal representation, it is 017. (Remember an octal number starts with 0 and a hexa number starts with 0x.)
          n= 1 0 0 1 0 1 0 1 = 149(decimal)
          & 0 0 0 0 1 1 1 1 = 017(octal)
          result n = 0 0 0 0 0 1 1 1
Note that the last four bits are 0101 and are unaffected, i.e. they are just reproduced in the result, whereas the left four bits are all 0s, i.e. they are masked.
Bitwise OR. This operator is used when you want to set a bit. For example, we want to set 0th and 2nd bit to 1 for n = 144, then we will use | operator with n and as shown below:
          n = 1 0 0 1 0 0 0 0 = 144(decimal)
          | = 0 0 0 0 0 1 0 1 = 005(octal)
          result n = 1 0 0 1 0 1 0 1 = 149(decimal)
^  Bitwise Exclusive OR. Exclusive OR also known as odd function, produces output 1, when both bits are not the same (odd) and produces a 0 when both bits are the same.
          n = 1 0 0 1 0 1 0 1 = 149(decimal)
          ^ = 0 0 0 0 0 1 0 1 = 005(octal)
          result n = 1 0 0 1 0 0 0 0 = 149(decimal)
  << Left Shift. Shifting left by one position, bits of a binary number is equal to multiplying the number with 2.
          n = 1 0 0 1 0 0 0 0 = 144(decimal)
          n<<1 1 0 0 1 0 0 0 0 0 = 288(decimal)
          n<<2 1 0 0 1 0 0 0 0 0 0 = 576
  >> Right Shift. Shifting right by one position, bits of a binary number is equal to division of the given number with 2.
          n = 1 0 0 1 0 0 0 0 = 144(decimal)
          n>> 0 1 0 0 1 0 0 0 = 72(decimal)
          n>>2 0 0 1 0 0 1 0 0 = 36(decimal)
 ~  Tilde operator. one's complement operator. This is a unary operator, used to find one's complement of a given number.
          n = 1  0 0 1 0 1 0 1 = 149(decimal)
          ~n = 0 1 1 0 1 0 1 0 = bitwise complement

 

Example 7.5:    bitwise.cpp to Demonstrate the Working of Bitwise Operators

  1.  #include<iostream>
  2.  using namespace std;
  3.  int main()
  4.  { int n = 149;
  5.  int res;
  6.  res = n & 0017;
  7.  cout<<”The resultant of Bitwise AND operator is “<<res<<endl;;
  8.  res = n | 0017;
  9.  cout<<”The resultant of Bitwise OR operator is “<<res<<endl;;
  10. res = n && 0017; // this is logical AND. Truth or false will be output
  11. cout<<”The resultant of Logical AND operator is “<<res<<endl; ;
  12. res = n || 0017; // this is logical OR . Truth or false will be output
  13. cout<<”The resultant of Logical OR operator is “<<res<<endl;;
  14. res = n ^ 0017;
  15. cout<<”The resultant of Exclusive operator is “<<res<<endl;;
  16. res = n <<2;
  17. cout<<”The resultant of shift left ( by 2 bits) operator is “<<res<<endl;;
  18. res = n >>2;
  19. cout<<”The resultant of shift right ( by 2 bits) operator is “<<res<<endl;;
  20. res = ~n;
  21. cout<<”The resultant of NOT operator is “<<res<<endl;
  22. return 0;
  23. }
      /*Output : The resultant of Bitwise AND operator is 5
      The resultant of Bitwise OR operator is 159
      The resultant of Logical AND operator is 1
      The resultant of Logical OR operator is 1
      The resultant of Exclusive operator is 154
      The resultant of shift left (by 2 bits) operator is 596
      The resultant of shift right (by 2 bits) operator is 37
      The resultant of NOT operator is –150*/

7.7 Precedence and Association of Operators

The precedence and association of operators are shown in Table 7.3. The operators at the top have priority more than those that appear later in the table, i.e. operators’ priority is highest at the top of the table and lowest at the bottom of the table. Operators on the same line have the same priority.

 

Table 7.3 Precedence and association rules for the operators

Operator Association
Function call ( ) , [ ] ,-> . Left to right
! ~ ++ -- + - * & sizeof Right to left
* / % Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
= = != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= ^= != <<= >>= Right to left
, Left to right
  • * / and % have all the same priority
  • Unary operators like +, – and * have more priority than binary operators

7.8 Control Loops

An algorithm or a procedure is a sequence of logical steps. Control statements change the sequence of execution of statements as per the requirement of logic. We have already used while for loop and if statements. We will now formalize and consolidate our understanding of control loops.

C++ is a block-oriented language. The program consists of statements. Statements are logically grouped into blocks. Blocks are enclosed in brace brackets. { and } are used to denote start and end of the block in C++. All variables declared inside the controlling braces are called local to the block. This means the value the variable holds is available only inside the block. Statements inside the block are also called compound statements.

Note that there will be no semicolon after the closing brace bracket. For example, in function definition we have enclosed all the statements in brace brackets.

7.8.1 Conditional and Branching Statements

7.8.1.1 If Statement

The syntax is simple and straightforward

                      if (expression)
                      statement;

7.8.1.2 If–Else Statement

The syntax is
                      if (expression)
                        {
                      statements;
                        }
                      else
                        {
                      statements;
                        }
Else statement is optional. But if used it will be associated with the nearest if statement. In the example shown, else is attached to innermost if.
        if ( totalMarks > 60)
        if ( total Marks > 70)
           cout<<“passed with distinction”<<endl;
        else
           cout<<“passed with first class”<<endl;
Use of brace brackets dictate the association rule for else statements. Else in the following code is linked up with first if statement:
        if ( totalMarks > 60)
          { if ( total Marks > 70)
           { cout<<“passed with distinction”<<endl;
          }

 

Control flow in if statement

 

Figure 7.2 Control flow in if statement

 

Flow in if–else statement

 

Figure 7.3 Flow in if–else statement

 

            else // associated with inner if
          { cout<<“passed with first class”<<endl;
          }
        }
        else // associated with outer if
        { …else block……….}

 

Example 7.6:    FindMax.cpp to Find the Maximum of Two Numbers

// Example 7.6: Findmax.cpp to find maximum of two numbers
  1.  #include <iostream>
  2.  #include<conio.h>
  3.  using namespace std;
  4.  long int FindMax (long int a, long int b);
  5.  void main ()
  6.  { long int int i=150, j=170, k;
  7.    long int x=715000, y=918000, z;
  8.    k=FindMax(i,j);
  9.    z=FindMax(x,y);
  10.   cout << “
 Larger of the two integers : “<<i<<” & “<<j<<” : “<< k << endl;
  11.   cout << “
 Larger of the two long integers : “<<x<<” & “<<y<<” : “<< z << endl;
  12.   getch();
  13. }
  14. //fn definition
  15.   long int FindMax (long int a, long int b)
  16.   {
  17.   long int max;
  18.   //max = (a>b)? a : b;
  19.   if ( a>b)
  20.   max=a;
  21.   else
  22.   max=b;
  23.   //max = (a>b)? a : b;
  24.   return (max);
  25. }
     /*Output: Larger of the two integers : 150 & 170 : 170
     Larger of the two long integers : 715000 & 918000 : 918000*/
Lines No. 14–24 are for function definition. Lines No. 19–20 depict usage of if. Lines No. 21–22 show else statement. Line No. 23 is commented out and uses question mark operator to achieve the same result but with elegance.

Note that we have included conio.h for console in and out library. This would facilitate the use of console functions like clear screen (clrscr()) and getch() for get character operation. Use of getchar() would make computer wait for input through console. It will proceed further only when it receives the input. This feature can be used to observe the result on console. Linux-based compilers like gnu C++ do not support conio.h.

7.8.1.3 Nested if

When an if statement has another if statement in its body or in the body os else statement we would call it as nested if statement.

 

Example 7.7:    calcif.cpp to Simulate Simple Calculator with +, -, *, / Operators Using Nested Ifs

/* Example 7.7 program to simulate the calculator using if-else ladder?*/
  1.  #include<iostream>
  2.  #include<conio.h>
  3.  using namespace std;
  4.  void main()
  5.  { char ch; // to store operator
  6.  float a,b,result;
  7.  cout<<”Enter any two numbers : “;
  8.  cin>>a>>b;
  9.  cout<<”
Enter the operation( + , - , * , / ) :”;
  10. cin>>ch;
  11. cout<<endl;
  12. if(ch==’+’)
  13.  result=a+b;
  14. else
  15.  if(ch==’-’)
  16.  result=a-b;
  17.  else
  18.  if(ch==’*’)
  19.  result=a*b;
  20.  else
  21.  if(ch==’/’)
  22.  result=a/b;
  23.  else
  24.  cout<<endl<<”wrong operator”;
  25. cout<<”
The result of “ << a << ch << b <<” = “<<result;
  26. }
     /*Output: Enter any two numbers : 21 18
      Enter the operation( + , - , * , / ) :/
      The result of 21/18 = 1.16667*/

 

Types of nested if statement

 

Figure 7.4 Types of nested if statement

 

7.8.1.4 If–Else–If Ladder

Lines No. 12 to 24 depict the if–else–if ladder. It is called ladder because it looks like a ladder. Observe the indentation. Its deep indent and costs in terms of space. Hence the if–else–if ladder can be replaced by the if–else–if, as shown below:

  if(ch==’+’)
result=a+b;
  else if(ch==’-’)
result=a-b;
  else if(ch==’*’)
result=a*b;
  else if(ch==’/’)
result=a/b;
  else
cout<<endl<<”wrong operator”;
  cout<<”
The result of “ << a << ch << b <<” = “<<result;
  }

7.8.2 Switch and Case Statements

Switch statement evaluates an expression and depending on the numerical value of the evaluation control is branched to corresponding block of statements. The syntax and example problems are shown below:

  switch ( expression)
    case constantexpression1 : statements1
    case constantexpression2 ; staements2
    default statements

 

Example 7.8:    calcswitch.cpp to Simulate Simple Calculator with +, -, *, / Operators Using Switch

// Example 7.8 program to show the usage of switch and case
  1.  #include<iostream>
  2.  #include<conio.h>
  3.  using namespace std;
  4.  void main()
  5.  {int choice;
  6.  int num1,num2;
  7.  cout<<“1.Addition”<<endl;
  8.  cout<<“2.Substraction”<<endl;
  9.  cout<<“3.Multiplication”<<endl;
  10. cout<<“4.Division”<<endl;
  11. cout<<“5.Quit”<<endl;
  12. do
  13. { cout<<“
Enter your choice: ”;
  14.   cin>>choice;
  15.   switch(choice)
  16.   {
  17.   case 1:cout<<“
Enter <num 1& num2>: ”;
  18.   cin>>num1>>num2;
  19.   cout<<“num1+num2=”<<num1+num2<<endl;
  20.   break;
  21.   case 2:cout<<“
Enter <num 1& num2>: ”;
  22.   cin>>num1>>num2;
  23.   cout<<“num1-num2=”<<num1-num2<<endl;
  24.   break;
  25.   case 3:cout<<“
Enter <num 1& num2>: ”;
  26.   cin>>num1>>num2;
  27.   cout<<“num1*num2=”<<num1*num2<<endl;
  28.   break;
  29.   case 4:cout<<“
Enter <num 1& num2>: ”;
  30.   cin>>num1>>num2;
  31.   cout<<”num1/num2=”<<(float)num1/num2<<endl;
  32.   break;
  33.   case 5:cout<<“exiting from program“<<endl;
  34.   exit(0);
  35.   default: cout<<“Invalid choice<enter no between 1 and 5 only>“<<endl;
  36.   } // end of switch
  37. }while(choice!=5);
  38. }//end of main
    /*Output
    1.Addition
    2.Subtraction
    3.Multiplication
    4.Division
    5.Quit
    Enter your choice: 3
    Enter <num 1& num2>: 65 2
     num1*num2=130
    Enter your choice: 1
    Enter <num 1& num2>: 65 2
     num1+num2=67
    Enter your choice: 2
    Enter <num 1& num2>: 65 2
     num1-num2=63
    Enter your choice: 4
    Enter <num 1& num2>: 65 2
     num1/num2=32.5
    Enter your choice: 5
     exiting from program*/

Note that switch statement directs flow to the block of statements depending on the integer constant choice. Further it is necessary to separate blocks in a switch statement through break statement. A break statement, simply put, breaks the nearest brace bracket block, in this case being switch block brace brackets. Also note that the while loop continues till you enter choice of 5. It exits the program through exit(0) statement.

7.8.3 While Loop

The while loop is written by a programmer if he is not sure if the while block will be executed. A condition is checked first. If it is true, the while block is executed. Control flow for the while loop in shown in Figure 7.5. The syntax of the while statement is

 

Control flow for while and for ops

 

Figure 7.5 Control flow for while and for ops

 

   While (expression)//body of while contains a single line no brace brackets required Statement;
   While(expression)
   { statement1;
     statement2;
 }
   while(1) // expression is always true
   { block of statements;
   } // the loop is called forever while loop

 

Example 7.9:    heater.cpp to Use While Loop to Turn off the Heater if Upper Cutoff Temperature has Reached

The algorithm is: Read the temperature. While temperature < upper cut off Switch on the heater Else Switch off the heater //Heater.cpp

 

  1.  #include<iostream>
  2.  #include<conio.h> // console input /output for getch() and clrscr()
  3.  using namespace std;
  4.  const int MAX=60;
  5.  void main()
  6.  { float temp ;
  7.    cout<<”Enter <temperature of the heater> :”;
  8.    cin>>temp;
  9.    while (temp<MAX)
  10.   cout<<”
 Temperature is lukewarm. Switch on heater”<<endl;
  11. cout<<”
Water is hot. Switch off the heater” <<endl;
  12. } // end of main
     /*Output :Enter <temperature of the heater> :67
     Water is hot. Switch off the heater *//*
Line No. 4: declares Max as integer data type and it does not change its value during its run-time.

 

Example 7.10:    sumwhile.cpp //Program to Find Sum of n Numbers and their Average Using

// Example 7.10 sumwhile.cpp.
  1.  #include<iostream>
  2.  #include<conio.h>// console input /output for getch() and clrscr()
  3.  using namespace std;
  4.  void main()
  5.  { int n;
  6.  int num ,sum = 0, avg=0,count =1;
  7.  // input N
  8.  cout<<”
 Enter value of <N>:”;
  9.  cin>>n;
  10. // control loop
  11. while (count <= n )
  12. {      cout<<”
 Enter value of “<<count<<”number”;
  13. cin>>num;
  14. sum+=num;
  15. count++;
  16. }//end of
  17. avg=sum/n;
  18. cout<<”
 Sum of” <<n<<”numbers =”<<sum<<endl;
  19. cout<<”
 Average of”<<n<<”numbers =”<<avg<<endl;
  20. getch();
  21. } // end of main
     /*Output: Enter value of <N>:3
     Enter value of 1number34
     Enter value of 2number56
     Enter value of 3number87
     Sum of 3numbers =177
     Average of 3numbers =59*/

7.8.4 Do-while Loop

The syntax is
  Do
{
  block of statements
} while (expression);

The block is executed first and the condition is checked. If true, the loop is executed till the condition becomes true. We will use do-while loop when we know that the loop needs to be executed at least once, whereas while loop is used when we are not aware if loop needs to be executed or not. The control flow is shown in Figure 7.6.

 

Control flow for do-while loop

 

Figure 7.6 Control flow for do-while loop

 

 

Example 7.11:    sumwhile.cpp //Program to Find Sum of n Numbers and their Average Using Do-while Loop

  1.  #include<iostream>
  2.  #include<conio.h>// console input/output for getch() and clrscr()
  3.  using namespace std;
  4.  void main()
  5. {  int n;
  6.   int num ,sum = 0, avg=0,count =1;
  7.   // input N
  8.   cout<<”
 Enter value of <N>:”;
  9.   cin>>n;
  10.  // control loop
  11.  do
  12.  {  cout<<”
 Enter value of “<<count<<”number”;
  13.  cin>>num;
  14.  sum+=num;
  15.  count++;
  16.  }while (count <= n ); //end of do while. Observe semicolon
  17.  avg=sum/n;
  18.  cout<<”
 Sum of” <<n<<”numbers =”<<sum<<endl;
  19.  cout<<”
 Average of”<<n<<”numbers =”<<avg<<endl;
  20.} // end of main
     /*output: Enter value of <N>:3
     Enter value of 1number45
     Enter value of 2number76
     Enter value of 3number78
     Sum of 3numbers =199
     Average of 3numbers =66*/

7.8.5 For Loop

For loop, as control loop is used, when we know the exact number of times the loop needs to be executed. The syntax of for loop is

for ( exp1 ; exp2 ; exp3)
  {
block of statements
  }
  where exp1 is initialization block
    exp2 is condition test block
    exp3 is alter initial value assigned to exp1
  Forever for loop is shown below:
    for ( ; ; )
  {
    statement;
  }

for loops can be nested. This means that we can write for loop within a for loop. In nested for loop, the inner loop is executed for each value of the outer loop. For example, inner loop is executed for i=0 and the value of j is varied from 0 final condition. Outer loop is executed for values of i varying from 0 to n – 1.

The syntax is
 for ( int i=0;i<n;i++)
  {
   for (int j=0;j<n;j++)
 {
   statement
 }
 }

 

Example 7.12:    sumfor.cpp //Program to Find Sum of n Numbers and their Average Using for Loop

#include<iostream>
#include<conio.h>// console input /output for getch() and clrscr()
using namespace std;
void main()
   { int n;
   int num ,sum = 0, avg=0,count;
   // input N
   cout<<”
 Enter value of <N>:”;
   cin>>n;
   // control loop
   for(count=1; count<=n ; count++)
   {cout<<”
 Enter value of “<<count<<”number”;
cin>>num;
sum+=num;
   avg=sum/n;
   cout<<”
 Sum of” <<n<<”numbers =”<<sum<<endl;
   cout<<”
 Average of”<<n<<”numbers =”<<avg<<endl;
   getch();
} // end of main
/*Output: Enter value of <N>:3
  Enter value of 1number67
  Enter value of 2number76
  Enter value of 3number87
  Sum of 3numbers =230
  Average of 3numbers =76*/

 

Example 7.13:    nestedfor.cpp A Program to Demonstrate Nested for Loop

#include<iostream>
#include<conio.h>// console input /output for getch() and clrscr()
using namespace std;
void main()
{ int i , j ; // counters for outer and inner for loop
for (i=15; i<16; i++) // outer loop
{
   cout<<”
 Multiplication table for “<< i<<” X “<<20<<endl;
   for (j=15; j<20 ; j++) // inner loop
         {
         cout<<endl<<i<<” X “<<j<<” = “<< i*j;
         } // end of inner for loop
   } // end of outer for loop
  } // end of main
/*Output : Multiplication table for 15 X 20
15 X 15 = 225
15 X 16 = 240
15 X 17 = 255
15 X 18 = 270
15 X 19 = 285 */

7.8.6 When to Use For or While or Do-while

For loop is best suited when programmers have exact knowledge of initialization and final conditions to be met.

    for ( exp1 ; exp2 ; exp3)
  {
   block of statements
  }
where exp1 is initialization block
  exp2 is condition test block
  exp3 is alter initial value assigned to exp1

The above for loop is equivalent to the following while loop. While loop is used when the programmer does not know if at all the while block will be executed. In other words, in a situation where we have to check a condition and then only execute block, we will use while loop.

exp1;
  while(exp2)
  {      statement;
  exp2;
  }

Do-while loop, on the other hand, is used when we know that the block is to be executed at least once. In other words, we have to execute the block and then check for a condition.

7.9 Break and Continue

7.9.1 Break

Break statement is used to exit from the switch control or control loop. We can use break statement to exit from for, while and do-while, and switch control statements. You have already seen the use of break statements in Switch statement. Observe how break is used to come out of if statement below:

 

Example 7.14:    break.cpp Program that Demonstrates Break Statement

#include<iostream>
#include<conio.h>// console input /output for getch() and clrscr()
using namespace std;
void main()
{
  int count=0;
  int sum,num;
  for ( ;;) // for ever for loop
  { if(count == 5)
   { cout<<”
 reached upper limit of 5: breaking the for loop”;
         break;
   }
   else
   {
         cout<<”
 Enter value of “ <<count+1<< “ number :”;
         cin>>num;
         sum+=num;
         count++;
   }
  } // end of for
} // end of main
/*Output
  Enter value of 1 number :89
  Enter value of 2 number :90
  Enter value of 3 number :91
  Enter value of 4 number :92
  Enter value of 5 number :93
  reached upper limit of 5: breaking the for loop*/

7.9.2 Continue Statement

Continue is used when we want to stop further processing of loop statements and start at the beginning of the control loop. In the example shown below, we would like to add 10 points to all odd numbers between 0 to 10 and skip adding to even numbers.

 

Example 7.15:    continue.c.cpp Program that Demonstrates Continue Statement

#include<iostream>
#include<conio.h>// console input /output for getch() and clrscr()
using namespace std;
void main()
 { int count;
 for ( count=0;count<=10;count++)
 { if( (count %2)== 0) // the number is even.
 { cout<<”
 even number: continue at the beginning if for loop: “<<count<<endl;
   continue; //control goes to beginning of for loop
   }//end of if
   else
 {
 cout<<”
 odd number : “<<count<<endl;
   }
 } // end of for
 } // end of main
/*output even number: continue at the beginning if for loop: 0
odd number : 1
even number: continue at the beginning if for loop: 2
odd number : 3
even number: continue at the beginning if for loop: 4
odd number : 5
even number: continue at the beginning if for loop: 6
odd number : 7
even number: continue at the beginning if for loop: 8
odd number : 9
even number: continue at the beginning if for loop: 10*/

7.9.3 Goto Statements

Goto statements are rarely used due to fears that they would lead to unstructured programs. Goto statements can be conditional and unconditional. The syntax is

               goto label // unconditional branch

 

Example 7.16:    goto.cpp to Demonstrate goto Statement

#include<iostream>
#include<conio.h>// console input /output for getch() and clrscr()
using namespace std;
void main()
{ int num ,sum=0,count=0;
  start: cout<<”
 Enter value of <number> number :”;
       cin>>num;
       sum+=num;
       count++;
       cout<<”
 number: “<<num<<endl;
       if ( count > 3)
             goto stop1;
       else
             goto start;
  stop1: cout<<”
 exiting the main program”<<endl;
} // end of main
/*Output
Enter value of <number> number :55
number: 55
Enter value of <number> number :67
number: 67
Enter value of <number> number :54
number: 54
Enter value of <number> number :65
number: 65
exiting the main program*//*

We do not recommend using goto at all. It is always better to get used to while, do-while and for loops for achieving the same result.

7.9.4 Exit Function

You can force a program to stop whatever it is doing and return the control to operating system by using exit() function. For this function you have to include stdlib.h in the include section.

 exit(0); // return after successful completion to operating system(os)
  exit(1); // return to os on being unsuccessful

7.10 Summary

  1. A token is a smallest individual unit in a program.
  2. C++ has three types of integer constants, namely, decimal octal and hexadecimal constants.
  3. Character constants must be enclosed in single quotes. Non-printable character constants are represented by a backslash followed by a character.
  4. String constants. String constants can contain any number of characters in sequence, but enclosed in double quotation marks.
  5. Enumeration is a user-defined data type and its members are constants. It can be used effectively to associate integer values to variables.
  6. Intrinsic or basic data types like int, char, float, double, etc. Intrinsic or basic data types are those that do not contain any other data type.
  7. Derived data types are: Arrays, functions, pointers, references and constants.
  8. User-defined data types are: class, structure, union and enumeration.
  9. Output operator << directs output stream to standard output device, i.e. display. It is tied to iostream object called cout. Similarly, input operator >> gets input from standard input device, i.e. keyboard and tied to iostream object called cin.
  10. Unary operators: In unary operators, operators precede a single operand. Unary operators are: –, ++, --. sizeof.
  11. sizeof operator will be useful for determining the size allocated for a data type by the computer.
  12. Arithmetic operators. The basic (also known as intrinsic) operators are +, –, *, /, %. C++ language does not support exponentiation.
  13. Type conversion: If the variable involved in an operation are of different types, then type conversion is carried out before the operation.
  14. Type cast: When we want to declare the result in a particular data type, we can type cast.
  15. The relational operators are: > >= < and <= . they have lower priority than arithmetic operators. equality operators = = and ! = have priority just below relational operators.
  16. Logical operators: These are && and ||. Evaluation of expressions connected by logical operators are done from left to right and evaluation stops when either truth or falsehood is established.
  17. Conditional expressions: Question mark operator. The syntax is: z = exp1 ? expr 2 : exp3. Exp1 is evaluated first. If it is true, z is equated to the result of exp2. Else z is equated to exp3.
  18. Comma operator: This operator is used to string together several expressions.
  19. Loop is executed once first and the condition is checked. Use do-while loop, when we know that the loop needs to be executed at least once.
  20. For loop, as control loop is used, when we know the exact number of times the loop needs to be executed.
  21. Break. Break statement is used to exit from the switch control or control loop. We can use break statement to exit from for, while and do-while, and switch control statements.
  22. Continue is used when we want to stop further processing of loop statements and start at the beginning of the control loop.
  23. Exit function. You can force a program to stop whatever it is doing and return the control to operating system by using exit() function.

Exercise Questions

Objective Questions

  1. Which of the following statements are true about variables of C++
    1. 0–9 are allowable characters
    2. Variable can start with digit
    3. Variable can start with underscore
    4. ~ tilde is allowable character
    1. i and ii
    2. i, ii and iii
    3. ii, iii and iv
    4. i, iii and iv
  2. Which of the following statements are invalid variables of C++?
    1. My.pay
    2. your city
    3. basic-pay
    4. 2times
    1. i and ii
    2. i, ii and iii
    3. i, ii, iii and iv
    4. i, iii and iv
  3. Which of the following statements are true about data types of C++?
    1. Literals change their values
    2. Identifier can start with underscore
    3. Void is a data type
    4. In C++ 1 means true and 0 means false
    1. i and ii
    2. i, ii and iii
    3. ii, iii and iv
    4. i and iv
  4. Which of the following are legal and allowed in respect integer constants?
    1. Octal constants:089
    2. 0xa22f
    3. 0x14.55
    4. 5E+12.5
    1. i and ii
    2. i, iii and iii
    3. i, ii and iv
    4. i and iv
  5. For modulus operator both operands must be
    1. Float and integer
    2. Float and double
    3. Integers
    4. int & double
  6. What is the output of the following code: int a, b=3; a = b; a+=2; // equivalent to a=a+2
    1. 4
    2. 5
    3. 6
    4. 3
  7. What is the output of following code?
    int a,b,c; a=2; b=7; c = (a>b) ? a : b;
    1. 4
    2. 5
    3. 6
    4. 7
  8. Which of the following are true with respect to IO operators?
    1. >> is called extraction operator
    2. << is tied to cout
    3. cin and cout are objects of iostream
    4. >> can read white spaces
    1. i, ii and iii
    2. i, iii and iv
    3. i, ii and iv
    4. i and iv
  9. Which of the following are true with respect to precedence and association of operators?
    1. + − have left to right association
    2. * / and % have all the same priority
    3. * / % association is from right to left
    4. Unary operators have less priority than binary operators
    1. i and ii
    2. i, iii and iv
    3. i, ii and iv
    4. i and iv
  10. The following control loop is preferred when loop needs to be executed at least once:
    1. While
    2. Do-while
    3. For loop
    4. Switch
  11. The following control loop is preferred when not sure about loop execution:
    1. While
    2. Do-while
    3. For loop
    4. Switch
  12. The following control loop is preferred when initial and final conditions are known:
    1. While
    2. Do-while
    3. For loop
    4. Switch
  13. Break statement takes the control to
    1. Goes out of the innermost loop that contains the break statement
    2. To the beginning of the program
    3. To the end of the program
    4. Goes out from all the nested loop
  14. Continue statement takes the control to
    1. To the bottom of the loop
    2. To the beginning of the loop
    3. To the next statement
    4. To the end of the program
  15. exit() function returns control to operating system.     TRUE/FALSE

    Short-answer Questions

  16. What are the basic data (fundamental, intrinsic) types of C++?
  17. What are the derived data types supported by C++?
  18. What are the user-defined data types supported by C++?
  19. How are enumeration data types useful?
  20. Explain sizeof() operator.
  21. Distinguish & operator and && operator.
  22. Give the syntax of ? operator.
  23. How is comma operator used?

    Long-answer Questions

  24. What are the data types allowed by C++? Explain with examples.
  25. What are IO operators? Explain with examples.
  26. Explain type conversion and type casting of operators.
  27. Explain bitwise operators with examples.
  28. Explain precedence and association of operators.
  29. Distinguish the switch and if else statements.
  30. When do you use for statement and while statements? State the situation when for statements are better than while statements.

    Assignment Questions

  31. Candidates have to score 90 or above in the IQ test to be considered eligible for taking further tests. All the candidates who do not clear the IQ test are sent reject letters and others are sent call letters for further tests. Represent the logic for automating this task.
  32. Write C++ code for following series:
    1. 1+3+5+7 + …………………..+n
    2. 1+x2+x4+x6 +…………….. n terms
    3. (1-x)n = 1 + nx + ((n(n+1)x2)/ 1.2 ) ((n(n+1)(n+2)x2)/ 1.2.3 )
  33. Write a C++ program to display the ascii table.
  34. Write a program to read a line from the keyboard and print the line using a suitable encryption. Simple encryption can be a substitution with next character A with B, a with b, and z with a and so on. De-crypt and display the original message.

Solutions to Objective Questions

  1. d
  2. c
  3. c
  4. b
  5. c
  6. b
  7. d
  8. a
  9. a
  10. b
  11. a
  12. c
  13. a
  14. b
  15. True
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10