0% found this document useful (0 votes)
8 views

C++ Com331

Uploaded by

aliyukawuji01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C++ Com331

Uploaded by

aliyukawuji01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

COM 313_C++

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. This C++ tutorial adopts a simple and
practical approach to describe the concepts of C++ for beginners to advanced
software engineers.
Why to Learn C++
C++ is a MUST for students and working professionals to become a great Software
Engineer. I will list down some of the key advantages of learning C++:
• C++ is very close to hardware, so you get a chance to work at a low
level which gives you lot of control in terms of memory management,
better performance and finally a robust software development.
• C++ programming gives you a clear understanding about Object
Oriented Programming. You will understand low level implementation
of polymorphism when you will implement virtual tables and virtual
table pointers, or dynamic type identification.
• C++ is one of every green programming language and loved by millions
of software developers. If you are a great C++ programmer then you
will never sit without work and more importantly you will get highly
paid for your work.
• C++ is the most widely used programming languages in application and
system programming. So, you can choose your area of interest of
software development.
• C++ really teaches you the difference between compiler, linker and
loader, different data types, storage classes, variable types their scopes
etc.
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 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, You can try it using Demo link
C++ is a super set of C programming with additional implementation of object-
oriented concepts.
Live Demo
#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
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"
• 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. The C++
world is just too large and too much new is happening.

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. I'm going to list
few of them here:
• 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.

C++ Program Structure

Let us look at a simple code that would print the words Hello World.
Live Demo
#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
• The C++ language defines several headers, which contain information
that is either necessary or useful to your program. For this program, the
header <iostream> is needed.
• The line using namespace std; tells the compiler to use the std
namespace. Namespaces 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.

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++ Identifiers
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++ Comments
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++ comments can also


* span multiple lines
*/
A comment can also start with //, extending to the end of the line. For example −
Live Demo
#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
Within a /* and */ comment, // characters have no special meaning. Within a //
comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
comment within the other kind. For example −
/* Comment out printing of Hello World:

cout << "Hello World"; // prints Hello World

*/
DATA TYPE
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

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

Variables
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 −

Variable Definition in C++

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. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
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;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
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
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;

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
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;
}

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
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;

// 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;
}
When the above code is compiled and executed, it produces the following result −
10

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize
it yourself. Global variables are initialized automatically by the system when you
define them as follows −

Data Type Initializer

int 0

char '\0'

float 0

double 0

pointer NULL

It is a good programming practice to initialize variables properly, otherwise


sometimes program would produce unexpected result.

OPERATOR
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 −
Show Examples

Operator Description Example


+ Adds two operands A + B will give 30

- Subtracts second operand from the A - B will give -10


first

* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator

% Modulus Operator and remainder B % A will give 0


of after an integer division

++ Increment operator, increases A++ will give 11


integer value by one

-- Decrement operator, decreases A-- will give 9


integer value by one

Relational Operators

There are following relational operators supported by C++ language


Assume variable A holds 10 and variable B holds 20, then −
Show Examples

Operator Description Example

== Checks if the values of two (A == B) is not true.


operands are equal or not, if yes
then condition becomes true.

!= Checks if the values of two (A != B) is true.


operands are equal or not, if values
are not equal then condition
becomes true.

> Checks if the value of left operand (A > B) is not true.


is greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand (A < B) is true.
is less than the value of right
operand, if yes then condition
becomes true.

>= Checks if the value of left operand (A >= B) is not true.


is greater than or equal to the value
of right operand, if yes then
condition becomes true.

<= Checks if the value of left operand (A <= B) is true.


is less than or equal to 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 −
Show Examples

Operator Description Example

&& Called Logical AND operator. If (A && B) is false.


both the operands are non-zero,
then condition becomes true.

|| Called Logical OR Operator. If (A || B) is true.


any of the two operands is non-
zero, then condition becomes true.

! Called Logical NOT Operator. Use !(A && B) is true.


to reverses the logical state of its
operand. If a condition is true, then
Logical NOT operator will make
false.

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 −
Show Examples

Operator Description Example

& Binary AND Operator copies a bit


(A & B) will give 12 which is 0000
to the result if it exists in both
1100
operands.

| Binary OR Operator copies a bit if (A | B) will give 61 which is 0011


it exists in either operand. 1101

^ Binary XOR Operator copies the


(A ^ B) will give 49 which is 0011
bit if it is set in one operand but not
0001
both.

~ Binary Ones Complement (~A ) will give -61 which is 1100


Operator is unary and has the 0011 in 2's complement form due
effect of 'flipping' bits. to a signed binary number.
<< Binary Left Shift Operator. The
left operands value is moved left A << 2 will give 240 which is 1111
by the number of bits specified by 0000
the right operand.

>> Binary Right Shift Operator. The


left operands value is moved right A >> 2 will give 15 which is 0000
by the number of bits specified by 1111
the right operand.

Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples

Operator Description Example

