Components of A C
Components of A C
1. Object − The object in C++ consists of states and behaviors . An object is an instance of
the class Example: A car has states - color, name, brand as well as behaviors - mileage, speed. An
object is an instance of a class.
2. Class − Classes are the language element in C++ most important to the support object-
oriented programming (OOP). A class defines the properties and capacities of an object. It
can be defined as a template or blueprint that describes the behaviors or states that object of its type
support.
3. Methods − A method defines the behavior of a class. There can be many methods in a
class. In methods the logics are written, data is manipulated and all the actions in the
code are executed.
4. Instance Variables − : There is a set of instant variables associated with the objects.
An object's state is created by the values assigned to these instance variables.
#include <iostream>
using namespace std;
Header, which contain information that is either necessary or useful to your program.
For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace.
Namespaces is a recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the end of
the line.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World."; causes the message "Hello World" to be
displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0
to the calling process.
2.1.2 Compile and Execute C++ Program
Follow the steps to save, compile and run the program −
In fact all keywords are subset of Reserve words. Keywords can be redefined while
reserved words cannot be redefined and used.
For example :
Example 1:
#include<iostream>
using namespace std;
int main() // here main is the keyword
{
int main; // it can be redefined
main = 1;
cout<< main;
return 0;
}
Here main is the keyword. So it can be redefined and used as an identifier.
Output :
1
Example 2:
#include <iostream>
using namespace std;
int main()
{
int auto;
auto = 1;
cout<< auto;
return 0;
}
Here auto is a reserved word. It cannot be redefined. So it gives an error.
The reserved words of C++ may be conveniently placed into several groups. In the first group,
we put those that were also present in the C programming language and have been carried
over into C++. There are 32 such reserved words:
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
There are another 30 reserved words that were not in C, are therefore new to C++:
asm dynamic_cast namespace reinterpret_cast try
bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t
The following 11 C++ reserved words are not essential when the standard ASCII character set
is being used, but they have been added to provide more readable alternatives for some of the
C++ operators, and also to facilitate programming with character sets that lack characters
needed by C++.
and bitand compl not_eq or_eq xor_eq
and_eq bitor not or xor
Identifiers
In C++, an identifier is a name assigned to a function, variable, or any other user-defined item. Identifiers can
be from one to several characters long. Variable names can start with any letter of the alphabet or an
underscore. Next comes a letter, a digit, or an underscore. The underscore can be used to enhance the
readability of a variable name, as in line_count. Uppercase and lowercase are seen as different; that is, to C++,
myvar and MyVar are separate names. There is one important identifier restriction: you cannot use any of the
C++ keywords as identifier names. In addition, predefined identifiers such as cout are also off limits.
Remember, you cannot start an identifier with a digit. Thus, 98OK is invalid. Good programming practice
dictates that you use identifier names that reflect the meaning or usage of the items being named.
2.3 Constants/Literals
Constants or Literals are fixed values which never change their value throughout the
execution of the program. Constants are treated just like regular variables except that their
values cannot be modified after their definition.
Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.
An integer constant can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
313 // Legal
316u // Legal
0xFeeL // Legal
058 // Illegal: 8 is not an octal digit
042UU // Illegal: cannot repeat a suffix
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal consists of an integer part, a decimal point, a fractional part, and an
exponent part. The floating point literals can be represented either in decimal form or
exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or
both and while representing using exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
3.14159 // Legal
314159E-5L // Legal
610E // Illegal: incomplete exponent
310f // Illegal: no decimal or exponent
.e77 // Illegal: missing integer or fraction
Boolean Literals
The Boolean literals are of two types and they are part of standard C++ keywords −
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it
is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable .
Otherwise, it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of
char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C++ when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a
list of some of such escape sequence codes −
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literals
String literals are enclosed in double quotes. A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separate them using
whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
When the above code is compiled and executed, it produces the following result −
50
The const prefix can be used to declare constants with a specific type as follows −
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
When the above code is compiled and executed, it produces the following result −
50
Data types in C++ are categorised in three groups: Built-in, user-defined and Derived.
2.4.1 Primitive Data Types
The various primitive data types available in C++.
Integer: Variables of type int hold integer quantities that do not require fractional components.
Variables of this type are often used for controlling loops and conditional statements, and for
counting. Because they don’t have fractional components, operations on int quantities are much
faster than they are on floating-point types.Keyword used for integer data types is
i1111111nt. Integers typically requires 4 bytes of memory space and ranges from -
2147483648 to 2147483647. The difference between signed and unsigned integers is in the
way the high-order bit of the integer is interpreted. If a signed integer is specified, then the C++
compiler will generate code that assumes that the high-order bit of an integer is to be used as a sign
flag. If the sign flag is 0, then the number is positive; if it is 1, then the number is negative. Negative
numbers are almost always represented using the two’s complement approach. In this method, all
bits in the number (except the sign flag) are reversed, and then 1 is added to this number. Finally,
the sign flag is set to 1.
Character: Variables of type char hold 8-bit ASCII characters such as A, z, or G, or any other 8-bit quantity.
Character data type is used for storing characters. Keyword used for character data type
is char. Characters typically requires 1 byte of memory space and ranges from -128 to
127 or 0 to 255. To specify a character, you must enclose it between single quotes. Thus, this assigns X to
the variable ch:
char ch;
ch = 'X';
You can output a char value using a cout statement. For example, this line outputs the value in ch:
cout << "This is ch: " << ch;
The char type can be modified with signed or unsigned. Technically, whether char is signed or unsigned by
default is implementation-defined. However, for most compilers char is signed. Character data type is used
for storing characters. Keyword used for character data type is char. Characters typically
requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool. C++
defines two Boolean constants, true and false, which are the only two values that a bool value can have.
Before continuing, it is important to understand how true and false are defined by C++. One of the
fundamental concepts in C++ is that any nonzero value is interpreted as true and zero is false. This
Floating Point Types: Variables of the types float and double are employed either when a
fractional component is required or when your application requires very large or small numbers.
Variables of the types float and double are employed either when a fractional component is required or
when your application requires very large or small numbers. The difference between a float and a
double variable is the magnitude of the largest (and smallest) number that each one can hold.
Floating Point data type is used for storing single precision floating point values or
decimal values. Keyword used for floating point data type is float. Float variables
typically requires 4 byte of memory space.
Double Floating Point data type is used for storing double precision floating point
values or decimal values. Keyword used for double floating point data type is double.
Double variables typically requires 8 byte of memory space. Typically, a double can store a
number approximately ten times larger than a float. Of the two, double is the most commonly used.
One reason for this is that many of the math functions in the C++ function library use double values.
void: Void means without any value. void datatype represents a valueless entity. Void
data type is used for those function which does not returns a value.
Wide Character: Wide character data type is also a character data type but this data
type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long.
C++ allows certain of the basic types to have modifiers preceding them. A modifier alters the meaning of the
base type so that it more precisely fits the needs of various situations. The data type modifiers are listed here:
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to int. The modifiers signed and unsigned
can be applied to the char type. The type double can be modified by long. Table 2-1 shows all valid
combinations of the basic types and the type modifiers. The table also shows the guaranteed minimum
range for each type as specified by the ANSI/ISO C++ standard.
2.4.2 Derived Data Types
Data types that are derived from the built-in data types are known as derived data types. The
various derived data types provided by C++ are arrays, junctions, references and pointers.
Array An array is a set of elements of the same data type that are referred to by the
same name. All the elements in an array are stored at contiguous (one after another)
memory locations and each element is accessed by a unique index or subscript value.
The subscript value indicates the position of an element in an array.
Function A function is a self-contained program segment that carries out a specific
well-defined task. In C++, every program contains one or more functions which can be
invoked from other parts of a program, if required.
Reference A reference is an alternative name for a variable. That is, a reference is an
alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made to any of them (say, a variable) are reflected in the other (on a
reference).
Pointer A pointer is a variable that can store the memory address of another variable.
Pointers allow to use the memory dynamically. That is, with the help of pointers,
memory can be allocated or de-allocated to the variables at run-time, thus, making a
program more efficient.
2.4.3 User-Defined Data Types
Various user-defined data types provided by C++ are structures, unions, enumerations and
classes.
Structure, Union andClass: Structure and union are the significant features of C language.
Structure and union provide a way to group similar or dissimilar data types referred to by a
single name. However, C++ has extended the concept of structure and union by incorporating
some new features in these data types to support object -oriented programming.
C++ offers a new user-defined data type known as class, which forms the basis of object-
oriented programming. A class acts as a template which defines the data and functions that are
included in an object of a class. Classes are declared using the keyword class. Once a class has
been declared, its object can be easily created.
Enumeration: An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables. These set of permissible
values are known as enumerators. For example, consider this statement.
By default, the first enumerator in the enumeration data type is assigned the value zero. The
value of subsequent enumerators is one greater than the value of previoNepal enumerator.
Hence, the value of NEPAL is 0, value of UN is 1 and so on. However, these default integer
values can be overridden by assigning values explicitly to the enumerators
as shown here.
In this declaration, the value of NEPAL is O by default, the value of UN is 3, India is 4 and
soon.
Once an enum type is declared, its variables can be declared Nepaling this statement.
These variables countryl, country2 can be assigned any of the values specified in enum
declaration only. For example, consider these statements.
Though the enumerations are treated as integers internally in C++, the compiler issues a
warning, if an int value is assigned to an enum type. For example, consider these statements.
C++ also allows creating special type of enums known as anonymous enums, that is, enums
without using tag name as shown in this statement.
The enumerators of an anonymous enum can be used directly in the program as shown here.
In this declaration, a new name integer is given to the data type into This new name now can
be used to declare integer variables as shown here.
integer i, j, k;
Note that the typedef is used in a program to contribute to the development of a clearer
program. Moreover, it also helps in making machine-dependent programs more portable.
2.6 OPERATORS
C++ has a rich set of operators. All C operators are valid in C++ also. An operator is a symbol
that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich
in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
> Checks if the value of left operand is greater than (A > B) is not true.
the value of right operand, if yes then condition
becomes true.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −
Binary Ones Complement Operator is unary and (~A ) will give -61 which is 1100 0011 in 2's
~
has the effect of 'flipping' bits. complement form due to a signed binary number.
{ block 2
int x=1; block 1
………;
}
…………;
}
Block 2 contained in Block 1. note that a declaration in the inner block hides the declaration in
outer block, therefore, each declaration of x causes it to refer to a different data object. Within
the inner block , the variable x will refer to the data object declared therein.
In C global version of a variable can’t be accessed from within the inner block. C++ resolves
this problem by introducing a new operator called scope resolution operator ( : : ). This can be
used to uncover a hidden variable.
: : variable-name
int main(void)
{
int m=20;
cout<<” \n m in inner block :”<<m;
cout<<”\n uncovered m :”<<: :m;
}
output :
m in inner block : 20
uncovered m :10
A major application of the scope resolution operator is to identify the class to which a member
function belongs.
class A
{
private : int m;
Note that int *ip = &m is illegal for m is not simply an int data type.
The pointer ip can be used to access the member m inside member function or
friend function.
The operator ->* or dereferencing operator is used to access a member when we use pointers to
both member and object.
cout<< ap->m;
cout<<ap->*ip;
are equivalent.
Since these operators manipulate memory on the free store, they are also known as free store
operator.
The new operator allocates sufficient memory to hold a data object with any data type and
returns the address of the object. The data type may be any valid data type. The pointer variable
holds the address of the memory space allocated . e.g.
writing
int *p ;
float *q ;
p = new int;
q = new float;
int *ip = new int ;
also permissible.
General form :
When a data object is no longer required, it is destroyed to release the memory space for re-use
using the delete operator.
delete q;
2.6.9 Manipulators
Manipulators are operators that are used to format the data display. The most commonly used
manipulators are ‘endl’ and ‘setw’.
The ‘endl’ manipulators, when used in an output statement , causes a linefeed to be inserted. It
has almost same effect as that of ‘\n’.
e.g.
int m = 7;
cout<< m<<endl;
output screen
7
within the printing zone, to make output justified, ‘setw’ manipulator is used.
The manipulator setw(n) specifies a field width n for printing the value of the variable sum. The
value is right justified within the field as shown below –
out<< setw(5)<<m;
output screen
3 4 5
1. if statement
2. switch statement
if Statement : If statement have three forms
(a) if … else Statement :- It is useable, when we have to performs an action if a condition is True
and we have to perform a different action if the condition is false. The syntax of if…else statement
is:
if ( < conditional expression > )
{
< statement-1 or block-1>;
/ statements to be executed when conditional expression is true.
}
else
{
statement-2 or block-2>;
}
If the <conditional expression> is evaluated to true then the < statement-1 or block-1> (statement
under if ( ) block ) will be executed otherwise the <statement-2 or block-2> (statements under else
block) would be executed. if there exists only one program statement under if( ) block then we may
omit curly braces { }.
#include <iostream>
using namespace std;
int main ()
{
//local variable declaration:
int a = 100;
//check the boolean condition
if( a < 20 )
{
}
cout << "value of a is : " << a << endl;
return 0;
}
a is not less than 20;
value of a is : 100
(b) Simple if statement:- The else part in if … else statement is optional, if we omit the else part then
it becomes simple if statement. This statement is usable, when we have to either perform an action if a
condition is True or skips the action if the condition is false. The syntax of simple if statement is:
if ( < conditional expression > )
{
< statement-1 or block-1>;
/ statements to be executed when conditional expression is true.
}
Here <statement-1 or block-1> will be executed only if <conditional expression > evaluates true. if there
exists only one program statement under if( ) block then curly braces { } may be omitted. Example:
#include <iostream>
{
// local variable declaration: int a=10;
statement-3 ;
statement-n ;
else
statement-m ;
In the above syntax there are ladder of multiple conditions presented by each if( ) , all of these
conditions are mutually exclusive. If one of them would evaluates true then the statement followed that
condition will be executed and all the conditions below it would not be evaluated (checked).
Say suppose if condition-3 gets satisfy (i.e. evaluates true value for the condition), then
statement-3 gets executed and all other conditions below it would be discarded.
If none of the n if ( ) conditions gets satisfied then the last else part always gets executed. It is not
compulsory to add an else at the last of the ladder.
Example:
#include <iostream>
using namespace std;
int main ()
{
local variable declaration: int a = 100;
//check the boolean condition if( a == 10 )
{
//if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
//if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
//if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
The output of above code is:
Value of a is not matching
Exact value of a is : 100
Nested if Statement:- If an if statement is written in the if or else clause of another if statement then it
is known as nested if. Some possible syntax of nested if statements given below: Syntax 1:-
#include <iostream>
using namespace std;
int main ()
{
//local variable declaration: int a = 100;
int b = 200;
//check the boolean condition if( a == 100 )
{
//if condition is true then check the following
if( b == 200 )
{
//if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
The output of above code is:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
break;
case value_2: statement -2;
break;
}
Note: expression/variable should be integer or character type only.
When the switch statement is executed, the expression/variable is evaluated and control is transferred directly
to the statement whose case label value matches the value of expression/ variable. If none of the case label
value matches the value of expression/variable then only the statement following the default will be
executed. If no default statement is there and no match is found then no action take place. In this case control
is transferred to the statement that follows the switch statement.
Example
#include <iostream>
using namespace std;
int main ()
{
//local variable declaration: char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
The output of above code is:
You passed
Your grade is D
Loops Types
A loop statement allows us to execute a statement or group of statements multiple times and following
is the general from of a loop statement in most of the programming languages:
C++ programming language provides the following type of loops to handle looping requirements.
for loop Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while Like a ‘while’ statement, except that it tests the condition at the end of the loop
loop body.
nested loops You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.
for Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.
Syntax:
In for loop, a loop variable is used to control the loop. First initialize this loop variable to
some value, then check whether this variable is less than or greater than counter value. If
statement is true, then loop body is executed and loop variable gets updated . Steps are
repeated till exit condition comes.
Flow diagram
Example:
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << "Hello World\n";
}
return 0;
}
The output of the above code is
Hello World
Hello World
Hello World
Hello World
Hello World
While loop
while loop is also an entry controlled loop. In case of for loop the number of iterations is known beforehand,
i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in
situations where the exact number of iterations of loop is not known beforehand. The loop execution is
terminated on the basis of test condition. A while loop statement repeatedly executes a target
statement as long as a given condition is true.
while (loop_condition)
{
Loop_body
}
Here, statement(s) may be a single statement or a block of statements. The condition
may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram
Example:
#include <iostream>
using namespace std;
int main ()
{
//Local variable declaration: int
a = 10;
//while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl; a+
+;
}
return 0;
}
The output of above code is:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop
do-while loop is an exit-controlled loop i.e. it evaluates its loop_condition at the bottom of the loop after
executing its loop_body statements. It means that a do-while loop always executes at least once. A
do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time. The syntax of a do...while loop in C++ is:
do
{
statement(s);
}
while( condition );
In do-while loop first of all loop_body will be executed and then loop_condition will be evaluates if
loop_condition is true then loop_body will be executed again, When the loop_condition becomes false, the
program control passes to the statement after the loop_body.
Flow Diagram
Example
#include <iostream>
int main ()
do loop execution
do
a = a + 1;
}while( a < 20 );
return 0;