Programming in C++
Programming in C++
Programming in C++
There are 1000s of good reasons to learn C++ Programming. But one thing for sure, to learn
any programming language, not only C++, you just need to code, and code and finally code
until you become an expert.
Hello World using C++
Just to give you a little excitement about C++ programming, I'm going to give you a small
conventional C++ Hello World program, C++ is a superset of C programming with
additional implementation of object-oriented concepts.
#include <iostream>
using namespace std;
It is really impossible to give a complete list of all the available compilers. The C++ world is
just too large and too much new is happening.
This list goes on, there are various areas where software developers are happily using C++ to
provide great software. I highly recommend you to learn C++ and contribute great software
to the community.
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.
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 real time 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++.
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 the
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.
If you have installed GCC, then it should print a message such as the following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed
instructions available at https://gcc.gnu.org/install/
Mac OS X Installation
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development
environment from Apple's website and follow the simple installation instructions.
Xcode is currently available at developer.apple.com/technologies/tools/.
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.
When we consider a C++ program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what a class,
object, methods, and instance variables mean.
● Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating. An object is an instance of a
class.
● Class − A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
● Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
● 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.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing file
hello.cpp.
You can compile C/C++ programs using makefile.
Semicolons and Blocks in C++
In C++, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
x = y;
y = y + 1;
add(x, y);
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++ Identifies
A C++ identifier is a name used to identify a variable, function, class, module, or any other
user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a
case-sensitive programming language. Thus, Manpower and manpower are two different
identifiers in C++.
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be used
as constant or variable or any other identifier names.
Trigraphs
A few characters have an alternative representation, called a trigraph sequence. A trigraph is
a three-character sequence that represents a single character and the sequence always starts
with two question marks.
Trigraphs are expanded anywhere they appear, including within string literals and character
literals, in comments, and in preprocessor directives.
Following are most frequently used trigraph sequences −
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, newlines 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.
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 */
A comment can also start with //, extending to the end of the line. For example −
#include <iostream>
using namespace std;
main() {
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable
will produce the following result −
Hello World
*/
While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations 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.
Primitive Built-in Types
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
Type Keyword
Boolean bool
Character char
Integer int
Valueless void
Several of the basic types can be modified using one or more of these type modifiers −
● signed
● unsigned
● short
● long
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.
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 an 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
typedef Declarations
You can create a new name for an existing type using typedef. Following is the simple
syntax to define a new type using typedef −
typedef type newname;
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;
Enumerated Types
An enumerated type declares an optional type name and a set of zero or more identifiers that
can be used as values of the type. Each enumerator is a constant whose type is the
enumeration.
Creating an enumeration requires the use of the keyword enum. The general form of an
enumeration type is −
enum enum-name { list of names } var-list;
Here, the enum-name is the enumeration's type name. The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the
variable c of type color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = 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.
A variable provides us with named storage 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 −
There are following basic types of variable in C++
1 bool
2 Char
3 int
4 float
5 double
6 void
Represents the absence of type.
7 wchar_t
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.
Following section will cover how to define, declare and use various types of variables.
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.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Example
Try the following example where 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;
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
Same concept applies on function declaration where you provide a function name at the time
of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
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;
A scope is a region of the program and broadly speaking 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.
We will learn what is a function and it's parameter in subsequent chapters. Here let us
explain what are local and 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. Following is the example using local variables −
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
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;
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;
}
When the above code is compiled and executed, it produces the following result −
10
int 0
char '\0'
float 0
double 0
pointer NULL
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). 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"
Defining Constants
There are two simple ways in C++ to define constants −
● Using #define preprocessor.
● Using const keyword.
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
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 a 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;
To understand the difference between the way signed and unsigned integer modifiers are
interpreted by C++, you should run the following short program −
#include <iostream>
using namespace std;
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
1 const
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. Only C99 adds a new type qualifier called restrict.
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
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Try the following example to understand all the arithmetic operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
# include <iostream>
u sing namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl
;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 5 - Value of c is :1
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand,
if yes then condition becomes true.
Try the following example to understand all the relational operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}
if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than \ or equal to b" << endl ;
}
if( b >= a ) {
cout << "Line 5 - b is either greater than \ or equal to b" << endl ;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Operat Description Example
or
Try the following example to understand all the logical operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
#include <iostream>
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
}
if(a || b) {
}
a = 0;
b = 10;
if(a && b) {
} else {
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows −
p q p & q p | q p ^ q
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 −
Try the following example to understand all the bitwise operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
#include <iostream>
using namespace std;
main() {
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100
^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
it is set in one operand but not both. 0001
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100
unary and has the effect of 'flipping' 0011 in 2's complement form due to a
bits. signed binary number.
Assignment Operators
There are following assignment operators supported by C++ language −
Try the following example to understand all the assignment operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
#include <iostream>
main() {
int a = 21;
int c ;
c= a;
c += a;
c -= a;
c *= a;
c /= a;
c = 200;
c %= a;
c <<= 2;
c >>= 2;
c &= 2;
c ^= 2;
c |= 2;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Try the following example to understand operators precedence concept available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this
program.
Check the simple difference with and without parenthesis. This will produce different results
because (), /, * and + have different precedence. Higher precedence operators will be
evaluated first −
Live Demo
#include <iostream>
using namespace std;
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50
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 form 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
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.
A while loop statement repeatedly executes a target statement as long as a given condition is
true.
Syntax
The syntax of a while loop in C++ is −
while(condition) {
statement(s);
}
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
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.
Examp
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
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
The syntax of a for loop in C++ is −
for ( init; condition; increment ) {
statement(s);
}
Flow Diagram
Example
Live Demo
#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
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
The syntax of a do...while loop in C++ is −
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
Live Demo
#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
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
Syntax
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.
}
} while( condition );
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#include <iostream>
using namespace std;
int main () {
int i, j;
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
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.
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
The syntax of a break statement in C++ is −
break;
Flow Diagram
Example
#include <iostream>
int main () {
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
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
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
Live Demo
#include <iostream>
int main () {
int a = 10;
// do loop execution
do {
if( a == 15) {
a = a + 1;
continue;
}
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
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
Live Demo
#include <iostream>
int main () {
int a = 10;
// do loop execution
LOOP:do {
if( a == 15) {
a = a + 1;
goto LOOP;
}
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
One good use of goto is to exit from a deeply nested routine. For example, consider the
following code fragment −
for(...) {
for(...) {
while(...) {
.
.
.
}
}
}
stop:
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the ‘for
(;;)’ construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −
C++ programming language provides following types of decision making statements.
1 if statement
2 if...else statement
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
Syntax
The syntax of an if statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
}
If the boolean expression evaluates to true, then the block of code inside the if statement will
be executed. If boolean expression evaluates to false, then the first set of code after the end
of the if statement (after the closing curly brace) will be executed.
Flow Diagram
Example
Live Demo
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 10;
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
1. // Program to print positive number entered by the user
2. // If user enters negative number, it is skipped
3.
4. #include <iostream>
5. using namespace std;
6.
7. int main()
8. {
9. int number;
10. cout << "Enter an integer: ";
11. cin >> number;
12.
13. // checks if the number is positive
14. if ( number > 0)
15. {
16. cout << "You entered a positive integer: " << number << endl;
17. }
18.
19. cout << "This statement is always executed.";
20. return 0;
21.
22. }
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is −
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
Live Demo
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
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
Syntax
The syntax of an if...else if...else statement in C++ is −
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.
}
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
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
1. // Program to check whether an integer is positive, negative or zero
2.
3. #include <iostream>
4. using namespace std;
5.
6. int main()
7. {
8. int number;
9. cout << "Enter an integer: ";
10. cin >> number;
11.
12. if ( number > 0)
13. {
14. cout << "You entered a positive integer: " << number << endl;
15. }
16. else if (number < 0)
17. {
18. cout<<"You entered a negative integer: " << number << endl;
19. }
20. else
21. {
22. cout << "You entered 0." << endl;
23. }
24.
25. cout << "This line is always printed.";
26. return 0;
27. }
Output
Enter an integer: 0
You entered 0.
This line is always printed.
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
The syntax for a switch statement in C++ is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
default : //Optional
statement(s);
}
Flow Diagram
Example
#include <iostream>
int main () {
switch(grade) {
case 'A' :
break;
case 'B' :
case 'C' :
break;
case 'D' :
break;
case 'F' :
break;
default :
}
cout << "Your grade is " << grade << endl;
return 0;
}
This would produce the following result −
You passed
Your grade is D
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
The syntax for a nested switch statement is as follows −
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
We have covered conditional operator “? :” in previous chapter which can be used to replace
if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression.
A function is a group of statements that together perform a task. Every C++ program has at
least one function, which is the main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
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.
A function is known with various names like a method or a subroutine or procedure etc.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −
● Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
● Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
● Parameters − A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
● Function Body − The function body contains a collection of statements that define
what the function does.
Example
Following is the source code for a function called max(). This function takes two parameters
num1 and num2 and return the biggest of both −
// function returning the max between two numbers
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 declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
}
I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function −
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 Pointer
This method copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the argument.
3 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.
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;
return;
}
Now, let us call 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;
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.
The call by pointer method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address 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 pointer, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer 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;
}
To check the more detail about C++ pointers, kindly check C++ Pointers chapter.
For now, let us call the function swap() by passing values by pointer 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;
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 :200
After swap, value of b :100
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 declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
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 :200
After swap, value of b :100
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.
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
C++ program to add two integers. Make a function add() to add integers and display
sum in main() function.
1. #include <iostream>
2. using namespace std;
3.
4. // Function prototype (declaration)
5. int add(int, int);
6.
7. int main()
8. {
9. int num1, num2, sum;
10. cout<<"Enters two numbers to add: ";
11. cin >> num1 >> num2;
12.
13. // Function call
14. sum = add(num1, num2);
15. cout << "Sum = " << sum;
16. return 0;
17. }
18.
19. // Function definition
20. int add(int a, int b)
21. {
22. int add;
23. add = a + b;
24.
25. // Return statement
26. return add;
27. }
Output
To print all prime numbers between two integers, checkPrimeNumber() function is created.
This function checks whether a number is prime or not.
If the user enters larger number first, this program will not work as intended. To solve this
issue, you need to swap numbers first.
Normally, when we work with Numbers, we use primitive data types such as int, short, long,
float and double, etc. The number data types, their possible values and number ranges have
been explained while discussing C++ Data Types.
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
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.
The first is a number you wish to raise and the second is the power you wish to
raise it t
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.
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) << endl;
cout << "abs(i) :" << abs(i) << endl;
cout << "floor(d) :" << floor(d) << endl;
cout << "sqrt(f) :" << sqrt(f) << endl;
cout << "pow( d, 2) :" << pow(d, 2) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
int main () {
int i,j;
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
C++ provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater
than zero and type can be any valid C++ data type. For example, to declare a 10-element
array called balance of type double, use this statement −
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as
follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that
we declare for the array between square brackets [ ]. Following is an example to assign a
single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th, i.e., last element because all arrays have 0 as the index of their first
element which is also called base index. Following is the pictorial representaion of the same
array we discussed above −
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example, which will use all the above-mentioned three concepts
viz. declaration, assignment and accessing arrays −
Live Demo
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When the above code is
compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are following few
important concepts, which should be clear to a C++ programmer −
1 Multi-dimensional arrays
2 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the
array name, without any index.
3 Passing arrays to functions
You can pass to the function a pointer to an array by specifying the array's name
without an index.