Unit-3 (C++ Programming) 26-March-2025
Unit-3 (C++ Programming) 26-March-2025
1
What is C++?
(C++ history read by student)
C++ gives programmers a high level of control over system resources and
memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11,
C++14, and C++17, C++20, C++23 (realised in 2024).
C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
There are many text editors and compilers to choose from. We can use
TurboC++ or DevC++.
2
Note : we are using DevC++ platform for C++ programming and for this
mention #include<iostream> .
C++ Quickstart
Write the following C++ code and save the file as myfirstprogram.cpp (File >
Save File as):
Here writing a simple C++ program that prints “Hello World!” message. Lets
see the program first and then we will discuss each and every part of it in detail.
/*
* Multiple line
* comment
*/
#include<iostream>
return 0;
}
Output:
Hello World!
Let’s discuss each and every part of the above program.
1. Comments – You can see two types of comments in the above program
3
Comments as the names suggests are just a text written by programmer during
code development. Comment doesn’t affect your program logic in any way, you
can write whatever you want in comments but it should be related to the code
and have some meaning so that when someone else look into your code, the
person should understand what you did in the code by just reading your
comment.
For example:
Now if someone reads my comment, he or she can understand what I did there
just by reading my comment. This improves readability of your code and when
you are working on a project with your team mates, this becomes essential
aspect.
4. int main() – As the name suggests this is the main function of our program
and the execution of program begins with this function, the int here is the return
type which indicates to the compiler that this function will return a integer
value. That is the main reason we have a return 0 statement at the end of main
function.
5. cout << “Hello World!”; – The cout object belongs to the iostream file and
the purpose of this object is to display the content between double quotes as it is
on the screen. This object can also display the value of variables on screen.
4
6. return 0; – This statement returns value 0 from the main() function which
indicates that the execution of main function is successful. The value 1
represents failed execution.
Omitting Namespace
You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:
Example
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
The cout object, together with the << operator, is used to output values/print
text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not
insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
5
cout << "I am learning C++";
return 0;
}
New Lines
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
6
Both \n and endl are used to break lines. However, \n is used more often and is
the preferred way.
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code. Comments
can be singled-lined or multi-lined.
Any text between // and the end of the line is ignored by the compiler (will not
be executed).
Example
// This is a comment
cout << "Hello World!";
Example
cout << "Hello World!"; // This is a comment
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments,
and /* */ for longer.
7
C++ Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for constructing names for variables (unique identifiers) are:
Here already learned that cout is used to output (print) values. Now we will
use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number, which is stored in the
variable x. Then we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
8
Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion operator
(<<)
cin is pronounced "see-in". Used for input, and uses the extraction operator
(>>)
In this example, the user must input two numbers. Then we print the sum by
calculating (adding) the two numbers:
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
C++ Constants
When you do not want others (or yourself) to override existing variable values,
use the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
const int Num = 15; // Num will always be 15
Num = 10; // error: assignment of read-only variable 'Num'
cout>>Num;
cin>>num;
cout>>num;
You should always declare the variable as constant when you have values that
are unlikely to change:
9
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Variables in C++
here variable name is num which is associated with value 20, int is a data type
that represents that this variable can hold integer values.
For example:
int num1=20, num2=100;
Types of variables
Variables can be categorised based on their data type. For example, in the above
example we have seen integer types variables. Following are the types of
variables available in C++.
In C++, there are different types of variables (defined with different keywords),
for example:
10
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is the name of the
variable (such as x or myName). The equal sign is used to assign values to the
variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
11
Other Types
Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Example
int myAge = 35;
cout << "I am " << myAge << " years old.";
Add Variables Together
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
cout<<x+y;
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated
list:
Example
int x = 5, y = 6, z = 50, sum;
cout << x + y + z;
12
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in the source code,
the <string> library:
Example
// Include the string library
#include <string.h>
// Create a string variable
string greeting = "Hello";
greeting[0]=H,
greeting [1]=e,
greeting [2]=l
greeting [3]=l,
greeting [4]=o,
greeting [5]=\0
13
C++ Access Strings
Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].
Example
string myString = "Hello";
cout << myString[0];
cout << myString[1];
cout << myString[2];
cout << myString[3];
cout << myString[4];
// Outputs H
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
Example
string myString = "Hello";
cout << myString[1];
// Outputs e
aTo change the value of a specific character in a string, refer to the index
number, and use single quotes:
Example
string myString = "Hello";
myString[0] = 'J';
myString[3]= ‘L’;
cout << myString;
// Outputs JelLo instead of Hello
14
C++ User Input Strings
It is possible to use the extraction operator >> on cin to display a string entered
by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
From the example above, you would expect the program to print "John Doe",
but it only prints "John".
That's why, when working with strings, we often use the getline() function to
read a line of text. It takes cin as the first parameter, and the string variable as
second:
Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
The + operator can be used between strings to add them together to make a new
string. This is called concatenation:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
In the example above, we added a space after firstName to create a space
between John and Doe on output. However, you could also add a space with
Append
A string in C++ is actually an object, which contain functions that can perform
certain operations on strings. For example, you can also concatenate strings
with the append() function:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
16
C++ String Length
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
Tip: You might see some C++ programs that use the size() function to get the
length of a string. This is just an alias of length(). It is completely up to you if
you want to use length() or size():
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
Boolean Types
A boolean data type is declared with the bool keyword and can only take the
values true or false. When the value is returned, true = 1 and false = 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing.
Types of variables based on their scope
Before going further lets discuss what is scope first. When we discussed
the Hello World Program, we have seen the curly braces in the program like
this:
int main {
//Some code
}
Any variable declared inside these curly braces have scope limited within these
curly braces, if you declare a variable in main() function and try to use that
variable outside main() function then you will get compilation error. Now that
we have understood what is scope.
17
Types of variables based on the scope as below:
1. Global variable
2. Local variable
Global Variable
A variable declared outside of any function (including main as well) is called
global variable. Global variables have their scope throughout the program, they
can be accessed anywhere in the program, in the main, in the user defined
function, anywhere.
#include <iostream>
using namespace std;
// This is a global variable
char Var = 'A';
int main()
{
cout <<"Value of Variable is: "<< Var<<endl;
Var='Z';
cout <<"Value of Variables: "<< Var;
return 0;
}
Output:
Value of Variable : A
Value of Variable: Z
Local variable
Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope
limited inside those braces.
18
Local variable example
#include <iostream>
using namespace std;
char myFuncn() {
// This is a local variable
char myVar = 'A';
}
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Compile time error, because we are trying to access the variable myVar outside
of its scope. The scope of myVar is limited to the body of function myFuncn(),
inside those braces.
Lets see an example having same name global and local variable.
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0;
}
19
Output:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
As you can see that when I changed the value of myVar in the main function, it
only changed the value of global variable myVar because local
variable myVar scope is limited to the function myFuncn().
char ch = 'A';
int: For integers. Size 2 bytes.
20
float num = 123.78987;
double: For double precision floating point. Size 8 bytes.
bool b = true;
wchar_t: Wide Character. This should be avoided because its size is
implementation defined and not reliable.
Operators in C++
21
Note : Students are required to make program in C++ for using all below types
of Operators
Arithmetic Operators
22
remainder
.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:
2) Assignment Operators
= 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
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
24
Example of Assignment Operators
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;
}
Output:
= Output: 240
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0
++ and —
num++ is equivalent to num=num+1;
#include <iostream>
using namespace std;
int main(){
25
int num1 = 240;
int num2 = 40;
num1++; num2--;
cout<<"num1++ is: "<<num1<<endl;
cout<<"num2-- is: "<<num2;
return 0;
}
Output:
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.
Logical operators are used to determine the logic between variables or values:
! Logical not Reverse the result, returns !(x < 5 && x <
false if the result is true 10)
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false
and it would return false if b1 is true.
26
Example of Logical Operators
#include <iostream>
using namespace std;
int main(){
bool b1 = true;
bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
cout<<"b1 || b2: "<<(b1||b2)<<endl;
cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;
}
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
Comparison Operators
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
27
A list of all comparison operators:
== Equal to x == y
!= Not equal x != y
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 =40;
if (num1==num2) {
cout<<"num1 and num2 are equal"<<endl;
}
else{
cout<<"num1 and num2 are not equal"<<endl;
}
if( num1 != num2 ){
cout<<"num1 and num2 are not equal"<<endl;
}
else{
cout<<"num1 and num2 are equal"<<endl;
}
if( num1 > num2 ){
cout<<"num1 is greater than num2"<<endl;
}
else{
cout<<"num1 is not greater than num2"<<endl;
}
if( num1 >= num2 ){
cout<<"num1 is greater than or equal to num2"<<endl;
}
else{
cout<<"num1 is less than num2"<<endl;
28
}
if( num1 < num2 ){
cout<<"num1 is less than num2"<<endl;
}
else{
cout<<"num1 is not less than num2"<<endl;
}
if( num1 <= num2){
cout<<"num1 is less than or equal to num2"<<endl;
}
else{
cout<<"num1 is greater than num2"<<endl;
}
return 0;
}
Output:
6) Bitwise Operators
num1 | num2 compares corresponding bits of num1 and num2 and generates 1
if either bit is 1, else it returns 0. In our case it would return 31 which is
00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1
if they are not equal, else it returns 0. In our example it would return 29 which
is equivalent to 00011101
29
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to
0. In our example it would return -12 which is signed 8 bit equivalent to
11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far
left bit, and assigns the rightmost bit a value of 0. In our case output is 44 which
is equivalent to 00101100
Note: In the example below we are providing 2 at the right side of this shift
operator that is the reason bits are moving two places to the left side. We can
change this number and bits would be moved by the number of bits specified on
the right side of the operator. Same applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the
far right bit, and assigns the leftmost bit a value of 0. In our case output is 2
which is equivalent to 00000010
#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
cout<<"num1 | num2: "<<result<<endl;
result = num1 ^ num2;
cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
cout<<"~num1: "<<result<<endl;
result = num1 << 2;
cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
cout<<"num1 >> 2: "<<result;
return 0;
}
Output:
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the
result.
Syntax:
#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:
num2: 200
num2: 100
31
C++ Math
C++ has many functions that allows you to perform mathematical tasks on
numbers.
The max(x,y) function can be used to find the highest value of x and y:
Example
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);
Example
// Include the cmath library
#include <cmath>
A list of other popular Math functions (from the <cmath> library) can be found
in the table below:
Function Description
32
atan(x) Returns the arctangent of x
expm1(x) Returns ex -1
33
C++ Boolean Expression
A Boolean expression is a C++ expression that returns a boolean value: 1 (true)
or 0 (false).
You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:
Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
Or even easier:
Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
Example
cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
Booleans are the basis for all C++ comparisons and conditions.
34
You can use these conditions to perform different actions for different
decisions.
The if Statement
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
35
C++ 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 block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
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:
36
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
The break Keyword
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
C++ Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
The while loop loops through a block of code as long as a specified condition
is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
37
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
38
C++ For Loop
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Example explained
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
39
C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
40
Continue Example
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
41