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.
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.
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:
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:
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
Octal integer constants:
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:
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:
A character constant contains a single character enclosed within a pair of single quote marks. Examples of character constants are:
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.
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.
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.
Figure 7.1 Data type supported by C++ language
Table 7.2 Ranges allowed for various data types for a PC
Data types can also be distinguished as
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.
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( )
An expression can comprise any one of the following:
Examples of expressions are:
root1=(-b+sqrt(d))/(2*a); x=y; ++i; x==y; x=oyez;
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
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.
Will be useful for determining the size allocated for a data type by the computer.
char city[]=”New Delhi”;
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 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 */
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.
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.
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.
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 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
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.
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*/
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 |
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.
The syntax is simple and straightforward
if (expression)
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;
}
Figure 7.2 Control flow in if 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 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.
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 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*/
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;
}
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 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.
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
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.
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*/
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.
Figure 7.6 Control flow for 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*/
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 */
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.
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*/
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*/
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
#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.
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
int a,b,c; a=2; b=7; c = (a>b) ? a : b;
18.227.79.241