= Simple assignment operator, Assigns


C = A + B will assign value of
values from right side operands to left
A + B into C
side operand.

+= Add AND assignment operator, It


C += A is equivalent to C = C +
adds right operand to the left operand
A
and assign the result to left operand.

-= Subtract AND assignment operator,


It subtracts right operand from the left C -= A is equivalent to C = C -
operand and assign the result to left A
operand.

*= Multiply AND assignment operator,


It multiplies right operand with the C *= A is equivalent to C = C *
left operand and assign the result to A
left operand.

/= Divide AND assignment operator, It


divides left operand with the right C /= A is equivalent to C = C /
operand and assign the result to left A
operand.
%= Modulus AND assignment operator,
C %= A is equivalent to C = C
It takes modulus using two operands
%A
and assign the result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment


C >>= 2 is same as C = C >> 2
operator.

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and


C ^= 2 is same as C = C ^ 2
assignment operator.

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

Misc Operators

The following table lists some other operators that C++ supports.

Sr.No Operator & Description

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.
Show Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right


Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

LOOP
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.

Sr.No Loop Type & Description

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.
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.

Sr.No Control Statement & Description

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.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the
‘for’ loop are required, you can make an endless loop by leaving the conditional
expression empty.
#include <iostream>
using namespace std;

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.

FUNCTION
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is 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 sub-routine or a
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

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 declaration
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;
}
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 −

Sr.No Call Type & Description

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.

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.
Default Values for Parameters

When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments
in the function definition. If a value for that parameter is not passed when the
function is called, the default given value is used, but if a value is specified, this
default value is ignored and the passed value is used instead. Consider the following
example −
#include <iostream>
using namespace std;

int sum(int a, int b = 20) {


int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
C++ NUMBERS
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.

Defining Numbers in C++

You have already defined numbers in various examples given in previous chapters.
Here is another consolidated example to define various types of numbers in C++ −
#include <iostream>
using namespace std;

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

Math Operations in C++

In addition to the various functions you can create, C++ also includes some useful
functions you can use. These functions are available in standard C and C++ libraries
and called built-in functions. These are functions that can be included in your
program and then use.
C++ has a rich set of mathematical operations, which can be performed on various
numbers. Following table lists down some useful built-in mathematical functions
available in C++.
To utilize these functions you need to include the math header file <cmath>.

Sr.No Function & Purpose

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 t

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.

Following is a simple example to show few of the mathematical operations −


#include <iostream>
#include <cmath>
using namespace std;

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

Random Numbers in C++

There are many cases where you will wish to generate a random number. There are
actually two functions you will need to know about random number generation. The
first is rand(), this function will only return a pseudo random number. The way to
fix this is to first call the srand() function.
Following is a simple example to generate few random numbers. This example
makes use of time() function to get the number of seconds on your system time, to
randomly seed the rand() function −
#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main () {
int i,j;

// set the seed


srand( (unsigned)time( NULL ) );

/* generate 10 random numbers. */


for( i = 0; i < 10; i++ ) {
// generate actual random number
j = rand();
cout <<" Random Number : " << j << endl;
}

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++ ARRAY
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 −

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
double salary = balance[9];
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 () {

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

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 −

Sr.No Concept & Description

1 Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the
multidimensional array is the two-dimensional array.

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.

4 Return array from functions


C++ allows a function to return an array.

C++ POINTER
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily
with pointers, and other C++ tasks, such as dynamic memory allocation, cannot be
performed without them.
As you know every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&) operator which
denotes an address in memory. Consider the following which will print the address
of the variables defined −
#include <iostream>

using namespace std;


int main () {
int var1;
char var2[10];

cout << "Address of var1 variable: ";


cout << &var1 << endl;

cout << "Address of var2 variable: ";


cout << &var2 << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6
What are Pointers?
A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it. The
general form of a pointer variable declaration is −
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.

Using Pointers in C++

There are few important operations, which we will do with the pointers very
frequently. (a) We define a pointer variable. (b) Assign the address of a variable to
a pointer. (c) Finally access the value at the address available in the pointer variable.
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;
}
When the above code is compiled and executed, it produces result something as
follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Pointers in C++

Pointers have many but easy concepts and they are very important to C++
programming. There are following few important pointer concepts which should be
clear to a C++ programmer −

Sr.No Concept & Description

1 Null Pointers
C++ supports null pointer, which is a constant with a value of zero defined
in several standard libraries.

2 Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, -

3 Pointers vs Arrays
There is a close relationship between pointers and arrays.

4 Array of Pointers
You can define arrays to hold a number of pointers.
5 Pointer to Pointer
C++ allows you to have pointer on a pointer and so on.

6 Passing Pointers to Functions


Passing an argument by reference or by address both enable the passed
argument to be changed in the calling function by the called function.

7 Return Pointer from Functions


C++ allows a function to return a pointer to local variable, static variable
and dynamically allocated memory as well.

You might also like