4.3 Variable Declaration and Initialization
4.8 Memory Management Operators
To write a C++program, it is necessary to know the syntaxes of the language. This enables a programmer to write error-free programs. If the programmer is not aware of the basic rules of the language, he/she may fail to write program, even though the logic is clear.
A few basic concepts of C++ language, such as syntaxes, data types, and keywords, are discussed in this chapter to help the programmer to develop programs. As the object-oriented programming is a new technology, the programmer will find a notable amount of new concepts to learn and master in it.
Most of the C++ programs in this chapter are implemented with former C language. Few rules and regulations of C programs are valid in C++ too. Intact the C++ is upward compatible to C. Hence the programs with C can be executed with C++. C++ allows us to use variable declaration anywhere in the program, and new operators such as reference and scope access operator are introduced. All these concepts are illustrated with figures and examples.
The smallest individual unit in a program is known as ‘token’. C++ programs contain various components. The compiler identifies them as tokens. Tokens are classified into the following types and are also indicated in Figure 4.1.
Fig. 4.1 Types of tokens
The keywords are reserved set of words with fixed meanings. The variables are used to hold data temporarily. The operators are used to perform different operations such as arithmetic and logical. Values such as 1, 5, 2.5, etc. are known as constants. The operators such as #, ?, and ~ are known as special characters. The # is used for preprocessor directive; ? is a conditional operator; and ~ is used for bitwise operation. The detailed descriptions of these tokens are described in following sections.
The ‘C++’ keywords are reserved words by the compiler and are assigned fixed meanings. All ‘C’ keywords are valid in C++. The programmer may not apply them in the programs for defining variable names; however, few ‘C++’ compilers permit to declare variable names that exactly match with the keywords.
The common keywords between C and C++ are listed in Table 4.1 and the additional keywords of C++ are listed in Table 4.2. These keywords are used with classes, templates, and exception handling, etc. Table 4.3 contains keywords added by ANSI committee. Table 4.4 contains additional keywords provided by Turbo C++ compiler.
Table 4.1 C and C++ Common Keywords
Table 4.2 Additional C++ Keywords
asm catch class delete friend inline new operator |
private protected public template this throw try virtual |
Table 4.3 Keywords Added by ANSI Committee
Table 4.4 Additional Keywords in Turbo C++
Each variable is represented by a symbol using identifiers. Identifiers are names of variables, functions, arrays, etc. In other words, identifiers refer to variety of entities such as structures, unions, enumeration, constants, typedef names, functions, and objects (refer Figure 4.2).
Fig. 4.2 Types of tokens
C++ identifier always starts with an alphabet and it is a plain sequence of alphabets and/or digits. C identifier does not allow blank spaces, punctuation, signs, etc.
Identifiers are user-defined names and are generally defined in lower case letters. However, the upper case letters are also permitted. The underscore (_) symbol can be used as an identifier. In general, underscore is used to link two words for the long identifiers. Valid identifiers are as follows:
length, area, volume, sUM, Average, etc.
Invalid identifiers are as follows:
Length of line, S+um, year’s, etc.
Rules for defining identifiers are as follows:
The constants in ‘C++’ are applicable to the values that do not change during execution of a program. There are several types of constants in ‘C++’. They are classified into the following groups as shown in Figure 4.3 and Table 4.5.
Fig. 4.3 ‘C++’ constants
Table 4.5 Constant Types
Example |
Constant Type |
---|---|
542 |
Integer constant |
35.254 |
Floating point constant |
0x54 |
Hexadecimal integer constant |
0171 |
Octal integer constant |
‘C’ |
Character constant |
“cpp” |
String constant |
Integer Constants:
Integer constants are represented with whole numbers. It requires minimum two bytes and maximum four bytes of memory.
The following concepts are essential for the numerical constants:
Valid Examples: 10, 20, +30, −15, etc.
Invalid integer constants: 2.3, .235, $76, 3*^6, etc.
Integers can be represented in octal or hexadecimal based on the requirement, besides decimals.
Octal has base 8 and hexadecimal 16. The octal numbers are 0, 1, 2, 3, 4, 5, 6, 7, and hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
The representation of octal numbers in C++ would be done with leading digit 0 and for hexadecimal with leading 0X.
Following are few examples of octal and hexadecimal numbers:
027, 037, 072 – octal numbers
0X9, 0Xab, 0X4 – hexadecimal
Various constants are given in Table 4.5.
Real Constants:
Real constants are often known as floating point constants and can be represented in exponential or fractional form. Integer constants are unfit to represent many quantities. Many parameters or quantities are defined not only in integers but also in real numbers. For example, length, height, prize, distance are also measured in real numbers.
The following concepts are essential for real numbers.
Examples of real numbers are as follows:
2.5, 5.521, 3.14.
The real constants can be written in exponential notation, which contains fractional and exponential parts. For example, the value 2456.123 can be written as 2.4561 X e+3.
The part that precedes ‘e’ is called as mantissa and following it is an exponent.
In this example 2.4561 is mantissa and +3 is exponent.
Following points must be noted while constructing a real number in exponential form:
Valid examples are 5.2e2, -2, 5.0e-5, 0.5e-3, etc.
Also in double type, the real numbers can be expressed with mantissa and exponent parts.
Single-character constants:
A character constant in C is represented with a single character and it is enclosed within single quotes. Each character constant has a particular integer value associated it.
Each character is represented with different ASCII value (the values are listed in Appendix 1). A character can also be represented with single digit or single special symbol or white space, all enclosed within a pair of single quote marks.
Example: ‘a’, ‘8’, ‘ ’, ‘&’, etc.
String constant:
String constants are sequence of characters enclosed within double quote marks. The string may be combination of all types of symbols.
Example: “Hello”, “India”, ”444”, “a”.
In short, the various constants are shown in Table 4.5.
A programming example for various constants is as follows:
4.1 Write a program to demonstrate various constants.
#include<iostream.h>
#include<conio.h>
int main()
{
int x;
float y;
char z;
double p;
clrscr();
x=20;
y=2e1;
z=‘a’;
p=3.2e20;
cout<<“x=”<<x<<endl;
cout<<“y=”<<y<<endl;
cout<<“z=”<<z<<endl;
cout<<“p=”<<p;
return 0;
}
x=20
y=20
z=a
p=3.2e+20
Explanation: In this programming example, various constants are assigned to different variables.
A symbolic constant is defined in the same way as a variable. However, once the constant is initialized, the assigned value cannot be altered.
The constant can be defined in three ways: #define, const keyword, enum keyword
#define preprocessor directive: The #define preprocessor directive can be used for defining constant. The symbols defined using #define are called macros. The syntax of #define is as follows.
#define name constant_value
Explanation: #define price 152
In the above example, price symbolic constant contains 152 and data type, such as int, float, or char, is not mentioned. Every time when the preprocessor finds the word price, it substitutes with 152.
4.2 Write a program to find the radius and circumference of the circle using #define directive.
#include<iostream.h>
#include<conio.h>
#define pi 3.14
int main()
{
float area,radius,circum;
clrscr();
cout<<“ Enter the radius of the circle:”;
cin>>radius;
cout<<“ Entered radius of the circle is ”<<radius;
area=pi*radius*radius;
cout<<“ Area of circle is =”<<area;
circum=2*pi*radius;
cout<<“ Circumference of the circle <<circum;
return 0;
}
OUTPUT
Enter the radius of the circle:1
Entered radius of the circle is 1
Area of circle is = 3.14
Circumference of the circle is = 6.28
Explanation: In the above program, the value of pi is replaced by 3.14 during program execution. In the program instead of writing the value of pi as 3.14 we define directly the value pi as 3.14. The term pi is used for calculating the area and circumference of the circle.
Constant using const keyword:
Example:
const int price=152;
The above declaration defines a constant of type int. Here, data type is strictly maintained while execution and the value of constant cannot be changed during run-time.
4.3 Program on const keyword.
#include<iostream.h>
#include<conio.h>
int main()
{
const int x=20;
clrscr();
cout<<“x=”<<x<<endl;
// cout<<“x=”<<x++; cannot modify the constant
return 0;
}
OUTPUT
x=20
Explanation: A constant value is assigned to the variable x and the same is displayed. If attempts are made to modify constant value, compiler shows an error (cannot modify the constant).
C++ allows us to create both constant pointer and pointer to constant. Consider the following example.
(1) Constant pointer: It is not possible to modify the address of the constant pointer.
Example:
char * const str=“Constant”;
In the above example, it is not possible to modify the address of the pointer str. Thus, the following operations will generate error.
// str=“san”; // cannot modify a constant object
// ++str; // cannot modify a constant object
(2) Pointer to constant: If pointer is declared to constant, only the value can be changed using actual variable which is not possible using pointer.
int const * pm=&k;
In the above example, pm is declared as pointer to constant. The following examples are possible and invalid operations.
// k=5; // possible
// *pm=5 // cannot modify the constant object
// pm++; // possible
// ++ *pm; // cannot modify a constant object
// *pm=5; // cannot modify a constant object
(3) Pointer and variable both constants:
Example:
const char * const p=“ABC”;
In the above example, both the pointer and variable are constants. Hence, it is not possible to change the value and address of the pointer.
4.4 Write a program to define constant pointer and pointer to constant. Perform the possible operations.
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
// constant pointer //
char * const str=“Constant”; // Declaration of constant //pointer
cout<<str;
// str=“san”; // can not modify a constant object
//++str; // can not modify a constant object
// pointer to constant //
int k=1;
int const * pm=&k; // pointer points to k
// k=5; // possible
//*pm=5 // can not modify the constant object
//pm++; // possible
//++*pm; // can not modify a constant object
// *pm=5; // can not modify a constant object
cout<<“ ”<<*pm;
// pointer and variable both constant
const char * const p=“ABC”;
// p++; // can not modify a constant object
// p=“xxx”; // can not modify a constant object
cout<<“ ”<<p;
}
OUTPUT
Constant
1
ABC
(4) Constants can be defined using enum as follows:
Example:
enum {a,b,c};
where a,b, and c are declared as integer constants with values 0, 1, and 2, respectively.
We can also assign new values to a, b, and c.
enum [a=5,b=10,c=15};
where a, b, and c are declared as integer constants with values 5,10, and 15, respectively.
C++ supports all the operators of ‘C’. In addition, C++ introduces few more operators. The new operators are <<, >>, ::, ::*, ->*,.*, delete, new, etc.
These operators are discussed in detail at the end of this chapter.
String is represented by an array of characters. String constants are enclosed in double quotes. Following are the valid examples of string constants.
“Pearson”, “Delhi”, “India”, Singapore”, “Popular”, “publisher”, etc.
A variable is used to store values. Each variable is stored in memory location(s). It can be of any data type such as integer, char, float, etc. A variable holds a single value at a time of its type; that is, values of variable vary, and the programmer can change the value of the variable.
The variable must be declared before they are used in the program. Once declared (1) the compiler obtains the variable name and (2) the compiler is notified about the data type of the variable being declared and helps in allocation of the memory. The variable can also be declared before main() and such variables are called external variables.
In C, all the variables must be declared in the declaration part. Hence, each time when one needs to declare a variable the programmer should go back to the beginning of the program.
C++ permits declaration of variables anywhere in the program. This makes the programmer more comfortable to declare the variables and need not go back to the beginning of the program. The declaration of variable consists of name of data type and variable list as follows.
The syntax of declaring a variable is as follows:
Data_type variable_name;
Example:
int age;
char m;
float s;
double k;
int a,b,c;
The int, char, float, and double are keywords to represent data types. Commas are used as separators for multiple variables.
When a variable is declared, appropriate number of bytes is reserved for that particular variable in the random access memory. Bytes are filled with garbage values if the user does not assign them a value. If the user performs operations without initializing the variable, the result will be unexpected. Hence, before using a variable it is essential to initialize it. Assigning a value to the variable is called as initialization. When a value is assigned to the variable, the garbage value is removed and replaced with the given value.
Example:
int x;
Here, the integer variable x is declared and not initialized. When the variables are not initialized, neither they are set to zero by the compiler nor they remain empty. The variables contain garbage values. The user cannot predict the garbage value, which is system dependent. The garbage values differ for each system.
If you try to print the value of x in C, the statement printf(“%d”,x) will display the garbage value (-29281 on my system). The cout<<x in C++ will display the value 0. If you use both these statements one after another, the value displayed will be 0.
4.5 Write a program to display value of uninitialized variable using cout statement.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int x;
cout<<x+5<<endl;
cout<<5+(++x);
return 0;
}
OUTPUT
0
5
6
Explanation: In the above program, the first cout statement displays the value of x zero; the second statement displays the value of x as 5; and the third statement displays the value 6. In the third statement x is incremented first and then added to 5. This program is compiled under compact memory model. If the program is compiled and executed under any other memory model the resultant value will be garbage.
All the operations performed in the above program are directly put in the cout statement. If the above program is executed with the printf() statement, the program will display the garbage values.
The following program displays garbage value of the variables:
4.6 Write a program to display garbage value of a variable.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int main()
{
int x,y;
clrscr();
y=5+(++x);
cout<<“Value of Y:”<<y;
return 0;
}
OUTPUT
Value of Y : 1134
Explanation: In the above program, 5 is added to variable x and assigned to y. One may expect that the value of y to be 6. Here, the value of y is displayed as a garbage value. From the above program it is clear that if the variable is not initialized, it will be assigned to a garbage value.
In the afore-mentioned program, the statement y=5+(++x); it uses variables x and y. The variables x and y are not initialized. The variable y has no effect on the operation because it is at the left-hand side and the result of the expression is assigned on the right-hand side. The variable x holds a garbage value. Integer 5 is added to the garbage value of x and stored in the variable y. Hence the value of y displayed is 1134.
Initialization of variable can be done at the place where it is declared or anywhere in the program before their use. Variables declared can be assigned or initialized using assignment operator ‘=’. The declaration and initialization can also be done in the same line.
Syntax: variable_name = constant;
or
data_type varaible_name= constant;
Example:
x=2; where x is an integer variable.
Example:
int y=2;
Figure 4.4 shows an example of initialization of a variable.
Syntax:
data-type variable_name = value;
Example:
int k = 5;
In the above example, variable k of integer type is declared. The value 5 is stored in it.
int a,b,c,d;
a=b=c=d=5;
Fig. 4.4 Initialization of variable
In the above example all the variables a, b, c, and d are initialized to 5. An example is illustrated as follows:
4.7 Write a program to initialize more than one variable at a time.
#include<conio.h>
#include<iostream.h>
int main()
{
int a,b,c,d;
a=b=c=d=5;
clrscr();
cout<<“ a=”<<a <<“b=”<<b <<“c=”<<c <<“d=”<<d;
return 0;
}
OUTPUT
a=5 b=5 c=5 d=5
Explanation: In the above program, variables, a, b, c, and d are declared. In next statement, all four variables are initialized with a value 5. First the value 5 assigned to variable d, then the value of d is assigned to c, c is assigned to b, and finally b is assigned to a.
Fig. 4.5 Initialization of variables
Here the variables are local and they are stored in the stack. Stack is the portion of the random access memory (RAM). Generally it is located at end of RAM to avoid overlapping of program and data memory. Figure 4.5 simulates this assignment.
The declaration and initialization of variable in a single statement at any place in the program is called as dynamic initialization. The dynamic initialization is always accomplished at run-time. Runtime means execution of program. Dynamic refers to a process carried out at run-time, for example dynamic initialization, dynamic memory allocation etc. The C++ compiler allows declaration and initialization of a variable at any point in the program. In C, initialization of variable can be done at any point but the variable must be declared at the beginning of the program illustrated as follows:
4.8 Write a program in C to demonstrate declaration and initialization of a variable.
#include<conio.h>
#include<stdio.h>
void main()
{
int r;
float area;
clrscr();
printf (“ Enter radius : ”);
scanf (“%d”,&r);
area=3.14*r*r;
printf (“ Area =%g”,area);
}
OUTPUT
Enter radius : 4
Area =50.24
Explanation: The above program is executed with C compiler. The variables area and r are declared at the beginning because declaration in C is compulsorily done at the beginning. The multiplication of 3.14 and the variable r is assigned to the variable area. This assignment is done within the program. Thus, from the above program it is demonstrated that in C variable declaration is done at the beginning and initialization can be done at any point in the program.
4.9 Write a program in C++ to demonstrate dynamic initialization.
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
cout<<“ Enter radius:”;
int r;
cin>>r;
float area=3.14*r*r;
cout<<“ Area =”<<area;
return 0;
}
OUTPUT
Enter radius : 3
Area =28.26
Explanation: In the above program, the variables r and area are declared within the program. The declaration and initialization of a variable area is done in the single statement within the program. Consider the following statement.
float area=3.14*r*r;
In the above statement, float variable area is declared and product of 3.14*r*r is assigned to the variable area. The assignment is carried out at run-time. Such type of declaration and initialization of a variable is called as dynamic initialization.
4.10 Write a program to read two integers through the keyboard. Declare the variables in C++ style.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
cout<<“Enter Two numbers:”;
int num;
cin>>num;
int num1;
cin>>num1;
cout<<“Entered Numbers are :”;
cout<<num<<“ ”<<num1;
return 0;
}
OUTPUT
Enter Two numbers : 8 9
Entered Numbers are : 8 9
Explanation: In the above program, the variables num and num1 are declared within the program and not at the beginning of the program. Once declared, they are used with cin statement that reads two integers and stores them in the variables num and num1. The cout statement displays entered values on the screen.
4.11 Use dynamic initialization and display an alphabet.
#include<iostream.h>
#include<conio.h>
int main()
{
int z=102;
clrscr();
char a = z;
cout<<a;
return 0;
}
OUTPUT
f
Explanation: In the above program, variable z is initialized with 102. The ASCII value of 102 is f; hence, the output is f.
4.12 Write a program to calculate length of the string. Use run-time declaration and initialization of variables.
#include<iostream.h>
#include<string.h>
#include<conio.h>
int main()
{
clrscr();
char name[15];
cin>>name;
int len=strlen(name);
cout<<“The length of the string is :”<<len;
return 0;
}
OUTPUT
Enter Your Name : Santosh
The length of the string is :7
Explanation: In the above program, the cin statement reads the string through the keyboard. The strlen() function is used to determine the length of the given string. The strlen() function calculates the length of the string and returns the length to variable len. The variable len is declared and value returned by strlen() is assigned to variable len. To avoid separate statements for declarations and initializations, both statements are combined as one statement. Declaration and initialization are carried out in one statement int len=strlen (name).
Data are collections of characters, digits, symbols, etc. The data are used to represent information. The data are classified into various types. Figure 4.6 indicates all data types. C++ data types can be classified as basic data type, derived data type and user-defined data type.
Fig. 4.6 C++ data types
The basic data types supported by C++ are described with their size in bytes and ranges in Table 4.6. Sizes of data types supported by C++ are shown in Figure 4.7.
Table 4.6 C++ Basic Data Types with Size and Range
Data Type |
Size in Bytes |
Range |
---|---|---|
char |
1
|
−128 to 127 |
unsigned char |
1 |
0 to 255 |
signed char |
1 |
−128 to 127 |
int |
2 |
−32768 to 32767 |
unsigned int |
2 |
0 to 65535 |
signed int |
2 |
−32768 to 32767 |
short int |
2 |
−32768 to 32767 |
unsigned short int |
2 |
0 to 65535 |
signed short int |
2 |
−32768 to 32767 |
long int |
4 |
−2147483648 to 2147483647 |
signed long int |
4 |
−2147483648 to 2147483647 |
unsigned long int |
4 |
0 to 4294967295 |
float |
4 |
3.4e-38 to 3.4e+38 |
double |
8 |
1.7e-308 to 1.7e+308 |
long double |
10 |
3.4e-4932 to 1.1e+4932 |
enum |
2 |
−32768 to 32767 |
bool |
1 |
true/false |
Fig. 4.7 Data types and their sizes
The keywords signed, unsigned, short, and long are type modifiers. A type modifier changes the meaning of the base data type to produce a new data type. Each of these type modifiers is applicable to the base type int. The modifiers signed and unsigned are also applicable to the base type char. In addition, long can be applied to double data type. When the base type is absent from a declaration, int is supposed.
Examples:
long l; // int is implied
unsigned char c;
signed int s; // signed is default
unsigned long int u; // int OK, not necessary
The type void is empty data type. It can be used in three ways:
void message (char *name)
{
cout<<“Hello.”<< name;
}
Here, message() is a void function. The keyword void is preceded by the function name. This function when executed displays only message and does not return any value to the calling function.
int fun(void)
{
return 1;
}
Here, the function is fun() and does not require any argument. It returns an integer value.
void fun (void);
The above function neither returns a value nor requires any argument.
The derived data types are pointers, functions, arrays, and references.
A pointer is a memory variable that stores a memory address. Pointer can have any name that is legal for other variable and it is declared in the same fashion like other variable but it is always denoted by ‘*’ operator.
int *x;
float *f;
char *y;
In the first statement ‘x’ is an integer pointer and it tells the compiler that it holds the address of any integer variable. In the same way ‘f’ is a float pointer that stores the address of any float variable and ‘y’ is a character pointer that stores the address of any character variable.
4.13 Write a program to use pointers.
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int x=2,*p;
cout<<“ Address of x =”<<(unsigned)&x;
p=&x;
cout<<“ Value of x=”<<*p;
return 0;
}
OUTPUT
Address of x = 4096
Value of x=2
Explanation: In this program, x is an integer variable and *p is an integer pointer. The first cout statement displays the address of variable x. The address of x is assigned to pointer p. The pointer variables are always used to store address of another variable. The second statement displays the value of x using pointer p. Figure 4.8 explains pointers.
Fig. 4.8 Pointers
A function is a self-contained block or a sub-program of one or more statements that perform a special task when called. The C++ functions are more civilized than C. It is possible to use the same name with multiple definitions known as function overloading. Figure 4.9 illustrates the functions.
Fig. 4.9 Functions
A simple program on function is described as follows:
4.14 Write a program to demonstrate user-defined functions.
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
void show (void);
show();
return 0;
}
void show()
{
cout<<“ In function show()”;
}
OUTPUT
In function show()
Explanation: In the above program, the function show() is defined. The function body contains only one cout statement. When the function is executed, a message is displayed. Functions are discussed in detail in Chapter 7 (Functions in C++).
Array is a collection of elements of similar data type in which each element is located in separate memory location, for example
int b[4];
The above statement declares an array b[] which can hold four integer values. The following program illustrates use of array.
4.15 Write a program to declare, initialize an array. Display the elements of an array.
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int b[4]={2,4,3,7};
cout<<“b[0]=”<<b[0]<<endl;
cout<<“b[1]=”<<b[1]<<endl;
cout<<“b[2]=”<<b[2]<<endl;
cout<<“b[3]=”<<b[3];
return 0;
}
OUTPUT
b[0]=2
b[1]=4
b[2]=3
b[3]=7
Explanation: In the above program, an array b [4] is declared and initialized. The cout statement displays the array elements. b[0] refers to first element, b[1] refers to second element, and so on. Figure 4.10 describes the elements in an array and their memory locations.
Fig. 4.10 Array elements and their memory locations
The & and * operators are used for referencing and dereferencing. The & symbol is also used in C++ to define reference types, and as a bitwise AND operator. We can also use the asterisk (*) as an operator to dereference a pointer and as a multiplication operator.
Syntax:
Data-type & reference variable name = variable name;
Example:
int qty=10;
int & qt=qty;
Here, qty is already declared and initialized. The second statement defines an alternative variable name, that is, qt to variable qty. If both variables printed displays the same value. Any change made in one of the variable causes the change in both the variables.
qt=qt*2;
Now, contents of qt and qty will be 20.
Note that the token & is not an address operator. The declaration int & indicates reference to data type int.
Principles for declaring reference variable are as follows:
char * h=“C++”;
char *&q=h;
int *x; Where, x is a pointer of integer type.
if the operand is a “pointer to function,” the result is a function designator. If the operand is a pointer to an object, the result is an lvalue indicating that object. In the following conditions, the result of indirection is undefined.
The & is a reference operator. It displays the address of a variable in the RAM. To display the address of the variable, it should be preceded by the variable name.
int b=10;
cout<<unsigned(&b);
The above statement displays the address of the integer variable b.
The operator * is used to display the value stored at the address of the variable.
Example:
int b = 10;
cout<<*(&b);
The above statements display the value of value stored at address of b, that is, value of b.
Fig. 4.11 Difference between & and * operator
As shown in Figure 4.11, the statement (a) displays the contents of variable b, the statement (b) displays the address of the variable b, and the statement (c) displays the value of variable b.
4.16 Write a program to declare reference variable to another variable. Display the assigned value using both the variables.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int qty=10;
int & qt=qty;
cout<<“qty Location qt Location”<<endl;;
cout<<“=== ======== == ========”<<endl;
cout<<qt<<“ ”<<(unsigned)&qt<<“ ”<<qty<<“ ”<<unsigned(&qt)<<endl;
cout<<qt<<“ ”<<(unsigned)&qt<<“ ” <<qty<<“ ”<<unsigned(&qt)<<endl;
qt--;
cout<<qt<<“ ”<<(unsigned)&qt<<“ ” <<qty<<“ ”<<unsigned(&qt)<<endl;
return 0;
}
OUTPUT
Explanation: In the above program, the variable qty is declared as integer variable and initialized with 10. The variable qt is declared as reference variable for variable qty. We can use variable qt to access the value of qty. Any change made in one of the variable changes the contents of both the variables. The contents of both variables and their addresses are always same. The variables qt and qty are modified using increment and decrement operator. But the contents and address printed of both variables are the same. Figure 4.12 explains the reference variable with respect to other variable.
Fig. 4.12 Reference variable
User-defined data types are structure and classes, union, and enumerated
(1) keyword struct: struct is a keyword and used to combine variables of different data types into a single record.
Syntax:
struct < struct name >
{
<data-type> <variable-name1, variable-name, 2>;
<data-type> <variable-name3, variable-name, 4>;
} <structure variable declarations>;
struct name: An optional tag name that defines the structure type.
structure variables: These are member variables and hold data
Though struct name and structure variables are noncompulsory, one of them should be present. Member variables in the structure are declared by naming a <data-type>, followed by one or more <variable-name> separated by commas.
A semicolon can separate variables of different data types.
Example:
struct my_friend
{
char fname [80], phone[80];
int age, height;
} friendA ;
The structure my_friend defines a variable containing two strings (fname and phone) and two integers (age and height)(Fig 4.13).
Fig. 4.13 Structure and its elements
To access elements in a structure, record selector (.) called as dot operator is used. For example
strcpy (friendA.fname,“Sachin”);
4.17 Write a program to declare struct object, initialize it and display the contents.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
struct my_friend
{
char *fname;
int phone, age;
float height;
} A ;
A.fname=“Bharat”;
A.phone=26251;
A.age=22;
A.height=4.5;
cout<<“ Contents of object A”;
cout<<“ Name:”<<A.fname;
cout<<“ Phone:”<<A.phone;
cout<<“ Age:”<<A.age;
cout<<“ Height:”<<A.height;
OUTPUT
Contents of object A
Name : Bharat
Phone : 26251
Age : 22
Height : 4.5
Explanation: In the above program, struct my_friend is defined with four member variables. Identifier A is an object of struct my_friend. The initialization of data members of struct is done using dot operator with object A. The cout statements display contents of object A.
(2) keyword class: The class is a new keyword introduced in C++. Its use is the same as struct keyword. To declare a class, following syntax is used.
Syntax:
<classkeyword> <class- name> [<:baseclasslist>]
{<member variable list>}
Class keyword: It is one of the keywords class, struct, or union.
Class-name: It can be any unique name inside its scope.
Base classlist: If the class is derived class, then it follows the list of the base class(es). It is optional.
Member variable list: Defines the data member variables and member functions.
Example:
class circle
{
int radius; // data member
int area (void); // member function
};
Reader may refer chapter 8 on class for more details.
A union is same as compared to a struct, but the only difference is that it allows the user to declare variables that share the same memory space.
The union requires bytes that are equal to the number of bytes required for the largest members. For example, if the union contains char, integer, and long integer, then the number of bytes reserved in the memory for the union is 4 bytes
Syntax:
union [<union name>]
{
<data-type> <variable names>;
} [<union variables name>];
C++ will allocate sufficient storage in union variable number to hold the largest element in the union. The union member variables number.c and number.i use the same memory location. In this way, writing into one will replace the other. Member variables of a union are accessed in the same way as a struct.
4.18 Program to access variable of different data types in union.
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
union ABC
{
char a;
int num;
float f1;
}x;
int main()
{
clrscr();
x.a=‘d’;
cout<<“ Character = ”<<x.a;
x.num=2;
cout<<“ Number = ”<<x.num;
x.f1=4.55;
cout<<“ float number = ”<<x.f1;
return 0;
}
OUTPUT
Character = d
Number = 2
float number = 4.55
Explanation: In the above program, ABC is the name of the union. a, num, f1 are the variables of char, int, and float, respectively. X is the variable associated with the union type. Dot (.) operator is used to access the variable of any data types.
An anonymous union does not contain tag name. Elements of such union can be accessed without using tag name. Consider the following example.
Union
{
int k;
float j;
};
Both the member variables of union have the same memory location. They can be accessed as follows:
K = 20;
j = 2.2;
The declaration should not declare a variable of the above union type. Following program illustrates the use of anonymous union.
4.19 Write a program to declare anonymous union and access its elements.
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
union
{
int k;
float f;
};
f=3.1;
k=2;
cout<<“ k =”<<k;
printf (“ f = %.1f”,f);
return 0;
}
OUTPUT
k = 2
f = 3.1
Explanation: In the above program, anonymous union is declared. The union has two data member variables k as integer variable and f as a float variable. The union has no tag name; hence, it is called as anonymous union. The member variable of such a union can be accessed directly like normal variable. Both the variables hold the same memory location.
The enum is a keyword. It is used for declaring enumeration data types. The programmer can declare new data type and define the variables of these data types that can hold. For example, the user can define the material as new data type. Its variable may be solid, liquid, and gas. Thus the three values are restricted for this new data type. These enumeration data types are useful in switch() case statement.
The syntax for enumerated data type is as follows and it uses a keyword enum.
enum logical { false,true};
enum logical {true=2, false=4};
enum components{solid,liquid,gas};
This statement declares a user-defined data type. The keyword enum is followed by the tag name logical. The enumerators are the identifiers false and true. Their values are constant unsigned integers and start from 0. The identifier false refers to 0 and true to 1. The identifiers are not to be enclosed with quotation marks. Also note that integer constants are not permitted and we can start the constants as given in the second statement. In the second statement, true refers to 2 and false refers to 4. In the third statement, the components is the user-defined data type and the variables attached to it are solid, liquid, and gas.
The ANSI C++ and Turbo C++ allow us to declare variables of enum type.
logical =N // N is of the type logical
logical F=false // valid
logical TT=1 // invalid in C++
logical TT=(logical) 1 // valid
int k=true; // valid
We can also define enum without tag name. Consider the following example.
enum{yes, no};
Here, yes is 0 and no is 1 and can be used as int answer=yes.
4.20 Write a program to declare enum data type and display their values.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
enum logical {false,true};
cout<<“true:”<<true<<“false :”<<false;
return 0;
}
OUTPUT
true : 1 false : 0
Explanation: In the above program, enum data type logical is declared with two values, that is, false and true. The false contains value 0 and true contains the value 1. The cout statement displays the contents of true and false. True means 1 and false means 0.
Operator is an instruction to the compiler or interpreter specified by a single or double symbol to perform certain operation with constants.
Example:
5+10
Here, 5 and 10 are constants. The symbol ‘+’ is an operator that indicates the operation to be performed. The ‘+’ performs addition of numbers. The ‘+’ is a single operator.
int x = 5;
++x;
In the above example, the operator ++ is an increment operator. This operator adds one to the value of operand.
The types of operators (Fig. 4.14) with their symbols are described in Table 4.7.
Fig. 4.14 Types of operators
Table 4.7 Types of Operators
Type of Operators |
Symbolic Representation
|
---|---|
Arithmetic operators |
+, −, *, /, and % |
Relational operators |
>, <, = =, >=.<=, and != |
Logical operators |
&&, ||, and ! |
Increment and decrement operators |
++ and −− |
Assignment operators |
=,+=,−=,*=,/=,<<=,>>=,&=,|=,^= |
Bit wise operators |
&, |, ^, >>, <<, and ~ |
Special operator |
, |
Conditional operators |
? and : |
C++ supports all operators of ‘C’ and C++ introduces new additional operators. The new operators are listed in Table 4.8.
Table 4.8 Operators in C++
Operators |
Description |
---|---|
<< |
Insertion operator |
>> |
Extraction operator |
:: |
Scope access (or resolution) operator |
::* |
Pointer to member decelerator |
−>* |
Deference pointers to pointers to class members |
.* |
Deference pointers to class members |
delete |
Memory release operator |
new |
Memory allocation operator |
The scope access (or resolution) operator :: (two colons) allows you to access a global (or file duration) name even if a local hides it redecoration of that name.
The .* and −>* operators represents deference pointers to class members and deference pointers to pointers to class members, respectively.
In the following operator precedence Table 4.9, the C++ operators are classified into 13 groups. The #1 group has the top (highest) precedence, group #2 (unary operators) takes second precedence, and so on to the comma operator, which has lowest precedence. The precedence of operator in C++ is shown in Table 4.9.
The operators within each category have equal precedence.
The unary (group #2), conditional (group #11), and assignment (group #12) operators associate right-to-left; all other operators associate left-to-right.
Table 4.9 Precedence of Operators in C++
All of the operators in this table can be overloaded except the following:
. C++ direct component selector
.* C++ dereference
:: C++ scope access/resolution
?: Conditional
In C++, the statements * x[4] and (* x) [4] are not same because the * operator having lower precedence than the [ ] operator. Consider the following examples.
The above statement declares an array of five pointers and the following operation is invalid because the array name itself is an address and it is a constant. Hence, cannot be changed.
arr++; or ++arr;
int (* arr)[5]
The above declaration declares a pointer to an array of five elements. Hence, the operations such as arr++ and ++arr are not supported. The following program explains both these conditions.
4.21 Write a program declare a pointer to array and display the elements.
#include<iostream.h>
#include<conio.h>
int main()
{
void display (int[] [3],int);
clrscr();
int a[3][3]={ {11,22,33},
{44,55,66},
{77,88,99}
};
display (a,3);
return 0;
}
void display (int x[] [3], int k)
{
int (*d) [3];
d=x;
for (int g=0;g<k;g++)
{
for (int h=0;h<3;h++)
cout<<d[g][h] <<“ ”;
cout<<“ ”;
}
}
OUTPUT
11 22 33
44 55 66
77 88 99
Explanation: In the above program, an integer array a[3][3] is declared and initialized. The base address of array and number of rows are passed to the function display(). In function display(), d is a pointer. The base address received by the variable x is assigned to pointer d. Using nested for loops, the elements of array are displayed.
Like C, the variables declared in ‘C++’ programs are totally different from other languages. We can use the same variable names in the ‘C++’ program in separate blocks. The two declarations of the same variable refer different memory locations. When we declare a variable, it is available only to specific part or block of the program. Remaining block or other functions cannot access the variable. The area or block of the ‘C++’ program from where the variable can be accessed is known as the scope of variables.
The scope access (or resolution) operator :: (two colons) allows programmer to access a global (or file duration) name even if it is hidden by a local re-declaration of that name.
4.22 Write a program to use scope access operator. Display the various values of the same variable declared at different scope levels.
#include<iostream.h>
#include<conio.h>
int a=10;
int main()
{
clrscr();
int a=20;
cout<<“::a=” <<::a;
cout<<“ a=” <<a;
return 0;
}
OUTPUT
::a=10 a=20
Explanation: In the above program, the integer variable ‘a’ is declared before main() and initialized with 10. It is a global variable. In the function main(), re-declaration of ‘a’ is done and this time the variable ‘a’ is initialized with 20. The first cout statement displays the global value of variable ‘a’, that is, 10. In this statement :: scope access operator is used to access the global value of the variable ‘a’. The second cout statement displays the local value of the variable ‘a’, that is, 20. Figure 4.15 shows the use of scope access operator for accessing global variable.
Fig. 4.15 Scope access operator
Namespace is one of the new features introduced by the ANSI C++.
It is used by programmers to avoid name clashes when programmer uses more than one library. If duplicate name with a matching scope is found in two parts of the program then name clash occurs.
All the items within the namespace have public visibility and the items declared within the namespace must include the C++ standard library and directives like using namespace std;.
Syntax of namespace is very similar to the classes or struct. The keyword namespace is followed by a namespace name, an opening curly brace, and terminated with closing brace without semicolon.
Syntax of the namespace is as follows-
Namespace name_of_the_namespace
{
…………………………
………………………….
………………………….
}
4.23 Write a program to use namespace keyword and access variables by using scope resolution operator.
Note: Following program is executed using visual c++.
#include<iostream.h>
#include<conio.h>
namespace window
{
int v=20;
float f=30;
}
int main()
{
cout<<window::v<<endl;
cout<<window::f;
return 0;
}
OUTPUT
20
30
Explanation: In the above program, variables v and f are declared within the namespace and are accessed by using scope resolution operator (::).
4.24 Write a program to perform few arithmetic operations between the variables declared under two namespaces.
Note: Following program is executed using visual c++.
#include<iostream.h>
namespace window
{
int v=20;
float f=2.5;
}
namespace wind
{
int v=20;
float f=2.5; e
}
int main()
{
cout<<“ Additon of two numbers:”<<endl;
cout<<window::v+wind::v<<endl;
cout<<“Multiplication of two numbers”<<endl;
cout<<window::f*wind::f<<endl;
return 0;
}
OUTPUT
Additon of two numbers:
40
Multiplication of two numbers
6.25
Explanation: In the above program, two different namespaces are used. Variables declared within them are used for performing the mathematical operations such as addition and multiplication.
4.25 Write a program to illustrate nested namespaces. Also use the unnamed namespace and display the variable declare and initialized in it.
Note: Following program is executed using visual c++.
#include<iostream.h>
namespace xyz
{
char b=‘p’;
namespace amit
{
int a=5;
char b=‘u’;
}
}
namespace //unnamed namespace
{
int g=100;
}
int main()
{
cout<<“a=”<<xyz::a<<endl;
cout<<“b=”<<xyz::b<<endl;
cout<<“a=”<<xyz::amit::a<<endl;
cout<<“b=”<<xyz::amit::b<<endl;
cout<<“g=”<<g;
return 0;
}
OUTPUT
a=2
b=p
a=5
b=u
g=100
Explanation: In this program nesting of namespaces is used and the variables declared under it are accessed. Unnamed namespace is used and variable within it is assigned a value which is displayed.
4.26 Write a program to declare a function using namespace and perform different operations.
#include<iostream.h>
namespace xyz
{
int mul(int x,int y)
return(x*y);
}
int div(int x,int y);
}
int xyz::div(int x,int y)
{
return(x/y);
}
int main()
{
cout<<“Multiplication =”<<xyz::mul(10,20)<<endl;
cout<<“Division =”<<xyz::div(20,10)<<endl;
return 0;
}
OUTPUT
Multiplication =200
Division =2
Explanation: Two functions named as mul and div are taken in namespace. Arguments to the functions are passed from the main() and functions’ results are displayed.
In ‘C’ language, we have studied the function malloc(), calloc(), and realloc() to allocate memory dynamically at run-time in the program. The free() function is used to release the resources allocated by these functions. C++ allows us to use these functions. In additional, C++ provides operators which help us to allocate and release the memory in easy way than these functions. These new operators are new and delete. The new operator creates an object and delete destroys the object. These operators are easy in writing as compared to malice() and calloc(). The syntaxes for new and delete are illustrated with suitable programs.
Following are the advantages of new operator over the function malloc():
Format of new operator is as follows:
pointer memory variable = new operator – data type[size];
Here, pointer memory variable is a pointer to the data type. The new operator allocates memory of specified type and returns back the starting address to the pointer memory variable. Here, the element size is optional and used when we allocation of memory space is required for user-defined data types such as arrays, classes, and structures. If the new operator fails to allocate the memory it returns NULL, which can be used to detect failure or success of new operator.
Examples:
In example (a), pv is a pointer variable of integer type. Once allocated, the pv contains the starting address. In example (b), 50 is assigned to pointer variable pv. In example (3), memory for 3 integers, that is, 6 bytes are assigned to pointer variable p. The example of new operator with arrays are as follows:
pv= new int [5] [2]; // valid
pv= new int [8][k][2] // invalid
pv= new int [ ] [ 2 ] [ 2 ] // invalid
4.27 Program to illustrate the simple example of new operator.
#include<conio.h>
#include<iostream.h>
int main()
{
int *x;
clrscr();
x=new int[10];
if(x==NULL)
cout<<“ Memory is not allocated”;
else
cout<<“ Memory is allocated”;
return 0;
}
OUTPUT
Memory is allocated
Explanation: In the above program, x is an integer pointer variable. The new operator allocates memory required for 10 integers, i.e. 20 bytes to pointer x as each integer occupies 2 bytes. new operator is used to replace the sizeof() operator.
The delete operator frees the memory allocated by the new operator. This operator is used when the memory allocated is no longer used in the program. The following syntax is used for the delete operator.
Syntax |
Example |
a) delete <pointer memory variable> |
a) delete p; |
b) delete [element size] <pointer memory variable> |
b) delete [5 ]p or delete [ ]p; |
In example (a), the delete operator releases the memory allocated to pointer p. Example (b) is advantageous when we want to free the dynamically allocated memory of array. The new C++ compilers do not require element size.
4.28 Program to illustrate the simple example of new operator.
#include<conio.h>
#include<iostream.h>
int main()
{
int *x;
clrscr();
x=new int[10];
if(x==NULL)
cout<<“ Memory is not allocated”;
else
cout<<“ Memory is allocated”;
delete x;
return 0;
}
OUTPUT
Memory is allocated
Explanation: The above program shows allocation of memory by using new operator. The delete operator frees the memory allocated by the new operator.
4.39 Write a program to allocate memory using new operator.
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
int *p= new int[3],k; // Memory allocation for 3 integers
for (k=0;k<3;k++)
{
cout<<“ Enter a Number :”;
cin>>*p;
p++; // Pointing to next location
}
p-=3; // Back to starting location
cout<<“ Entered numbers with their address are : ”;
for (k=0;k<3;k++)
{
cout<<“ ”<<*p <<“ ”<<(unsigned)p; // type casting
p++;
}
p-=3;
delete p;
}
OUTPUT
Enter a Number : 7
Enter a Number : 9
Enter a Number : 8
Entered numbers with their address are :
7 3658
9 3660
8 3662
Explanation: In the above program, p is an integer pointer variable. The new operator allocates memory required for three integers, i.e. 6 bytes to pointer p. The first for loop reads integer through the keyboard and stores the number at memory location pointed by p as shown in Figure 4.16. Each time, pointer p is incremented and it shows the next location of its type. The second for loop displays the number by applying the same logic. Before that the pointer is again set to the starting location by decrementing by 3. The delete operator releases the memory allocated by the new operator. Figure 4.16 shows the memory allocation of the different variable.
Fig. 4.16 Memory allocated by the different variables
In the output of the program, only starting memory location numbers are displayed.
The sizeof() operator is used to return size occupied in bytes in memory by the variable. The sizeof() operator in C++ displays different values as compared to C. The following program illustrates this.
4.30 Write a program to display number of bytes occupied by char data type.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<sizeof(‘a’);
}
OUTPUT
1
Explanation: In the above program, a character constant is used, sizeof( ) operator. The size determined is 1 byte. The same program ‘C’ will display the size 2 bytes, because C and C++ reacts differently with data types. In C, ‘a’ character is considered as integer. Hence the size displayed is 2 whereas in C++, it is considered as a character.
The size is the space occupied in memory in bytes by the variable. It depends upon the data type of variable. Figure 4.17 describes the space occupied in the memory by the variable integer and float.
Example:
int x = 5;
float f = 3.14;
The integer variable occupies two bytes and float variable occupies four bytes in memory.
Fig. 4.17 Space occupied by the int and float
In C++ a symbol // (double slash) is used as a comment symbol and there is no termination symbol. Comment begin with // symbol. A comment can be inserted anywhere in the line and whatever follows till the end of line is ignored. The C comment symbols /* and */ are also valid in C++.
Examples:
// This is a C++ comment style
/* The C comment style is also valid in C++. */
In C, every statement of the program is terminated by semicolon (;). In C++ it is applicable and in addition C++ allows us to terminate a statement using comma operator after satisfying the following rules.
Consider the following programs.
4.31 Write a program to use comma operator in place of semi-colon.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr(),
cout<<“ Use of comma operator”,
cout<<endl;
}
OUTPUT
Use of comma operator
Explanation: In function main(), the first two statements are terminated by comma operator and the last statement is terminated by semicolon.
All the above points are noticed in the Turbo C++ compiler. The reader is advised to follow his/her own observations.
4.32 Write a program to declare an integer, initialize it and display it. Terminate the statements using comma operator.
#include<iostream.h>
#include<conio.h>
void main()
{
int x;
clrscr(),
cout<<“ x = ”<<x,
cout<<endl;
}
OUTPUT
x = 10
Explanation: In the above program, the first and last statements are terminated by semicolon. Comma operator terminates the statements in between these two statements.
The curly braces ({}) are used to define the body of function and scope of the control statements. The opening curly brace ({) indicates starting of the scope and closing curly (}) brace indicates the end of the scope. It is also possible to use comma operator in condition and loop statement in place of {} to indicate the scope of the statement. The use of comma operator is not allowed in definition of function. The following declaration is invalid.
main()
,
,
The following program explains the use of comma operator with conditional and loop statements.
4.33 Write a program to use comma operator in if–else structure as scope indicator.
#include<iostream.h>
#include<conio.h>
void main()
{
int x;
clrscr(),
x=10;
if (x==10) // if block
cout<<x<<endl,
cout<<x+1<<endl,
cout<<x+2<<endl,
cout<<“end of if block”; // end of if block terminated by semi-colon //
else
cout<<“False”, // else block
cout<<“ End”; // end of else block terminated by semi-colon
}
OUTPUT
10
11
12
end of if block
Explanation: In the above program, integer variable x is declared and initialized with 10. The if statement checks the value of x and executes respective blocks. The statements of if and else blocks are terminated by comma. The last statements of if block and else block are terminated by a semicolon to indicate the end of scopes. In this program, the if block is executed.
4.34 Write a program to use comma operator in for loop to indicate the scope.
#include<iostream.h>
#include<conio.h>
void main()
{
int x;
clrscr(),
x=5;
for (;x>0;x--)
cout<<“ x = ”<<x, // {
cout<<“ In loop”,
cout<<“ In loop”; // }
cout<<“ Out of loop”; // executed after end of for loop
}
OUTPUT
x = 5 In loop In loop
x = 4 In loop In loop
x = 3 In loop In loop
x = 2 In loop In loop
x = 1 In loop In loop Out of loop
Explanation: In the above program, the statements terminated by comma are included in the scope of for loop. The first two statements are terminated by comma and the last statement is terminated by semicolon, that is end of scope of for loop.
4.35 Write a program to show the use of scope access operator.
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
int j=11;
int main()
{
clrscr();
int j=12;
cout<<“ Local j = ”<<j <<“ Global j = ”<<::j;
::j=21;
cout<<“ Local j = ”<<j <<“ Global j = ”<<::j;
return 0;
}
OUTPUT
Local j = 12 Global j = 11
Local j = 12 Global j = 21
Explanation: In the above program, variable j is declared in two scopes, that is, local and global. The variable j declared before main() is a global variable and the variable j is declared inside the main() function is local. Both global and local variables are initialized with 11 and 12, respectively. The local variable j can be accessed directly. The local variable hides the existence of global variable. The global variable can be accessed using (::) the scope access operator. The scope access operator prefixed with variable name displays the value of global scope and similarly we can also change the value. The output shows the values of local and global variables.
Whenever there is a tie between local and global variables, the local variable gets the preference.
4.36 Write a program to define three variables in different scopes and access them with and without a scope access operator.
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
int j=10;
int main()
{
int j=20;
cout<<“ j = ”<<j <<“ j = ”<<::j;
{
int j=30;
cout<<“ j = ”<<j <<“ j = ”<<::j;
}
cout<<“ j = ”<<j <<“ j = ”<<::j;
return 0;
}
OUTPUT
j = 20 j = 10
j = 30 j = 10
j = 20 j = 10
Explanation: In the above program, the variable j is declared in three different scopes. First is defined in before main(), second is inside the main(), and the third one is also inside the main() but within another block. The first cout statement displays the values of variable j of local and global scope. The second cout statement that is inside the block displays the value of variable j local to the same block and the global variable declared before main(). The third statement produces the same output as the first.
4.37 Write a program to demonstrate the use of reference variable.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
int x=15;
int &y=x;
cout<<endl <<“x = ”<<x <<“ y = ”<<y;
y=25;
cout<<endl<<“x = ”<<x <<“ y = ”<<y;
x=x+y;
cout<<endl<<“x = ”<<x <<“ y = ”<<y;
x--;
cout<<endl<<“x = ”<<x <<“ y = ”<<y;
y--;
cout<<endl<<“x = ”<<x <<“ y = ”<<y;
cout<<endl <<“Address of x=” <<(unsigned)&x <<“ Address of y=”<< (unsigned) &y;
return 0;
}
OUTPUT
x = 15 y = 15
x = 25 y = 25
x = 50 y = 50
x = 49 y = 49
x = 48 y = 48
Address of x=65524
Address of y=65524
Explanation: In the above program integer variable x is initialized to 15 and y is declared reference to variable x. The variable x and y refers to the same memory location and change in one variable can affects other. In the above program values of variable x and y are modified and values and address are displayed. From the output we notice that value and address of the variable x and y are displayed same.
4.38 Write a program to pass structure variable into function using c and c++ style.
#include<iostream.h>
#include<conio.h>
#include<string.h>
struct boys
{
char name[20];
int age ;
};
int main()
{
clrscr();
void cstyle(boys *);
void cppstyle(boys &);
boys b1={“Ankit”,15};
boys b2={“Saurav”,10};
cstyle(&b1);
cout<<“ Name : ”<<b1.name<<“ Age : ”<<b1.age;
cppstyle(b2);
cout<<“ Name : ”<<b2.name<<“ Age : ”<<b2.age;
}
void cstyle (boys *b)
{
strcpy (b->name,“Suraj”);
b->age=11;
}
void cppstyle (boys &b)
{
strcpy (b.name,“Harsha”);
b.age=5;
}
OUTPUT
Name : Suraj Age : 11
Name : Harsha Age : 5
Explanation: In the above program, the structure boy is declared before main() with two data members name and age of char and int data type, respectively. Two user-defined functions are defined as cstyle() and cppstyle(). In function main(), b1 and b2 are two variables of the struct boy type and they are initialized. The address of b1 is passed to the cstyle() function whereas cppstyle() needs only variable name. The cstyle() function receives address and stores it in the pointer. The cppstyle() function accept reference of the actual variable and stores it in the format variable. The code inside these functions directly replaces the old values with new ones. The result is displayed as per the output.
4.39 Write a program to return an object by reference.
#include<iostream.h>
#include<conio.h>
#include<string.h>
struct boys
{
char name[20];
int age ;
};
boys b1={“Ankit”,15};
boys b2={“Saurav”,10};
int main()
{
clrscr();
boys & show();
show()=b2;
cout<<“ Name : ”<<b1.name<<“ Age : ”<<b1.age;
}
boys & show()
{
cout<<“ Name : ”<<b1.name<<“ Age : ”<<b1.age;
return (b1);
}
OUTPUT
Name : Ankit Age : 15
Name : Saurav Age : 10
Explanation: In the above program, structure boys is declared. The objects b1 and b2 are declared of structure boys type. Both the structure variables are initialized. The function show() is declared and defined. The statement show()=b2; passes contents of b2 into function show(). The contents of variable b1 are displayed that is similar to b2. The function returns object b1 and again content of b1 is displayed.
4.40 Write a program to declare constant variable and calculate area of a circle.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
float r, area;
const float pi=3.14;
clrscr();
cout<<“ Enter radius : ”;
cin>>r;
area= pow(r,2)*pi;
cout<<“ Area of circle : ”<<area;
return 0;
}
OUTPUT
Enter radius : 2
Area of circle : 12.5
Explanation: In the above program, variable r and area are of float type. The variable pi is constant and initialized to 3.14. The value of r is entered through the keyboard. Area of circle is calculated using the formula. The pow() function calculates the square of the variable r. The cout statement displays the area of the circle. The variable pi is constant and cannot be changed during the program execution.
4.41 Write a program to declare reference variable to const variable.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
const int x=15;
int & y=x;
cout<<“ x = ”<<x << “ y = ”<<y;
y=25;
cout<<“ x = ”<<x <<“ y = ”<<y;
return 0;
}
OUTPUT
x = 15 y = 15
x = 15 y = 25
Explanation: In the above program, integer x is a constant variable and initialized with 15. The variable y is a reference variable to variable x. We cannot change the value of x as it is a constant variable. But we can change the value of its reference variable. The change in reference variable does not change the value of constant variable. The output shows the values of both the variables.
4.43 Write a program to declare a constant variable.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
int x=15;
const int & y=x;
cout<<“ x = ”<<x << “ y = ”<<y;
x=25;
cout<<“ x = ”<<x <<“y = ”<<y;
return 0;
}
OUTPUT
x = 15 y = 15
x = 25 y = 25
Explanation: The above program is the same as previous one. In this program the reference is declared as constant. We cannot change the value of the reference variable. A change made in actual variable changes the value of the reference variable.
4.44 Write a program to declare reference variable to character pointer and display the strings.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
char *txt1=”Eye”;
char *& txt2=txt1;
cout<<“ ”<<txt1 <<“ ”<<txt2;
*txt1=‘B’;
cout<<“ ”<<txt1 <<“ ”<<txt2;
*txt2=‘d’;
cout<<“ ”<<txt1 <<“ ”<<txt2;
return 0;
}
OUTPUT
Eye Eye
Bye Bye
dye dye
Explanation: In the above program, txt1 is a character pointer and initialized with the string “Eye”. The pointer txt2 is a reference variable to the character pointer txt1. The statement *txt1=‘B’; replaces the first character of the string with character ‘B’ and contents of both the pointers are displayed. The statement *txt2=‘d’; replaces the first character of the string with variable ‘d’ through the reference variable.
4.45 Write a program to return a constant reference.
#include<iostream.h>
#include<conio.h>
#include<math.h>
int main()
{
clrscr();
const char *show();
const char *s;
// *s=‘W’; can not modify the constant object
cout<<s;
return 0;
}
const char *show() { return “Hello”; }
OUTPUT
Hello
Explanation: In the above program, the function show() and pointer s are declared as constants. It is not possible to assign any data to pointer s because it is a constant. The function show() is invoked and it returns string. The returned string is assigned to pointer s. The content displayed is “Hello”.
4.46 Write a program to use global and local variable and their pointer of same name and calculate their sum.
#include<iostream.h>
#include<conio.h>
int s=15;
int *sp=&s;
int main()
{
clrscr();
int s=20;
int *sp=&::s;
cout<<“Local Variable s = ”<<s<<endl;
cout<<“Global Variable ::s = ”<<::s<<endl;
cout<<“Local pointer sp = ”<<*sp<<endl;
cout<<“Global pointer ::sp = ”<<*::sp<<endl;
cout<<“::s + s = ” <<::s+s<<endl;
cout<<“*::sp+ *sp = ”<<*::sp+*sp;
return 0;
}
OUTPUT
Local Variable s = 20
Global Variable ::s = 15
Local pointer sp = 15
Global pointer ::sp = 15
::s + s = 35
*::sp+ *sp = 30
Explanation: In the above program, variable s and pointer sp are declared in two scopes, that is, global and local. The address of global variables is assigned to both the local and global pointers sp using the following statements:
In statement (a), the address of global variable s is assigned to global pointer sp. In statement (b), the scope access operator is used to access the global variable and ampersand pre-fixed assigns address of global variable to local pointer sp. Thus, both the local and global pointers point to the same variable. The output indicates contents of individual variables and pointers and sum of local and global variables. The last sum result is 30 since both pointers point to the same variable, that is global variable.
4.47 Write a program to perform division of local and global variable of same name.
#include<iostream.h>
#include<conio.h>
#define G ::
int loop=110;
int main()
{
clrscr();
register loop=2;
for (;loop<10;loop+=2)
cout<<endl<<G loop/loop;
return 0;
}
OUTPUT
55
27
18
13
Explanation: In the above program, G is a macro initialized with scope access operator. We can use G in place of (::) scope access operator. The variable loop is declared and initialized in two scopes (local and global). Using for loop repetitive division of global and local loop variable is performed and result is displayed.
4.48 Write a program to create variable with reference to pointer variable. Initialize and display the values.
#include<iostream.h>
#include<conio.h>
{
clrscr();
int a=175;
int *x=&a;
int &j=*x;
cout<<“a = =”<<a <<“j = ”<<j <<“*x = ”<<*x <<endl;
int q=147;
x=&q;
q=155;
cout<<“a = ”<<a << “ j=”<<j <<“*x = ”<<*x<<endl;
return 0;
}
OUTPUT
a= =175 j = 175 *x = 175
a = 175 j=175 *x = 155
Explanation: In the above program, integer a is declared and initialized with value 175. The pointer variable x is declared and initialized with address of variable a. The reference variable j is declared and value pointer x is assigned to it. The cout statement displays the values of a, j, and x. The value printed is 175. The integer variable q is declared and initialized with 147. Its address is assigned to pointer x and again q is initialized with 155. This time the values of a, j, and x displayed are 175,175, and 155, respectively. The value of pointer is altered but values of actual and reference variables are unaffected.
4.49 Write a program to use type casting and convert values from one to another data type.
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int x;
float y=2.1;
cout<<“int(15.2) = ”<<int(15.2) <<endl;
cout<<“int(85.13)= ”<<int(85.13) <<endl;
cout<<“y = ”<<y<<endl;
x=int(y);
cout<<“x=”<<x<<endl;
y=float(x)+1.5;
cout<<“y = float(x)+1.5 = ”<<y;
}
OUTPUT
int(15.2) = 15
int(85.13)= 85
y = 2.1
x=2
y = float(x)+1.5 = 3.5
Explanation: In the above program, x is an integer variable and y is a float variable. The variable y is initialized with value 2.1. The values 15.2 and 85.13 are displayed by converting them to integer using type casting syntaxes.
The value of float y is assigned to integer variable x using type casting. The values of x and y are displayed on the screen. Again variable y is assigned with x + 1.5. The result will be 3.5 and not 3.6 because by applying float type cast we cannot convert an integer value to float.
(A) Answer the following questions
(B) Answer the following by selecting the appropriate option
#include<iostream.h>
int main()
{
char *n;
cout<<sizeof(n);
return 0;
}
#include<iostream.h>
void main()
{
int *p, c=0;
p=new int[4];
for (int x=0;x<2;x++)
c=c+sizeof((p+x));
cout<<c;
}
#include<iostream.h>
void main()
{
{
for ( int i=0;i<5;i++)
{ cout<<i; }
}
cout<<“i =”<<i;
}
#include<iostream.h>
#include<conio.h>
union aa
{
int a;
char b;
float c;
unsigned int d;
double e;
}z;
int main()
{
clrscr();
cout<<sizeof(z);
return 0;
}
#include<iostream.h>
#include<conio.h>
struct aa
{
char b;
float c;
unsigned int d;
double e;
}z;
int main()
{
clrscr();
cout<<sizeof(z);
return 0;
}
#include<iostream.h>
namespace aaa
{
int b=10;
}
int main()
{
cout<<b;
}
#include<iostream.h>
namespace
{
char b=‘a’;
}
int main()
{
cout<<b;
}
#include<conio.h>
#include<iostream.h>
void main()
{
clrscr();
float x=5.5,y=10.0,*p,*q,r;
p=&x;
q=&y;
r=*p++*++*q/2;
cout<<“ Value of r=”<<r;
getch();
}
#include<iostream.h>
#include<constream.h>
const int tax=1000;
void main()
{
clrscr();
int value=10000;
int cost;
cost=tax+value;
cout<<“ ”<<cost;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int *price= new
*price=500,price++;
price-=1;
cout<<“Price :”;
cout<<“ ”<<* price,delete price;
}
(C) Attempt the following programs
Ct = 8x/27Rb
p = x/27b2
v = 3b
R = 0.0821 dm3atm/mol/k
Read values of x and y and calculate and print the values of Ct, p, and v.
Below Rs. 15000 150001–20000 200001–30000 Above 30000 |
No commission 5% 10% 12% |
Write a program to read the sales and display the commission.