Unit-1 C++-ECE-SEM2-2020
Unit-1 C++-ECE-SEM2-2020
Unit-1:
Review of C:
strings,
arrays,
pointers,
Programming in C++,
1
What is C++:-
C++ is a general purpose, cas e-sensitive, free-form programming that supports object-
language
oriented, procedural and generic programming.
C++ is a middle-level language, as it encapsulates both high and low lev le language features.
C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX
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.
Some of the features & key-points to note about the programming language are
as follows:
Simple: It is a simple language in the sense that programs can be brok en down into logical
units and parts, has a rich li brary support and a variety of data-types.
Machine Independent b ut Platform Dependent: A C++ executable is not platform-
independent (compiled programs on Linux won’t run on Windows), however they are machine
independent.
2
Mid-level language: It is a mid-level language as we can do both systems-programming
(drivers, kernels, networking etc.) and build large-scale user applications (Media Players,
Photoshop, Game Engines etc.)
Rich library support: Has a rich library support (Both standard ~ built-in data structures,
algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language,
and also hugely procedural. Newer languages have extra in-built default features such as garbage-
collection, dynamic typing etc. which slow the execution of the program overall. Since there is no
additional processing overhead like this in C++, it is blazing fast.
Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly
manipulate storage address. This helps in doing low-level programming (where one might need
to have explicit control on the storage of variables).
Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-
Oriented support helps C++ to make maintainable and extensible programs. i.e. Large- scale
applications can be built. Procedural code becomes difficult to maintain as code-size grows.
Compiled Language: C++ is a compiled language, contributing to its speed.
3
Object-Oriented Programming:-
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming(OOPs) used in C++ are:
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 datastructures,
etc.
4
When we consider a C++ program, it can be defined as a collection of objects that communicate via
invoking each other's methods(functions). Let us now briefly look into what a class, object, methods,
and instant 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(functions) − 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.
return 0;
}
Output
Hello World
5
Let us now understand every line and the terminologies of the above program:
1) // C++ program to display “Hello World”: This line is a comment line. A comment is used to display
additional information about the program. A comment does not contain any programming logic.
When a comment is encountered by a compiler, the compiler simply skips that line of code. Any
line beginning with ‘//’ without quotes OR in between /*…*/ in C++ is comment.
2) #include: In C++, all lines that start with pound (#) sign are called directives and are processed
by a preprocessor which is a program invoked by the compiler. The #include directive tells the
compiler to include a file and #include<iostream>. It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output library functions.
3) using namespace std: This is used to import the entirety of the std namespace into the current
namespace of the program.
4) int main(): This line is used to declare a function named “main” which returns data of integer
type. A function is a group of statements that are designed to perform a specific task. Execution of
every C++ program begins with the main() function, no matter where the function is located in the
program. So, every C++ program must have a main() function.
5) { and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing
braces ‘}’ indicates the ending of the main function. Everything between these two comprises the
body of the main function.
6) cout<<“Hello World”;: This line tells the compiler to display the message “Hello World” onthe
screen. This line is called a statement in C++. Every statement is meant to perform some task. A
semi-colon ‘;’ is used to end a statement. Semi-colon character at the end of the statement is
used to indicate that the statement is ending there. Everything followed by the character “<<” is
displayed to the output device
7) return 0; : This is also a statement. This statement is used to return a value from a function and
indicates the finishing of a function. This statement is basically used in functions to return the
results of the operations performed by a function.
8) Indentation: As you can see the cout and the return statement have been indented or moved
to the right side. This is done to make the code more readable. In a program as Hello World, it
doesnot hold much relevance, but as the programs become more complex, it makes the code more
readable, less error-prone. Therefore, you must always use indentations and comments to make the
code more readable
6
C++ Basic Input/Output:-
The C++ standard libraries provide an extensive set of input/output capabilities which we will see in
subsequent chapters. This chapter will discuss very basic and most common I/O operations
requiredfor C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a
keyboard, a disk drive, or a network connection etc. to main memory, this is called input
operation and if bytes flow from main memory to a device like a display screen, a printer, a disk
drive, or a network connection, etc., this is called output operation.
1
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the standard input
stream, the standard output stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
2
<iomanip>
This file declares services useful for performing formatted I/O with so-called parameterized
stream manipulators, such as setw and setprecision.
3
<fstream>
This file declares services for user-controlled file processing. We will discuss about it in detailin
File and Stream related chapter.
int main() {
char str[] = "Hello C++";
When the above code is compiled and executed, it produces the following result −
7
Value of str is : Hello C++
8
The C++ compiler also determines the data type of variable to be output and selects the appropriate
stream insertion operator to display the value. The << operator is overloaded to output data items of
built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above
and endl is used to add a new-line at the end of the line.
int main() {
char name[50];
}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a
value and then hit enter to see the following result −
Please enter your name:
cplusplusYour name is: cplusplus
The C++ compiler also determines the data type of the entered value and selects the appropriate
stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To
requestmore than one datum you can use the following −
cin >> name >> age;
This will be equivalent to the following two statements
−cin >> name;
cin >> age;
#include <iostream>
using namespace std;
int main() { 9
char str[] = "Unable to read ... ";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result –
Error message : Unable to read....
#include <iostream>
using namespace std;
int main() {
char str[] = "Unable to read ... ";
You would not be able to see any difference in cout, cerr and clog with these small examples, but
while writing and executing big programs the difference becomes obvious. So it is good practice to
display error messages using cerr stream and while displaying other log messages then clog
shouldbe used.
C++ Keywords:-
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.
10
Auto Break Case char const continue default do
11
Double Else enum extern float for goto if
A list of 30 Keywords in C++ Language which are not available in C language are given below.
Asm dynamic_cast namespace reinterpret_cast bool
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 */
#include <iostream>
using namespace std;
main() {
cout << "Hello World"; // prints Hello World
return 0; 12
}
When the above code is compiled, it will ignore // prints Hello World and final executable will
produce the following result −
Hello World
Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
commentwithin the other kind. For example −
14
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Derived Data Types: The data types that are derived from the primitive or built-in datatypes
arereferred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: These data types are defined by the user itself. Like, as
defining a class in C++ or a structure. C++ provides the following user-defined datatypes:
Class
Structure
Union
Enumeration
Typedef defined DataType
sizeof operator — sizeof operator is used to find the number of bytes occupied by a variable/data
type in computer memory. Eg: int m , x[50]; cout<<sizeof(m); //returns 4 which is the number
of bytes occupied by the integer variable “m”. cout<<sizeof(x); //returns 200 which is the number
of bytes occupied by the integer array variable “x”.
15
// Following is the example, which will produce correct size of various data types on your
16
computer.
#include <iostream>
using namespace
std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
return 0;
}
Output
Size of char : 1
Size of int : 4 Size
of long : 8 Size of
float : 4 Size of
double : 8
Datatype Modifiers
As the name implies, datatype modifiers are used with the built-in data types to modify the length
ofdata that a particular data type can hold.
18
The below table summarizes the modified size and range of built-in datatypes when combined with
the type modifiers:
Data Type Size (in bytes) Range
Float 4
Double 8
long double 12
Note: Above values may vary from compiler to compiler. In the above example, we have considered
GCC 32 bit.
We can display the size of all the data types by using the sizeof() operator and passing the
keywordof the datatype as an argument to this function as shown below:
Now to get the range of data types refer to the following chart
Note: syntax<limits.h> header file is defined to find the range of fundamental data-types. Unsigned
modifiers have minimum value is zero. So, no macro constants are defined for the unsigned
minimum value.
C++ Identifiers:-
19
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++.
Variable in C++:-
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
Let's see the syntax to declare a variable:
type variable_list;
The example of declaring variable is given below:
int x;
float y;
char z;
Here, x, y, z are variables and int, float, char are data types. We can also provide values
whiledeclaring the variables as given below:
21
Variable Scope in C++:-
A scope is a region of the program and broadly speaking there are three places, where variables
canbe declared −
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;
// 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;
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
23
It is a good programming practice to initialize variables properly, otherwise sometimes programwould
produce unexpected result.
Identifiers Keywords
Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaningis
basic elements of a program. known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the underscore. It cannot contain any special character.
24
The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
C++ Expressions:-
C++ expression consists of operators, constants, and variables which are arranged according to the rules
of the language. It can also contain function calls which return values. An expression can consist of one
or more operands, zero or more operators to compute a value. Every expression produces some value
which is assigned to the variable with the help of an assignment operator.
1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c 4.
(a+b) * (x+y)
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
25
If the expression is a combination of the above expressions, such expressions areknown
as compound expressions.
Constant expressions
A constant expression is an expression that consists of only constant values. It is an expression
whose value is determined at the compile-time but evaluated at the run-time.It can be
composed of integer, character, floating-point, and enumeration constants.
26
o It is used in the pre-processor #if
In the above scenarios, the constant expression can have integer, character, and enumeration
constants. We can use the static and extern keyword with the constants todefine the function-
scope.
x = (2/3) * 4 (2/3) * 4
extern int y = 67 67
int z = 43 43
static int a = 56 56
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }
In the above code, we have first declared the 'x' variable of integer type. After
declaration, we assign the simple constant expression to the 'x' variable.
Output
27
Value of x is : 3
Integral Expressions
An integer expression is an expression that produces the integer value as output after
performing all the explicit and implicit conversions.
1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13. }
In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take the user
input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their result in 'z'
variable.
Output
In the above code, we declare two variables, i.e., x and y. We store the value of
expression (y+int(10.0)) in a 'x' variable.
Output
Value of x : 19
Float Expressions
A float expression is an expression that produces floating-point value as output after
performing all the explicit and implicit conversions.
1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
29
6. float x=8.9; // variable initialization
30
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.11.
12.
13. return 0;
14. }
Output
value of z is :14.5
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10. }
In the above code, we have declared two variables, i.e., x and y. After declaration, we store the
value of expression (x+float(10)) in variable 'y'.
Output
value of y is :16.7
Pointer Expressions
A pointer expression is an expression that produces address value as an output.
1. &x
31
2. ptr
3. ptr++
4. ptr-
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12. }
In the above code, we declare the array and a pointer ptr. We assign the base address to the
variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is
incremented then 'ptr' will be pointing to the second element of the array.
Output
Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either trueor
false. It is also known as a boolean expression. When arithmetic expressions are used on both sides of
the relational operator, arithmetic expressions are evaluated first, and then their results are compared.
1. a>b
2. a-b >= x-y
3. a+b>80
32
Let's understand through an example
33
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=45; // variable declaration
6. int b=78; // variable declaration
7. bool y= a>b; // relational expression
8. cout<<"Value of y is :"<<y; // displaying the value of y.
9. return 0;
10. }
In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have applied
the relational operator between the variables to check whether 'a' is greater than 'b' or not.
Output
Value of y is :0
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11. }
In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then, we apply the
relational operator (>=) between these variables.
Output
34
Logical Expressions
A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10. }
Output
Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are
basically used to shift the bits.
For example:
x=3
x>>3 // This statement means that we are shifting the three-bit position to the right.
In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x' by
three-bit position to the right. Let's understand through the diagrammatic representation.
35
Let's see a simple example.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }
In the above code, we have declared a variable 'x'. After declaration, we applied the bitwiseoperator,
i.e., right shift operator to shift one-bit position to right.
Output
36
2
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }
In the above code, we have declared a variable 'x'. After declaration, we applied the left shift
operator to variable 'x' to shift the three-bit position to the left.
Output
56
o Chained Assignment
Chained assignment expression is an expression in which the same value is assigned to more thanone
variable by using single statement.
For example:
1. a=b=20
2. or
3. (a=b) = 20
1. #include <iostream>
2. using namespace std;
37
3. int main()
4.
38
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10. }
In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have assigned the
same value to both the variables using chained assignment expression.
Output
Note: Using chained assignment expression, the value cannot be assigned to the variable
at the time of declaration. For example, int a=b=c=90 is an invalid statement.
o Embedded Assignment Expression
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10. }
In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we applied embedded
assignment expression (a=10+(b=90)).
Output
40
A compound assignment expression is an expression which is a combination of an assignment
operator and binary operator.
For example,
1. a+=10;
1. #include <iostream>
2. using namespace std;
3. int
main()4.
{
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }
In the above code, we have declared a variable 'a' and assigns 10 value to this variable. Then,
we applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to
(a=a+10).This statement increments the value of 'a' by 10.
Output
Value of a is :20
41
C++ Operators:-
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example above, it can also
beused to add together a variable and a value, or a variable and another variable:
Example
int sum1= 100 + 50; // 150 (100 + 50)
int sum2= sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Assignment Operators
Assignment operators are used to assign values to variables.
42
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
43
Example
int x = 10;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Comparison operators are used to compare two values.
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
44
== Equal to x == y
45
!= Not equal x != y
Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
47
Function Description
expm1(x) Returns ex -1
48
Manipulators in C++ with Examples:-
Manipulators are helping functions that can modify the input/output stream. It does not mean
thatwe change the value of a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
Manipulators are special functions that can be included in the I/O statement to alter the
formatparameters of a stream.
Manipulators are operators that are used to format the data display.
To access manipulators, the file iomanip should be included in the program.
For example, if we want to print the hexadecimal value of 100 then we can print it as:
cout<<setbase(16)<<100
Examples:
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> std::ws, line);
49
stream.cout << line << endl;
50
cout << "only a test" << flush;
// Use of ends
Manipulatorcout << "\na";
return 0;
}
Output:
Programmer
only a test
abc
1. Manipulators with Arguments: Some of the manipulators are used with the argument like
setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to
use these manipulators then we must include this header file in our program. For Example,
youcan use following manipulators to set minimum width and fill the empty space with any
character you want: std::cout << std::setw (6) << std::setfill (’*’);
Some important manipulators in <iomanip> are:
1. setw (val): It is used to set the field width in output operations.
2. setfill (character): It is used to fill the character ‘c’ on output stream.
3. setprecision (val): It sets val as the new value for the precision of floating-point values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to set the format flags specified by parameter mask.
Example:
int a,b;
a=15; b=20;
cout<< setfill(‘*’) << endl;
cout << setw(5) << a << setw(5) << b<< endl;
setprecision() is a function in Manipulators in C++:
It is an output manipulator that controls the number of digits to display after the decimal for a
floating point integer.
Example:
float A = 1.34255;
cout << setprecision(3) << A << endl;
setbase() is a function in Manipulators in C++:
The setbase() manipulator is used to change the base of a number to a different value. The
following base values are supported by the C++ language:
• hex (Hexadecimal = 16)
• oct (Octal = 8)
• dec (Decimal = 10)
The manipulators hex, oct, and dec can change the basis of input and output numbers.
// Example:
#include <iostream>
#include <iomanip>
53
cout << "Hex Value =" << " " << hex << number << endl;
cout << "Octal Value=" << " " << oct << number << endl;
cout << "Setbase Value=" << " " << setbase(8) << number << endl; cout
<< "Setbase Value=" << " " << setbase(16) << number << endl;
return 0;
}
Output
Hex Value = 64
Octal Value= 144
Setbase Value= 144
Setbase Value= 64
2] Non-parameterized
Examples are endl, fixed, showpoint
• endl – Gives a new line
• ends – Adds null character to close an output string
• hex, oct, dec – Displays the number in hexadecimal or octal or in decimal format
if Statement
The C++ if statement tests the condition. It is executed if condition is true.
if(condition){
/code to be executed
}
54
Example:
#include <iostream>
using namespace std;
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:
It is even number
IF-else Statement
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwiseelse block is executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
55
if-else Example
#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
Output:
It is odd number
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
56
{
cout<<"It is odd number"<<endl;
}
57
return 0;
}
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
if else-if Example
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check
grade:";cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
58
else if(num >= 0 && num < 50){
cout<<"Fail";
59
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
Output:
Enter a number to check grade:66
C Grade
Output:
Enter a number to check grade:-2
wrong number
Switch Statements:-
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code
blockbreak;
default:
// code block
}
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords are optional, and will be described later in this
60
chapterThe example below uses the weekday number to calculate the weekday name:
61
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
Loops:-
In programming, sometimes there is a need to perform some operation more than once or (say) n
number of times. Loops come into use when we need to repeatedly execute a block of statements.
For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as
shown below:
Manual(general) Method (Iterative Method)
Manually we have to write cout statement 10 times. Let’s say you have to write it 20 times (it would
surely take more time to write 20 statements) now imagine you have to write it 100 times, it
62
wouldbe really hectic to re-write the same statement again and again. So, here loops have their role.
63
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10
times as shown below. In computer programming, a loop is a sequence of instructions that is
repeated until a certain condition is reached.
64
for Loop
A for loop is a repetition control structure that allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in
one
65
line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example:
for(int i = 0; i < n; i++){
}
In for loop, a loop variable is used to control the loop. First, initialize this loop variable to
some value, then check whether this variable is less than or greater than the counter value. If
the statement is true, then the loop body is executed and the loop variable gets updated.
Steps are repeated till the exit condition comes.
Initialization Expression: In this expression, we have to initialize the loop counter to
some value. for example: int i=1;
Test Expression: In this expression, we have to test the condition. If the condition
evaluates to true then we will execute the body of the loop and go to update expression
otherwise we will exit from the for a loop. For example: i <= 10;
Update Expression: After executing the loop body this expression
increments/decrements the loop variable by some value. for example: i++;
Example:
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
66
Hello World
Hello World
Hello World
Hello World
67
Hello World
While Loop
While studying for loop we have seen that the number of iterations is known beforehand,
i.e. the number of times the loop body is needed to be executed is known to us. while loops
are used in situations where we do not know the exact number of iterations of the
loop beforehand. The loop execution is terminated on the basis of the test conditions.
Syntax: We have already stated that a loop mainly consists of three statements –
initialization expression, test expression, and update expression. The syntax of the three
loops – For, while, and do while mainly differs in the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Example:
int main()
{
// initialization
expressionint i = 1;
// test
expressionwhile
(i < 6)
{
cout << "Hello World\n";
// update
expressioni++;
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
68
Hello World
69
do-while loop
In do-while loops also the loop execution is terminated on the basis of test conditions. The main
difference between a do-while loop and the while loop is in the do-while loop the condition is
testedat the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are
entry controlled loops.
Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Example:
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";
// update
expressioni++;
return 0;
}
Output:
Hello World
In the above program, the test condition (i<1) evaluates to false. But still, as the loop is
anexit – controlled the loop body will execute once.
Infinite Loop?
70
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks
a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is
71
always evaluated to be true. Usually, this is an error.
Output:
This loop will run forever.
This loop will run forever.
...................
#include <iostream>
using namespace
std;
int main()
{
while (1)
cout << "This loop will run forever.\n";
return 0;
}
Output:
This loop will run forever.
This loop will run forever.
...................
#include <iostream>
using namespace
72
std;
int main() {
73
do{
cout << "This loop will run forever.\n";
} while(1);
return 0;
}
Output:
This loop will run forever.
This loop will run forever.
...................
Functions:-
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.
Functions are used to perform certain actions, and they are important for reusing code: Define the
code once, and use it many times.
Advantage of functions
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
It makes the code optimized, we don't need to write much code.
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header files such as
ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++ programmer, so
74
that he/she can use it many times. It reduces complexity of a big program and optimizes the
code.
75
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can
alsocreate your own functions to perform certain actions.
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. 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.
Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will
occur:
Example
int main() {
myFunction();
return 0;
76
}
void myFunction() {
77
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization.
You will often see C++ programs that have function declaration above main(), and function
definitionbelow main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// The main
methodint main() {
myFunction(); // call the
functionreturn 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executedlater, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
78
int main() {
myFunction();
myFunction();
myFunction();
79
return 0;
}
Example:
Below is a simple program to demonstrate functions.
#include <iostream>
using namespace
std;
int main() {
int a = 10, b = 20;
Output:
m is 20
80
#include <iostream>
using namespace
std;
void fun(int x) {
81
x = 30;
}
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Output:
x = 20
However, in C, we can use pointers to get the effect of pass-by reference. For example, consider
the below program. The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is used to access
thevalue at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function call statement
‘fun(&x)’, the address of x is passed so that x can be modified using its address.
#include <iostream>
using namespace
std;
int main() {
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}
Output:
x = 30
83
int result;
result = a + b;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120
3) In C and C++, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.
4) Empty parameter list means that the parameter list is not specified and function can be
called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare a
function that can only be called without any parameter, we should use “void fun(void)”.
As a side note, in C++, an empty list means a function can only be called without any parameter. In
C++, both void fun() and void fun(void) are same.
84
Main Function:
The main function is a special function. Every C++ program must contain a function named main.
85
It serves as the entry point for the program. The computer will start running the code from the
beginning of the main function.
Types of main Function:
1) The first type is – main function without parameters :
// Without
Parametersint main()
{
...
return 0;
}
// With Parameters
int main(int argc, char * const argv[])
{
...
return 0;
}
The reason for having the parameter option for the main function is to allow input from the
command line.
When you use the main function with parameters, it saves every group of characters (separated
bya space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what the
result of the program’s execution was. Returning 0 signals that there were no problems.
Lifetime refers to the period during which the variable remains active and visibility refers to the
module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable
{
auto int y;
float y = 3.45;
}
The above example defines two variables with a same storage class, auto can only be used
withinfunctions.
The static variable has the default value 0 which is provided by compiler.
#include <iostream>
using namespace
std;void func() {
static int i=0; //static
variableint j=0; //local
variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
87
{
func();
func();
func();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
88
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from
0. We can store only fixed set of elements in C++ array.
#include <iostream>
using namespace
std;int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
89
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
10
0
20
0
30
#include <iostream>
using namespace
std;int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing
arrayfor (int i:
arr)
{
cout<<i<<"\n";
}
}
Output:
10
20
30
40
50
Let's see an example of C++ function which prints the array elements.
#include <iostream>
using namespace
std;
90
void printArray(int arr[5]);
int main()
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
91
printArray(arr1); //passing array to
functionprintArray(arr2);
}
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
Printing array
elements:10
20
30
40
50
Printing array
elements:5
15
25
35
45
#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int arr1[5] = { 30, 10, 20, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printMin(arr1);//passing array to
functionprintMin(arr2);
}
void printMin(int arr[5])
{
int min = arr[0];
for (int i = 0; i > 5; i++)
{
if (min > arr[i])
92
{
min = arr[i];
}
93
}
cout<< "Minimum element is: "<< min <<"\n";
}
Output:
Minimum element is: 10
Minimum element is: 5
#include <iostream>
using namespace
std;
void printMax(int arr[5]);
int main()
{
int arr1[5] = { 25, 10, 54, 15, 40 };
int arr2[5] = { 12, 23, 44, 67, 54 };
printMax(arr1); //Passing array to
functionprintMax(arr2);
}
void printMax(int arr[5])
{
int max = arr[0];
for (int i = 0; i < 5; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
cout<< "Maximum element is: "<< max <<"\n";
}
Output:
Maximum element is: 54
Maximum element is: 67
94
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
int threedim[5][10][4];
95
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
ofsize x,y, you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown as
below −
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
thename of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays
Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following
is an array with 3 rows and each row have 4 columns.
int a[3][4] = {{0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11}};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
96
#include <iostream>
using namespace std;
int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
97
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that
most of the arrays you create will be of one or two dimensions.
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50
In the above example, p is a pointer to double which means it can store address of a variable of
double type. Once we have address in p, then *p will give us value available at the address stored
inp, as we have shown in the above example.
99
}
100
void myFunction(int param[]) {
.
.
}
Now, consider the following function, which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed
throughthe array as follows −
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;
return avg;
}
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.4
As you can see, the length of the array doesn't matter as far as the function is concerned because
C++performs no bounds checking for the formal parameters.
102
int * myFunction() {
.
.
}
Second point to remember is that C++ does not advocate to return the address of a local variable
tooutside of the function so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them
using an array and call this function as follows −
#include <iostream>
#include <ctime>
return r;
}
// a pointer to an int.
int *p;
p = getRandom();
return 0;
}
When the above code is compiled together and executed, it produces result something as follows −
624723190
1468735695
807113585
976495677
613357504
1377296355
103
1530315259
1778906708
104
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415
C++ Strings:-
C++ provides following two types of string representations −
The C-style character string.
The string class type introduced with Standard C++.
The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
above-mentioned string −
105
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
106
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
int main () {
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
C++ Pointers:-
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers,
andother C++ tasks, such as dynamic memory allocation, cannot be performed without them.
108
As you know every variable is a name of 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>
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
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.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
109
etc.and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
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
110
Pointer Program to swap 2 numbers without using 3rd variable
#include <iostream>
using namespace std;
int main()
{
int a=20,b=10,∗p1=&a,∗p2=&b;
Pointers vs Arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many
cases. For example, a pointer that points to the beginning of an array can access that array by using
either pointer arithmetic or array-style indexing. Consider the following program −
#include <iostream>
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
return 0;
}
111
When the above code is compiled and executed, it produces result something as follows −
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
However, pointers and arrays are not completely interchangeable. For example, consider the
following program −
#include <iostream>
112
113
114
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value.
The reason for this is that var is a constant that points to the beginning of an array and can not
beused as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style
expressions, as long as it is not modified. For example, the following is a valid statement that assigns
var[2] the value 500 −
*(var + 2) = 500;
Above statement is valid and will compile successfully because var is not changed.
Following a simple example where we pass an unsigned long pointer to a function and change the
value inside the function which reflects back in the calling function −
#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par);
int main () {
unsigned long sec;
getSeconds( &sec );
return 0;
}
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following result −
C++ structures:-
C/C++ arrays allow you to define variables that combine several data items of the same kind,
but structure is another user defined data type which allows you to combine data items of different
kinds.
Structures are used to represent a record, suppose you want to keep track of your books in a library.
You might want to track the following attributes about each book −
116
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type,with more than one member, for your program. The format of the struct statement is this −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition. At the end of the structure's definition, before the
final semicolon, you can specify one or more structure variables but it is optional. Here is the
wayyou would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
117
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
118
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
119
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
120
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variableas follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To
findthe address of a structure variable, place the & operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the -> operator
asfollows −
121
struct_pointer->title;
122
Let us re-write above example using structure pointer, hope this will be easy for you to
understandthe concept −
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
Writing the ‘struct’ keyword is necessary to Writing the ‘struct’ keyword is not necessary to
declare structure-type variables. declare structure-type variables.
124
C Structures C++ Structures
Only pointers to structs are allowed. Can have both pointers and references to the struct.
125
The typedef Keyword
There is an easier way to define structs or you could "alias" types you create. For example −typedef
struct {
char title[50]; char
author[50]; char
subject[100];int
book_id;
} Books;
Now, you can use Books directly to define variables of Books type without using struct keyword.
Following is the example −
126
The following are the differences between C and C++:
ADVERTISEMENT
o Definition
C is a structural programming language, and it does not support classes and
objects, while C++ is an object-oriented programming language that supportsthe
concept of classes and objects.
127
o
o Developer of the language
Dennis Ritchie developed C language at Bell Laboratories while Bjarne Stroustrup
developed the C++ language at Bell Labs circa 1980.
o Subset
C++ is a superset of C programming language. C++ can run 99% of C code butC
language cannot run C++ code.
o Type of approach
C follows the top-down approach, while C++ follows the bottom-up approach. The
top-down approach breaks the main modules into tasks; these tasks are broken into
sub-tasks, and so on. The bottom-down approach develops the lowerlevel modules
first and then the next level modules.
o Security
In C, the data can be easily manipulated by the outsiders as it does not support the
encapsulation and information hiding while C++ is a very secure language, i.e., no
outsiders can manipulate its data as it supports both encapsulation and data hiding.
In C language, functions and data are the free entities, and in C++ language, all the
functions and data are encapsulated in the form of objects.
o Function Overloading
Function overloading is a feature that allows you to have more than one functionwith
the same name but varies in the parameters. C does not support the function
overloading, while C++ supports the function overloading.
o Function Overriding
Function overriding is a feature that provides the specific implementation to the
function, which is already defined in the base class. C does not support the function
overriding, while C++ supports the function overriding.
o Reference variables
C does not support the reference variables, while C++ supports the reference
variables.
o Keywords
C contains 32 keywords, and C++ supports 52 keywords.
128
o Namespace feature
A namespace is a feature that groups the entities like classes, objects, and
129
functions under some specific name. C does not contain the namespace feature,while
C++ supports the namespace feature that avoids the name collisions.
o Exception handling
C does not provide direct support to the exception handling; it needs to usefunctions
that support exception handling. C++ provides direct support to exception handling by
using a try-catch block.
o Input/Output functions
In C, scanf and printf functions are used for input and output operations,respectively,
while in C++, cin and cout are used for input and output operations, respectively.
o Inheritance
Inheritance is a feature that allows the child class to reuse the properties of theparent
class. C language does not support the inheritance while C++ supports the
inheritance.
o Header file
C program uses <stdio.h> header file while C++ programuses
<iostream.h> header file.
No. C C++
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
130
outside users.
7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.
10) C does not provide the featureof C++ supports the feature of namespace.
namespace.
11) Exception handling is not easy C++ provides exception handling using Try
in C. It has to perform using and Catch block.
other functions.
131
C++ Dynamic Memory:-
A good understanding of how dynamic memory really works in C++ is essential to becoming a good
C++ programmer. Memory in your C++ program is divided into two parts −
The stack − All variables declared inside the function will take up memory from the stack.
The heap − This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.
Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given type using a special
operator in C++ which returns the address of the space allocated. This operator is
called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator, which
de-allocates memory that was previously allocated by new operator.
132
Here, data-type could be any built-in data type including an array or any user defined data types
include class or structure. Let us start with built-in data types. For example we can define a pointer to
type double and then request that the memory be allocated at execution time. We can do this using
the new operator with the following statements −
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So it is
good practice to check if new operator is returning NULL pointer and take appropriate action as
below −
double* pvalue = NULL;
if( !(pvalue )) {
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. The main advantage of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore required,
you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows −
delete pvalue; // Release memory pointed to by pvalue
Initialize memory: We can also initialize the memory for built-in data types using a new operator.
For custom data types, a constructor is required (with the data type as input) for initializing the
value. Here’s an example of the initialization of both data types :
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);
Let us put above concepts and form the following example to show how ‘new’ and
‘delete’ work −
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
133
return 0;
}
If we compile and run above code, this would produce the following result −
Value of pvalue : 29495
To free the dynamically allocated array pointed by pointer-variable, use the following form
of delete:
delete[] pointer-variable; // Release block of memory pointed by pointer-variable
Example:
delete[] p; // It will free the entire array pointed by p.
int main ()
{
if (!q)
cout << "allocation of memory failed\n";
else
134
{
for (int i = 0; i < n; i++)
q[i] = i+1; // or *(q+i)=i+1
cout << "Values stored in block of memory: "; for (int i = 0; i <
n; i++)
cout << q[i] << " ";
}
return 0;
}
Output:
135
C Revision Topics:-
Arrays,
Strings,
Structures,
Pointers etc..
C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language whichcan
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its
index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code arerequired to
access the elements of the array.
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.
o Elements of the array are stored at contiguous memory locations where the firstelement
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size ofthe data element.
Advantage of C Array
136
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an arrayeasily.
137
3) Ease of sorting: To sort the elements of the array, we need a few lines of codeonly.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which wewill learn
later.
Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
138
C array example
Output
139
C Array: Declaration with
Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
int marks[]={20,30,40,50,60};
140
C Array Example: Sorting an
array
In the following program, we are using bubble sort method to sort the array i
ascending order.
141
142
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word orsentences.
Each character in the array occupies one byte of memory, and the last character must
always be 0. The termination character ('\0') is important in a string since it is the only way
to identify where the string ends. When we define a string as char s[10], the character s[10]
is implicitly initialized with the null in the memory.
1. By char array
2. By string literal
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure givenbelow.
While declaring string, size is not mandatory. So we can write the above code as givenbelow:
In such case, '\0' will be appended at the end of the string by the compiler.
143
Difference between char array and string literal
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the characterarray.
o The string literal cannot be reassigned to another set of characters whereas, wecan
reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The'%s' is
used as a format specifier for the string in c language.
144
Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by traversing
the text. Traversing string is somewhat different from the traversing an integer array. We
need to know the length of the array to traverse an integer array, whereas we may use the
null character in the case of string to identify the end the string and terminate the loop.
145
}
Output
146
Output
148
It is clear from the output that, the above code will not work for space separated strings. To
make this code working for the space separated strings, the minor changedrequired in the
scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which
instructs the compiler to store the string s while the new line (\n) is encountered. Let's
consider the following example to store the space-separated strings.
149
Some important points
However, there are the following points which must be noticed while entering thestrings by
using scanf.
o The compiler doesn't perform bounds checking on the character array. Hence, there can
be a case where the length of the string can exceed the dimension ofthe character array
which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a header
file string.h. The gets() is capable of receiving only one string at a time.
150
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However pointers
can be used to point to the strings. There are various advantages of using pointe point strings. Let us
consider the following example to access the string via the pointer.
151
As we know that string is an array of characters, the pointers can be used in the same way
they were used with arrays. In the above example, p is declared as a pointer to thearray of
characters s. P affects similar to s since s is the base address of the string and treated as a
pointer internally. However, we can not change the content of s or copy the content of s into
another string directly. For this purpose, we need to use the pointers to store the strings. In
the following example, we have shown the use of pointers to copy the content of a string into
another.
152
Once a string is defined, it cannot be reassigned to another set of characters. However, upointers,
we can assign the set of characters to the string. Consider the following exampl
153
154
C Pointers
The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function, or
any other pointer. The size of the pointer depends onthe architecture.
However, in 32-bit architecture the size of a pointer is 2 byte.
155
Let's see the pointer example as explained for the above figure.
156
157
Usage of pointer
There are many applications of pointers in c language.
Pointers in c language are widely used in arrays, functions, and structures. It reducesthe
code and improves the performance.
158
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you canassign NULL
value. It will provide a better approach.
159
Output
160
C Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. In other words,
we can say that the collection of functions creates a program. The functionis also known as
procedureor subroutinein other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in aprogram.
o We can call C functions any number of times in a program and from any place ina
program.
o We can track a large C program easily when it is divided into multiple functions.
Function Aspects
There are three aspects of a C function.
o Function call Function can be called from anywhere in the program. The parameter
list must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed.It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
161
SN C function Syntax
aspects
162
163