Lesson 1 Language Structures of Oop (C ++ Notes)
Lesson 1 Language Structures of Oop (C ++ Notes)
C ++ TUTORIAL
C++ is a middle-level programming language developed by Bjarne Stroustrup starting
in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.
There are many C++ compilers available which you can use to compile and run above
mentioned program:
• Apple C++. Xcode
• Bloodshed Dev-C++
• Clang C++
• Cygwin (GNU C++)
• Mentor Graphics
• MINGW - "Minimalist GNU for Windows"
• CodeBlocks
• GNU CC source
• IBM C++
• Intel C++
• Microsoft Visual C++
• Oracle C++
• HP C++
It is really impossible to give a complete list of all the available compilers.
Applications of C++ Programming
As mentioned before, C++ is one of the most widely used programming languages. It
has it's presence in almost every area of software development. Some of its
application may include:
• Application Software Development - C++ programming has been used in
developing almost all the major Operating Systems like Windows, Mac OSX and
Linux. Apart from the operating systems, the core part of many browsers like
Mozilla Firefox and Chrome have been written using C++. C++ also has been
used in developing the most popular database system called MySQL.
• Programming Languages Development - C++ has been used extensively in
developing new programming languages like C#, Java, JavaScript, Perl, UNIX’s
C Shell, PHP and Python, and Verilog etc.
• Computation Programming - C++ is the best friends of scientists because of
fast speed and computational efficiencies.
• Games Development - C++ is extremely fast which allows programmers to do
procedural programming for CPU intensive functions and provides greater
control over hardware, because of which it has been widely used in
development of gaming engines.
• Embedded System - C++ is being heavily used in developing Medical and
Engineering Applications like softwares for MRI machines, high-end CAD/CAM
systems etc.
• Device Drivers development
C++ Overview
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form
programming language that supports procedural, object-oriented, and generic
programming.
C++ is regarded as a middle-level language, as it comprises a combination of both
high-level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with
Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Note − A programming language is said to use static typing when type checking is
performed during compile-time as opposed to run-time.
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-
oriented development −
• Encapsulation
• Data hiding
• Inheritance
• Polymorphism
Standard Libraries
Standard C++ consists of three important parts −
• The core language giving all the building blocks including variables, data types
and literals, etc.
• The C++ Standard Library giving a rich set of functions manipulating files,
strings, etc.
• The Standard Template Library (STL) giving a rich set of methods
manipulating data structures, etc.
The ANSI Standard
The ANSI standard is an attempt to ensure that C++ is portable; that code you write
for Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX,
a Windows box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++ compiler
manufacturers support the ANSI standard.
Learning C++
The most important thing while learning C++ is to focus on concepts.
The purpose of learning a programming language is to become a better programmer;
that is, to become more effective at designing and implementing new systems and at
maintaining old ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C,
Smalltalk, etc., in any language. Each style can achieve its aims effectively while
maintaining runtime and space efficiency.
Use of C++
C++ is used by hundreds of thousands of programmers in essentially every application
domain.
C++ is being highly used to write device drivers and other software that rely on direct
manipulation of hardware under realtime constraints.
C++ is widely used for teaching and research because it is clean enough for successful
teaching of basic concepts.
Anyone who has used either an Apple, Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written
in C++.
C++ Environment Setup
Local Environment Setup
If you are still willing to set up your environment for C++, you need to have the following
two softwares on your computer.
Text Editor
This will be used to type your program. Examples of few editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows and vim or vi can be used on windows as well as
Linux, or UNIX.
The files you create with your editor are called source files and for C++ they typically
are named with the extension .cpp, .cp, or .c.
A text editor should be in place to start your C++ programming.
C++ Compiler
This is an actual C++ compiler, which will be used to compile your source code into
final executable program.
Most C++ compilers don't care what extension you give to your source code, but if you
don't specify otherwise, many will use .cpp by default.
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise
you can have compilers either from HP or Solaris if you have the respective Operating
Systems.
Windows Installation
To install GCC at Windows you need to install MinGW. To install MinGW, go to the
MinGW homepage, www.mingw.org, and follow the link to the MinGW download page.
Download the latest version of the MinGW installation program which should be
named MinGW-<version>.exe.
While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils,
and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment
variable so that you can specify these tools on the command line by their simple
names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool,
and several other GNU tools from the Windows command line.
NOTE
We shall install CodeBlocks which will provide us with both the text editor and a compiler for our
programming class
C++ Basic Input/Output
The C++ standard libraries provide an extensive set of input/output capabilities which
we will see in subsequent chapters. This chapter will discuss very basic and most
common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device
like a keyboard, a disk drive, or a network connection etc. to main memory, this is
called input operation and if bytes flow from main memory to a device like a display
screen, a printer, a disk drive, or a network connection, etc., this is called output
operation.
1
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the
standard input stream, the standard output stream, the un-buffered standard error
stream and the buffered standard error stream, respectively.
2
<iomanip>
This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.
3
<fstream>
This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.
The C++ compiler also determines the data type of variable to be output and selects
the appropriate stream insertion operator to display the value. The << operator is
overloaded to output data items of built-in types integer, float, double, strings and
pointer values.
The insertion operator << may be used more than once in a single statement as shown
above and endl is used to add a new-line at the end of the line.
}
When the above code is compiled and executed, it will prompt you to enter a name.
You enter a value and then hit enter to see the following result −
Please enter your name: cplusplus
Your name is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the
appropriate stream extraction operator to extract the value and store it in the given
variables.
The stream extraction operator >> may be used more than once in a single statement.
To request more than one datum you can use the following −
cin >> name >> age;
This will be equivalent to the following two statements −
cin >> name;
cin >> age;
The Standard Error Stream (cerr)
The predefined object cerr is an instance of ostream class. The cerr object is said to
be attached to the standard error device, which is also a display screen but the
object cerr is un-buffered and each stream insertion to cerr causes its output to appear
immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the
following example.
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....
You would not be able to see any difference in cout, cerr and clog with these small
examples, but while writing and executing big programs the difference becomes
obvious. So it is good practice to display error messages using cerr stream and while
displaying other log messages then clog should be used.
C++ Basic Syntax
When we consider a C++ program, it can be defined as a collection of objects that
communicate via invoking (calling) each other's methods (functions).
Let us now briefly look into what a class, object, methods, and instant variables mean.
• Object – the are real life entities e.g a phone, a student, a tree, a car
• Objects have states (attributes) and behaviours.
Example: A dog has states - colour, name, breed as well as behaviours -
wagging, barking, eating.
An object is an instance of a class.
• Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
• The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively 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.
A block is a set of logically connected statements that are surrounded by opening and
closing braces. For example −
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does
not matter where you put a statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any
other user-defined item.
The general rules for naming identifiers are similar to those of naming
variables. They include:
a) Identifier can contain letters, digits and underscores
b) Identifier must begin with a letter or an underscore (_)
c) Identifier are case sensitive (myVar and myvar are different Identifier)
d) Identifier cannot contain whitespaces or special characters like !, #, %, etc.
e) Reserved words (like C++ keywords, such as int) cannot be used as Identifier
Trigraph Replacement
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
All the compilers do not support trigraphs and they are not advised to be used because
of their confusing nature.
Whitespace in C++
A line containing only whitespace, possibly with a comment, is known as a blank line,
and C++ compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables
the compiler to identify where one element in a statement, such as int, ends and the
next element begins.
Statement 1
int age;
In the above statement there must be at least one whitespace character (usually a
space) between int and age for the compiler to be able to distinguish them.
Statement 2
fruit = apples + oranges; // Get the total fruit
In the above statement 2, no whitespace characters are necessary between fruit and
=, or between = and apples, although you are free to include some if you wish for
readability purpose.
Comments in C++
Program comments are explanatory statements that you can include in the C++ code.
These comments help anyone reading the source code. All programming languages
allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example −
/* This is a comment */
*/
C++ Data Types
While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations (storage
containers) to store values. This means that when you create a variable you reserve
some space in memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in
the reserved memory.
Table below shows the various data types in c++
Primitive/ Basic/ Built-in Data Types
Following table lists down seven basic C++ data types –
int Integer 2 or 4
float Floating-point 4
char Character 1
bool Boolean 1
void Empty 0
• signed
• unsigned
• long
• short
The modifiers signed, unsigned, long, and short can be applied to integer base
types. In addition, signed and unsigned can be applied to char, and long can be
applied to double.
The modifiers signed and unsigned can also be used as prefix
to long or short modifiers.
For example, unsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You
can simply use the word unsigned, short, or long, without int. It automatically
implies int.
For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
program to show difference interpretation between signed and unsigned integer
modifiers
#include <iostream>
using namespace std;
/* This program shows the difference between signed and unsigned integers.*/
int main() {
short int i; // a signed short integer
short unsigned int j; // an unsigned short integer
j = 50000;
i = j;
cout << i << "\t' " << j;
return 0;
}
When this program is run, following is the output −
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short unsigned
integer is interpreted as -15,536 by a short.
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in
such type of variables.
Float 4bytes
Double 8bytes
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on your
computer.
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and <<
operator is being used to pass multiple values out to the screen. We are also
using sizeof() operator to get size of various data types.
When the above code is compiled and executed, it produces the following result which
can vary from machine to machine −
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
#include <limits>
int main() {
std::cout << "Unsigned Int Min " << std::numeric_limits<unsigned int>::min() << endl;
std::cout << "Unsigned Int Max " << std::numeric_limits<unsigned int>::max() << endl;
std::cout << "Long Int Min " << std::numeric_limits<long int>::min() << endl;
std::cout << "Long Int Max " << std::numeric_limits<long int>::max() << endl;
std::cout << "Unsigned Long Int Min " << std::numeric_limits<unsigned long int>::min() <<endl;
std::cout << "Unsigned Long Int Max " << std::numeric_limits<unsigned long int>::max() << endl;
Other types of data types like user defined and derived data types to be covered later
typedef Declarations
You can create a new name for an existing type using typedef.
For example, the following tells the compiler that feet is another name for int :-
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called
distance:-
feet distance;
C++ Variable Types
A variable provides us with named storage space in computer memory that our
programs can manipulate. Each variable in C++ has a specific type, which determines
the size and layout of the variable's memory; the range of values that can be stored
within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive.
Note: Variables are created using the various data types in c++
1
Bool - Stores either value true or false.
2
Char - Typically a single octet (one byte). This is an integer type.
3
Int - The most natural size of integer for the machine.
4
float - A single-precision floating point value.
5
Double - A double-precision floating point value.
6
Void - Represents the absence of type.
7
wchar_t - A wide character type.
C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.
Variable Definition in C++
This section covers how to define, declare and use various types of variables.
A variable definition tells the compiler where and how much storage to create for the
variable.
A variable definition specifies a data type, and contains a list of one or more variables
of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double,
bool or any user-defined object, etc., and variable_list may consist of one or more
identifier names separated by commas.
The line int i, j, k; both declares and defines the variables i, j and k; which instructs
the compiler to create variables named i, j and k of type int.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables
is undefined.
Variable Declaration in C++
A variable declaration provides assurance to the compiler that there is one variable
existing with the given type and name so that compiler proceed for further compilation
without needing complete detail about the variable. A variable declaration has its
meaning at the time of compilation only, compiler needs actual variable definition at
the time of linking of the program.
A variable declaration is useful when you are using multiple files and you define your
variable in one of the files which will be available at the time of linking of the program.
You will use extern keyword to declare a variable at any place. Though you can
declare a variable multiple times in your C++ program, but it can be defined only once
in a file, a function or a block of code.
Example: A program that accepts input of two numbers, multiplies them and
displays the results
#include <iostream>
using namespace std;
int main() {
int first_number, second_number, product;
cout << "Enter first number: ";
cin >> first_number;
cout << "Enter second number: ";
cin >> second_number;
product = first_number * second_number;
// prints product
cout << first_number << " * " << second_number << " = " << product;
return 0;
}
Example
Here a variable has been declared at the top, but it has been defined inside the main
function:
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
Assignments
I. Write a C++ program to calculate area and circumference of a circle. The
program should prompt the user to enter the required parameters for the
calculations
II. Write a C++ program to calculate area and perimeter of a rectangle
Lvalues and Rvalues
There are two kinds of expressions in C++
• lvalue − Expressions that refer to a memory location is called "lvalue"
expression. An lvalue may appear as either the left-hand or right-hand side of
an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address
in memory. An rvalue is an expression that cannot have a value assigned to it
which means an rvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so may not be assigned and can not appear on the
left-hand side. Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-time error −
10 = 20;
Variable Scope in C++
A scope is a region of the program where a variable can be declared.
Broadly there are three places, where variables can be declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.
Local Variables
Variables that are declared inside a function or block are local variables. They can be
used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own.
Global Variables
Global variables are defined outside of all the functions, usually on top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.
Following is the example using global and local variables:
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local
variable inside a function will take preference. For example:
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Output: 10
Int 0
Char '\0'
Float 0
Double 0
Pointer NULL
Integer Literals
An integer literal 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.
Here are some examples of integer literals −
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals −
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals 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.
Here are some examples of floating-point literals −
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords −
• A value of true representing true.
• A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.
Character Literals
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).
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
Kenya
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"
1
Const
Objects of type const cannot be changed by your program during execution.
2
Volatile
The modifier volatile tells the compiler that a variable's value may be changed in
ways not explicitly specified by the program.
3
Restrict
A pointer qualified by restrict is initially the only means by which the object it
points to can be accessed.
Enumerated Types
Here, the enum-name is the enumeration's type name. The list of names is comma
separated.
Example
enum color { red, green, blue };
By default, the value of the first name is 0, the second name has the value 1, and the
third has the value 2, and so on. But you can give a name, a specific value by adding
an initializer. For example, in the following enumeration, green will have the value 5.
enum color { red, green = 5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one
that precedes it
Example
enum season { spring, summer, autumn, winter };
Example
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
.
To use the enumerated values in a program you must create variables of enum
type
Example in a program using enumerated data type
#include <iostream>
using namespace std;
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Output
Day 4
Assignment
Write a C++ program to implement enumerated data type of your choice
Storage Classes in C++
A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C++ Program. These specifiers precede the type that they modify. There are
following storage classes, which can be used in a C++ Program
• auto
• register
• static
• extern
• mutable
{
int mount;
auto int month; //
}
The example above defines two variables with the same storage class, auto can only
be used within functions, i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the variable
will be stored in a register. It means that it MIGHT be stored in a register depending
on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows them
to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C++, when static is used on a class data member, it causes only one copy of that
member to be shared by all objects of its class.
#include <iostream>
// Function declaration
void func(void);
static int count = 10; /* Global variable */
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
Here, extern keyword is being used to declare count in another file. Now compile these
two files as follows −
$g++ main.cpp support.cpp -o write
This will produce write executable program, try to execute write and check the result
as follows −
$./write
5
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then –
== Checks if the values of two operands are equal or not, if (A == B) is not true.
yes then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value (A < B) is true.
of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand, if yes then condition becomes
true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then –
&& Called Logical AND operator. If both the operands are non- (A && B) is false.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is true.
state of its operand. If a condition is true, then Logical NOT
operator will make false.
Bitwise Operators
Bitwise Operator
Bitwise operator works on bits and perform bit-by-bit operation.
The truth tables for &, |, and ^ are as follows –
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
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
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 AND Operator copies a bit to the (A & B) will give 12 which is
result if it exists in both operands. 0000 1100
^ Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
in one operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100
and has the effect of 'flipping' bits. 0011 in 2's complement form
due to a signed binary number.
Assignment Operators
There are following assignment operators supported by C++ language −
1
Sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.
2
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.
3
,
Comma operator causes a sequence of operations to be performed. The value of
the entire comma expression is the value of the last expression of the comma-
separated list.
4
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes,
structures, and unions.
5
Cast
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.
6
&
Pointer operator & returns the address of a variable. For example &a; will give
actual address of the variable.
7
*
Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.
Operators Precedence in C++
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated.
Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
The kinds of control flow statements supported by different languages vary, but can
be categorized by their effect.
o continuation at a different statement i.e. unconditional jump e.g. GoTo
statements
o executing a set of statements only if some condition is met i.e. choice
o executing a set of statements zero or more times, until some condition is met
i.e. loop
o executing a set of distant statements, after which the flow of control usually
returns e.g. Subroutines/ functions
Program statements are executed in the sequence in which they appear in the
program.
#include <iostream>
using namespace std;
int main()
{
Cout<<"hello world” ;
return (0);
}
1 if statement
An ‘if’ statement consists of a boolean expression followed by one or more
statements.
2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes
when the Boolean expression is false.
3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of
values.
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10
if...else statement
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false.
Syntax
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100
Assignments
Write a C++ program that accepts input of a number and determines if the
number is an even number or an odd number using IF..ELSE statement
Write a C++ Program to check whether a person is eligible to vote or not. Only
a person who is 18 years and above can vote.
Use if else statement
Syntax
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true
} else {
// executes when the none of the above condition is true.
}
Flowchart
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;
}
When the above code is compiled and executed, it produces the following result −
Value of a is not matching
Exact value of a is : 100
Assignments
Write a C++ program that accepts input of three numbers. The program then
determines the largest between the three numbers and displays the results.
Use the IF..ELSE statement
The below table is used to grade students in KBC secondary school. Write a
C++ program that can be used to implement the logic of grading the students.
Use the if..else ladder
No Marks Grade
Above 90 A
80-89 B
70-79 C
60-69 D
50-59 E
Below 49 F
switch statement
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
Assignment
The below table is used to grade students in KBC secondary school. Write a
C++ program that can be used to implement the logic of grading the students.
Use the if..else ladder
No Marks Grade
Above 90 A
80-89 B
70-79 C
60-69 D
50-59 E
Below 49 F
nested if statements
It is always legal to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).
Syntax
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#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;
}
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
nested switch statements
It is possible to have a switch as part of the statement sequence of an outer switch.
Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise.
C++ specifies that at least 256 levels of nesting be allowed for switch statements.
Syntax
switch(ch1) {
case 'A':
cout << "This A is part of outer switch";
switch(ch2) {
case 'A':
cout << "This A is part of inner switch";
break;
case 'B': // ...
}
break;
case 'B': // ...
}
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
int b = 200;
switch(a) {
case 100:
cout << "This is part of outer switch" << endl;
switch(b) {
case 200:
cout << "This is part of inner switch" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
This would produce the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
The ? : Operator (conditional operator)
Conditional operator is also known as Ternary Operator
It can be be used to replace if...else statements.
A ternary operator evaluates the test condition and executes a block of code based
on the result of the condition.
Its syntax is
condition ? expression1 : expression2;
Here, condition is evaluated and
if condition is true, expression1 is executed.
And, if condition is false, expression2 is executed.
The ternary operator takes 3 operands (condition, expression1 and expression2).
Hence, the name ternary operator.
Output 1
Enter your marks: 80
You passed the exam.
Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true.
Hence, the first expression "passed" is assigned to result.
Output 2
Enter your marks: 39.5
You failed the exam.
Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates
to false. Hence, the second expression "failed" is assigned to result
C++ Loop Types
There may be a situation, when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
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.
1 while loop
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop
body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
while loop
A while loop statement repeatedly executes a target statement as long as a given
condition is true.
Syntax
while(condition) {
statement(s);
}
Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement
after the while loop will be executed.
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;
}
When the above code is compiled and executed, it produces the following result −
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
Assignments
I. Write a C++ Program that prints all natural numbers from 1 to 20 using a
while loop
II. Write a C++ to Print table for the given number using while loop
III. Write a C++ Program to calculate the sum of first n natural numbers
using while loop
IV. Write a C++ Program to display all even numbers from 1 to n using while
loop
V. Write a C++ Program to calculate sum of all even numbers from 1 to n
using while loop
VI. Using do while loop write a C++ program that can generate the output below
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop −
• The init step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement
here, as long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the for loop.
• After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement can be left blank, as long as a
semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the for loop terminates.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
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
Assignments
I. Write a C++ Program that prints all natural numbers from 1 to 20 using a
for loop
II. Write a C++ to Print table for the given number using for loop
III. Write a C++ Program to calculate the sum of first n natural numbers
using for loop
IV. Write a C++ Program to display all even numbers from 1 to n using for
loop
V. Write a C++ Program to calculate sum of all even numbers from 1 to n
using for loop
do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
Syntax
do {
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again. This process repeats until the given condition becomes false.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
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
Assignments
I. Write a C++ Program that prints all natural numbers from 1 to 20 using a
do..while loop
II. Write a C++ to Print table for the given number using do..while loop
III. Write a C++ Program to calculate the sum of first n natural numbers
using do..while loop
IV. Write a C++ Program to display all even numbers from 1 to n using
do..while loop
V. Write a C++ Program to calculate sum of all even numbers from 1 to n
using do..while loop
nested loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
The syntax for a nested for loop statement in C++ is as follows −
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows −
do {
statement(s); // you can put more statements.
do {
statement(s);
} while( condition );
} while( condition );
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <iostream>
using namespace std;
int main () {
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) cout << i << " is prime\n";
}
return 0;
}
This would produce the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
#include <iostream>
using namespace std;
int main(){
int i, j;
for (i=1; i<=5;i++)
{
for (j=1;j<=5;j++)
{
cout<<"*";
}
cout<<" ";
cout<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main(){
int i, j;
for (i=1; i<=5;i++)
{
for (j=1;j<=i;j++)
{
cout<<"*";
}
cout<<" ";
cout<<endl;
}
return 0;
}
Assignments
Write a C++ program to display the below pattern using for loop
*****
****
***
**
*
Write a C++ program to display the below pattern using for loop
1
12
123
1234
12345
123456
Write a C++ program to display the below pattern using for loop
1
22
333
4444
55555
Write a C++ program to display the below pattern using for loop
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15 16
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.
1 break statement
Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.
break statement
The break statement has the following two usages in C++
• When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the
loop.
• It can be used to terminate a case in the switch statement
If you are using nested loops (i.e., one loop inside another loop), the break statement
will stop the execution of the innermost loop and start executing the next line of code
after the block.
Syntax
break;
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15) {
// terminate the loop
break;
}
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue statement
The continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, program control passes to the
conditional tests.
Syntax
The syntax of a continue statement in C++ is −
continue;
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
if( a == 15) {
// skip the iteration.
a = a + 1;
continue;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement
A goto statement provides an unconditional jump from the goto to a labeled statement
in the same function.
NOTE − Use of goto statement is highly discouraged because it makes difficult to
trace the control flow of a program, making the program hard to understand and hard
to modify. Any program that uses a goto can be rewritten so that it doesn't need the
goto.
Syntax
The syntax of a goto statement in C++ is −
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is
any statement that is preceded by an identifier followed by a colon (:).
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do {
if( a == 15) {
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Declaring Arrays
Specify the type of the elements and the number of elements required by an array
Type array-name [array-size]
This is called a single dimensional array
The array-size must be an integer constant greater than zero
Type can be any valid C++ data type
e.g. to declare a 10 element array called balance of type double use the statement below
Double balance [10];
This array called balance can hold up to 10 double numbers
Initializing arrays
You can initialize an array in C++ either one by one or using a single statement as follows:
Double balance [5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces {} cannot be larger than the number of elements that
we declare for the array between square brackets []
If you omit the size of the array, an array just big enough to hold the initialization is created.
The below statement will create exactly the same array as you did in the previous example
Double balance []={1000,0, 2.0, 3.4, 7.0, 50.0};
typeArray element
name size
Element 35 33 42 10 14 19 27 44 26 31
Index 0 1 2 3 4 5 6 7 8 9
Index starts with zero (called the base index) and progresses from 0 to n-1 (where n is the size
of the array)
Array length is 10 which means it can store 10 elements
Each element can be accessed via its index e.g., we can fetch an element at index 5 as 19
Examples: a c program that stores three elements in an array and displays them
#include<iostream>
using namespace std;
int main()
{
int marks [3];
marks [0]=6;
marks [1]=85;
marks [2]=66;
cout<< marks[0] << marks[1] <<marks[2];
return 0;
}
Examples: a c program that accepts three inputs from the user and stores them in an
array and then displays the values stored in the array
#include<iostream>
using namespace std;
int main()
{
int marks [3];
cout<<"enter three values";
cin>> marks[3-1]>> marks[3-2]>> marks[3-3];
cout<<"printing the values";
cout<< marks[0] << marks[1] <<marks[2];
return 0;
}
Using loops in arrays
Examples: a program that displays elements of an array using a for loop
#include<iostream>
using namespace std;
int main()
{
int numbers[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i;
for (i=0; i<10; i++)
{
cout<< numbers[i];
}
return 0;
}
Examples: Program to take 5 values from the user and store them in an array using a
for loop. The program then prints the elements in the array
#include<iostream>
using namespace std;
int main()
{
int values[5];
int i;
cout<<"enter five value";
//taking input and storing in an array
for (i=0;i<5; i++)
{
cin>> values[i];
}
cout<<"display integers";
//printing elements of an array
for (i=0; i<5; i++)
{
cout<< values[i];
}
return 0;
}
Assignments
I. Write a C program that accepts 5 integers, and stores them in an array and
displays the number in reserve order
II. C program that prompts the user to enter weight of five people and stores the
values in an array. The program then computes and outputs the total weight
III. Write a program in C language that stores the elements in the array below. The
program then computes and displays the average of the elements
IV. 30 V. 7 VI. 50 VII. 85 VIII. 41 IX. 90
X. Write a C program that accepts 5 numbers and stores then in an array and then
prints the elements stored in the array
XI. Program to find average of n numbers using arrays
Multi-dimensional Arrays
C++ allows multidimensional arrays. Here is the general form of a multidimensional
array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer
array −
int threedim[5][10][4];
Two-Dimensional Arrays
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size x, y, you would write something as
follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be thought of as a table, which will have x number of
rows and y number of columns.
A 2-dimensional array a, which contains three rows and four columns can be shown
as below –
Int a [3][4];
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example –
The above statement will take 4th element from the 3rd row of the array.
#include<iostream>
using namespace std;
int main()
{
int a[2][3]={10, 20, 30,100, 25, 55};
cout<< a[0][0];
cout<<" ";
cout<< a[0][1];
cout<<" ";
cout<< a[0][2];
cout<<endl;
cout<< a[1][0];
cout<<" ";
cout<< a[1][1];
cout<<" ";
cout<< a[1][2];
return 0;
}
Example 2
Program that accepts input of values, stored them in an array and displays the
stored values. The program also calculates the sum of the values stored in the
array and displays the results.
#include<iostream>
using namespace std;
int main()
{
int a[2][3];
int sum=0;
int i, j;
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
cout<<"enter a number";
cin>> a[i][j];
}}
for(i=0; i<2; i++)
{
for(j=0; j<3; j++)
{
cout<< a[i][j];
cout<<" ";
sum=sum+a[i][j];
}
cout<<endl;
}
cout<<" sum =%d", sum;
return 0;}
C++ Strings
C++ provides following two types of string representations −
If you follow the rule of array initialization, then you can write the above statement as
follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the
array.
Example
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
Output
Greeting message: Hello
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the
name of the pointer variable. The asterisk (*) you used to declare a pointer is the
same asterisk that you use for multiplication. However, in this statement the asterisk
is being used to designate a variable as a pointer.
Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data type
of the variable or constant that the pointer points to.
This is done by using unary operator * that returns the value of the variable located
at the address specified by its operand.
Following example makes use of these operations −
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Output
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
C++ Data Structures (struct)
C++ arrays allow you to define variables that combine several data items of the same
kind. Structure is user defined data type which allows you to combine data items of
different kinds.
Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book −
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member, for your program. The format of the
struct statement is this −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of
the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional.
Here is the way you would declare the Book structure −
struct Books { struct Books {
char title[50]; char title[50];
char author[50]; OR char author[50];
char subject[100]; char subject[100];
int book_id; int book_id;
} book; };
[one or more variables of struct type]
Assignment
As a programming student, you are required to store the following details in program.
Declare the most appropriate data structure in a C language to store them
Name, Date of Birth, height, weight, sub-county
The typedef Keyword
Using the typedef keyword to create structures
For example −
typedef struct {
char title[50];
char author[50];
char subject[100];
int book_id;
} Books;
Now, you can use Books directly to define variables of Books type without using struct
keyword. Following is the example −
Books Book1, Book2;
You can use typedef keyword for non-structs as well as follows −
typedef long int *pint32;
pint32 x, y, z;
1
double cos(double);
This function takes an angle (as a double) and returns the cosine.
2
double sin(double);
This function takes an angle (as a double) and returns the sine.
3
double tan(double);
This function takes an angle (as a double) and returns the tangent.
4
double log(double);
This function takes a number and returns the natural log of that
number.
5
double pow(double, double);
The first is a number you wish to raise and the second is the power
you wish to raise it to
6
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it
will return you the length of the hypotenuse.
7
double sqrt(double);
You pass this function a number and it gives you the square root.
8
int abs(int);
This function returns the absolute value of an integer that is passed
to it.
9
double fabs(double);
This function returns the absolute value of any decimal number
passed to it.
10
double floor(double);
Finds the integer which is less than or equal to the argument passed
to it.
Types of functions
• Built in functions
• User defined functions
Built-In Functions
The C++ standard library provides numerous built-in functions that your program can
call. For example,
function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many more
functions,
function sqrt() to calculate the square root of a number,
function pow() to calculate the power of a number.
To use built-in function you must include the library/ header file where the specified
function is found
Output
Enter base and exponent respectively: 2.3
4.5
2.3^4.5 = 42.44
Output
Enter a number: 23.4
Square root of 23.40 = 4.84
Assignment
Write a C++ Program that accepts input of first name and second name of a
students separately and display the two names joined together
User defined functions
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
Example
Function definition for a user defined function called max() that takes two
parameters num1 and num2 and return the biggest of both −
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
so following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the
top of the file calling the function.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function.
A called function performs defined task and when it’s return statement is executed or
when its function-ending closing brace is reached, it returns program control back to
the main program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
For example:
#include <iostream>
using namespace std;
// function definition returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
Output
Hello there!
Example 2: using a function to display values (this function does not return a
value)
// program to print a text
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Output
The int number is 5
The double number is 5.5
int main() {
int sum;
// calling the function and storing the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Output
100 + 78 = 178
Function Prototype
In C++, the code of function declaration should be before the function call. However,
if we want to define a function after the function call, we need to use the function
prototype.
This provides the compiler with information about the function name and its
parameters. That's why we can use the code to call a function before the function
has been defined.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
int main() {
int sum;
// calling the function and storing the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
// function definition
int add(int a, int b) {
return (a + b);
}
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here,
the function is defined after the function call.
That's why we have used a function prototype in this example.
Example 2
#include <iostream>
using namespace std;
// function declaration (function prototype)
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Vet:=max(a, b);
1 Call by Value
This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have
no effect on the argument.
2 Call by Reference
This method copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.
function call by value
The call by value method of passing arguments to a function copies the actual value
of an argument into the formal parameter of the function. In this case, changes made
to the parameter inside the function have no effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
// function definition to swap the values.
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Calling the function swap() by passing actual values as in the following example −
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed
inside the function.
function call by reference
The call by reference method of passing arguments to a function copies the
reference of an argument into the formal parameter. Inside the function, the reference
is used to access the actual argument used in the call. This means that changes made
to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like
any other value. So accordingly you need to declare the function parameters as
reference types as in the following function swap(), which exchanges the values of the
two integer variables pointed to by its arguments.
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
For now, let us call the function swap() by passing values by reference as in the
following example −
#include <iostream>
using namespace std;
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
Actual and formal arguments will be Actual and formal arguments will be
created in created in
different memory location same memory location.
C++ References
A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialized with a variable, either the variable name or the reference
name may be used to refer to the variable.
References vs Pointers
References are often confused with pointers but there are three major differences
between references and pointers are −
• You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
• Once a reference is initialized to an object, it cannot be changed to refer to
another object. Pointers can be pointed to another object at any time.
• A reference must be initialized when it is created. Pointers can be initialized at
any time.
References are usually used for function argument lists and function return values.
So following are two important subjects related to C++ references which should be
clear to a C++ programmer –
1 References as Parameters
C++ supports passing references as function parameter more safely than
parameters.
1
time_t time(time_t *time);
This returns the current calendar time of the system in number of seconds
elapsed since January 1, 1970. If the system has no time, .1 is returned.
2
char *ctime(const time_t *time);
This returns a pointer to a string of the form day month year
hours:minutes:seconds year\n\0.
3
struct tm *localtime(const time_t *time);
This returns a pointer to the tm structure representing local time.
4
clock_t clock(void);
This returns a value that approximates the amount of time the calling program
has been running. A value of .1 is returned if the time is not available.
5
char * asctime ( const struct tm * time );
This returns a pointer to a string that contains the information stored in the
structure pointed to by time converted into the form: day month date
hours:minutes:seconds year\n\0
6
struct tm *gmtime(const time_t *time);
This returns a pointer to the time in the form of a tm structure. The time is
represented in Coordinated Universal Time (UTC), which is essentially
Greenwich Mean Time (GMT).
7
time_t mktime(struct tm *time);
This returns the calendar-time equivalent of the time found in the structure pointed
to by time.
8
double difftime ( time_t time2, time_t time1 );
This function calculates the difference in seconds between time1 and time2.
9
size_t strftime();
This function can be used to format date and time in a specific format.
The UTC date and time is: Sun Jan 9 03:07:41 2011
Format Time using struct tm
The tm structure is very important while working with date and time in either C or C++.
This structure holds the date and time in the form of a C structure as mentioned above.
Most of the time related functions makes use of tm structure. Following is an example
which makes use of various date and time related functions and tm structure −
While using structure in this chapter, I'm making an assumption that you have basic
understanding on C structure and how to access structure members using arrow ->
operator.
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
cout << "Number of sec since January 1,1970 is:: " << now << endl;
tm *ltm = localtime(&now);
// print various components of tm structure.
cout << "Year:" << 1900 + ltm->tm_year<<endl;
cout << "Month: "<< 1 + ltm->tm_mon<< endl;
cout << "Day: "<< ltm->tm_mday << endl;
cout << "Time: "<< 5+ltm->tm_hour << ":";
cout << 30+ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
}
When the above code is compiled and executed, it produces the following result −
Number of sec since January 1,1970 is:: 1588485717
Year:2020
Month: 5
Day: 3
Time: 11:31:57
return 0;
}
When the above code is compiled and executed, it produces the following result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989