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

Unit I Introduction toC++

This is important pdf for c++ its only for sale My u

Uploaded by

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

Unit I Introduction toC++

This is important pdf for c++ its only for sale My u

Uploaded by

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

C++ Using OOPs BCA (Manag) IIISem

Unit I: Introduction to C++:


*Basic concepts:
C++ is a high-level programming language that is widely used by software developers
for developing a variety of things including software applications, operating systems,
games, and more.
It is a versatile language that offers procedural, object-oriented, and functional
programming. Learning C++ is a valuable skill that can open up a range of career
opportunities in the tech industry. There are several reasons why learning C++ is a
good idea for accelerating your career.
Firstly, it is a widely used language that is used in many industries, including gaming,
finance, and aerospace. Secondly, it is a powerful language that is ideal for developing
high-performance applications. Finally, it helps in improving your problem-solving and
critical thinking skills, which are valuable in any industries.
Getting Started with C++
To get started with C++, you will need to install an Integrated Development Environment
(IDE) such as Visual Studio or Code::Blocks. Once you have an IDE installed, you can
start learning the basics of C++ programming, including data types, variables, control
structures, and functions. There are many online resources available to help you learn
C++, including tutorials, forums, and online courses. It is important to practice coding
regularly and to work on projects to gain experience and improve your skills.
We also have a list of C++ certifications and projects cumulated for you.
Advantages of C++
1. High Perfomance: It gives low-level access to computer hardware, making it
ideal for developing high-performance applications
2. Versatility: It supports various programming paradigms including procedural,
object-oriented, and functional programming.
3. Portability: C++ can be compiled and run on different operating systems and
hardware platforms making it versatile.
4. Large Community: C++ has a large and active community of developers who
contribute to open-source libraries, frameworks, and tools, making it a wide
community where you can interact and learn more. Eg: Most of the errors and
questions that might arise can be shared on Stack Overflow
Applications of C++
1. Operating Systems: It is used for developing operating systems, including
Windows, Linux, and Mac OS.
2. Finance: It used in financial applications, including trading systems, risk
management tools, and portfolio management software.
3. Aerospace: It is used for developing software for spacecraft and satellites,
controlling drones and other unmanned vehicles.
4. Gaming: Another popular place its is used is developing video games due to its
performance and low-level access to computer hardware.
Key Concepts in C++
Let us now dive into some key concepts in C++ that are essential for a developer to
know before making any progress in C++. We’ll look into some basic concepts along
with their code snippets:
1. Variables and Data Types
2. Input and Output Operations
3. Control flow structures
4. Arrays and Pointers
Variables and Data Types
Now let’s take a closer look at the data types and variables in C++:
A. Declaration and Initialisation of Variables:
In C++ we must declare the variables before using them. The declaration specified the
name and data type of the variable. We can also simultaneously initialise them while
declaring the variables.

int x; // declare an integer variable


x = 5; // initialize the variable with the value 5
int y = 10; // declare and initialize an integer variable with the value 10
B. Fundamental Data Types:
C++ has several fundamental data types, including int, float, double, char, and bool.
Here’s a brief description of each:
• int: used to store integer values
• float: used to store floating-point values with single precision
• double: used to store floating-point values with double precision
• char: used to store a single character
• bool: used to store true/false values
Here is an example of declaring and initialising the various types of variables:

• int age = 30;
• float height = 1.75;
• double weight = 75.5;
• char gender = 'M';
• bool isStudent = true;
• C. User-defined Data Types:
In addition to the fundamental data types, C++ also allows you to define your own data
types using struct and enum. A struct is a collection of data elements, while an enum is
a set of named integer constants. Here’s an example of defining a struct and an enum:

// define a struct to represent a person


struct Person {
string name;
int age;
};

// define an enum to represent the days of the week


enum Day { Monday,Tuesday, Wednesday,Thursday, Friday, Saturday, Sunday};
D. Type Modifiers:

Type modifiers in C++ also let you change how a data type behaves. A variable’s initial
value cannot be altered once it has been initialised, according to the const modifier.
With integer types, the signed and unsigned modifiers are used to determine whether or
not the values can be negative. Here’s an illustration of how to use type modifiers:

const int MAX_VALUE = 100; // declare a constant variable


unsigned int count = 0; // declare an unsigned integer variable
signed int temperature = -10; // declare a signed integer variable
Input and Output Operations
Now let us take a look at how the input and output operations look in C++:
A. Standard Input and Output Streams:
C++ provides standard input and output streams, which are represented by the built in
“cin” and “cout”.
–The cin object is used for reading input from the user.
–The cout object is used for writing output to the console.
Here’s an example of using cin and cout to read input and write output:

int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
B. Formatting Output:
C++ provides several ways to format output using the cout object.
–setw() function to specify the width of the output.
–setprecision() function to specify the number of decimal places to display for floating-
point numbers.
–setfill() function to specify the fill character for the output.
Here’s an example of using formatting functions:

double pi = 3.14159265358979323846;
cout << "Pi is approximately: " << setprecision(4) << pi << endl;
C. String Manipulation:
C++ provides several functions for manipulating strings, which are represented by the
string class.
– “+” operator to concatenate strings
– size() function to get the length of a string
– substr() function to get a substring of a string
Here’s an example of using string manipulation functions:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << "Full name: " << fullName << endl;
cout << "Length of full name: " << fullName.size() << endl;
cout << "First name: " << fullName.substr(0, 4) << endl;
// Output
Full name: John Doe
Length of full name: 8
First name: John

Control Flow Structures


Let’s take a closer look at control flow structures and functions in C++.
A. Conditional Statements:
In C++, you can use conditional statements like if, if-else, and switch to execute
different blocks of code based on different conditions.
–”if” statement executes a block of code if a specified condition is true
– “if-else” statement executes one block of code if the condition is true and another
block of code if the condition is false
– “switch” statement is used to execute different blocks of code based on the value of a
variable. Here’s an example of using conditional statements:

int num = 10;


if (num > 0) {
cout << "The number is positive" << endl;
} else if (num < 0) {
cout << "The number is negative" << endl;
} else {
cout << "The number is zero" << endl;
}

int day = 1;
switch (day) {
case 1:cout << "Monday" << endl; break;
case 2:cout << "Tuesday" << endl; break;
// ...
default:cout << "Invalid day" << endl;
}

B. Looping Statements:
C++ provides several looping statements like for, while, and do-while to execute a block
of code repeatedly.
– “for” loop executes a block of code a fixed number of times
– “while” the while loop executes a block of code as long as a specified condition is true
– “do-while” loop is similar to the while loop, but it always executes the block of code at
least once
Here’s an example of using looping statements:

for (int i = 0; i < 10; i++) {


cout << i << endl;
}

int j = 0;
while (j < 10) {
cout << j << endl;
j++;
}

int k = 0;
do {
cout << k << endl;
k++;
} while (k < 10);
C. Nested Loops and Conditional Statements:
You can also nest conditional statements and loops to create more complex control flow
structures. Here’s an example of using nested loops and conditional statements:

for (int i = 1; i <= 10; i++) {


if (i % 2 == 0) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
}
Functions
A. Defining and calling functions:
Functions are used to perform a specific task. A function is a block of code that can be
called from other parts of your program. To define a function, you need to specify the
-return type
-name
-parameter list
To call a function, you simply need to use its name and pass any required arguments.
Here’s an example of defining and calling a function:

int add(int x, int y) {


return x + y;
}

int sum = add(5, 7);


cout << "The sum is: " << sum << endl;
B. Parameters and Return Values:
Functions can take zero or more parameters,they are values that are passed to it .
Functions can also return a value, which is the result of the function’s computation. To
specify a return value, you need to use the return statement. Here’s an example of
using parameters and return values:
double divide(double x, double y) { return x / y; } double result = divide(10.0, 2.0);
C. Function Overloading:
In C++, you can define multiple functions with the same name but different parameter
lists. This is called function overloading, and it allows you to use the same function
name for different tasks,where the return type is different. Here’s an example of function
overloading:

int add(int x, int y) {


return x + y;
}

double add(double x, double y) {


return x + y;
}

int sum = add(5, 7);


double total = add(3.14, 2.71);
cout << "The sum is: " << sum << endl;
cout << "The total is: " << total << endl;
Arrays and Pointers
A. Declaring and Accessing Arrays:
Arrays in programming are a collection of variables of the same data type, which are
grouped together under a common name. The variables in an array can be accessed
using their index number, which starts at 0 for the first element in the array.
We can declare an array in C++, we need to specify the data type of data elements
followed by array name and size in the of th array in square brackets.

int myArray[5];
int myArray[5] = {1, 2, 3, 4, 5}; //array of size 5
To access elements we need to use the index

int x = myArray[0]; // access the first element in the array


B. Multidimensional Arrays:
Multidimensional arrays are arrays that have more than one dimension. The most
common type is the two-dimensional array, which is also called a table or matrix. To
declare a two-dimensional array in C++, you can use the following syntax:

int myArray[3][4];
int myArray[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
To access the elements we use:
int x = myArray[0][1]; // access the element in the first row and second column
C. Introduction to Pointers:
A pointer is a variable that holds the memory address of another variable. Pointers are
often used in C++ for dynamic memory allocation and for passing parameters by
reference.

int* myPointer;
int x = 10;
myPointer = &amp;x; //This declares a pointer variable that can hold the memory
address of an integer variable.
D. Pointers and Arrays:
In C++, arrays and pointers are closely related. In fact, the name of an array is a pointer
to the first element in the array.
To declare a pointer to an array, you can use the following syntax:

int myArray[5];
int* myPointer = myArray;
This creates a pointer variable myPointer that points to the first element in the array
myArray. You can access individual elements in the array using pointer arithmetic:

int x = *(myPointer + 2); // access the third element in the array


Practical Tips for Writing C++ Code
• Use meaningful variable names to improve code readability.
• Declare variables close to where they are used to reduce bugs and improve code
readability.
• Use comments to explain the purpose of code and improve code readability.
• Follow a consistent coding style to make code easier to read and maintain.
Sample Codes
1. Hello World Program

#include <iostream.h>
using namespace std;

int main() {
int n = 10, t1 = 0, t2 = 1, nextTerm;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
cout << t1 << " + ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Object Oriented Programming Class
1.Class
The building block of C++ that leads to Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is
the class, and wheels, speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc
and member functions can apply brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of objects which
shares some common properties and behaviors.
2.Object
An Object is an identifiable entity with some characteristics and behavior. An Object is
an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented PProgramming
#include <iostream.h>
using namespace std;

class person {
char name[20];
int id;

public:
void getdetails() {}
};

int main()
{

person p1; // p1 is a object


return 0;
}
Difference Between Class And Object:
There are many differences between object and class. Some differences between
object and class are given below:

Class Object

Class is used as a template for


declaring and An object is an instance of a class.
creating the objects.

When a class is created, no memory Objects are allocated memory space


is allocated. whenever they are created.

The class has to be declared first An object is created many times as per
and only once. requirement.

A class can not be manipulated as


they are not Objects can be manipulated.
available in the memory.

A class is a logical entity. An object is a physical entity.

3.Data Abstraction:
Data Abstraction in C++ means providing only the essential details to the outside world
and hiding the internal details, i.e., hiding the background details or implementation.
Abstraction is a programming technique that depends on the separation of the interface
and implementation details of the program.
Ways to implement Data Abstraction in C++
Abstraction using classes
Abstraction in C++ programming language can be implemented in classes. The class
helps the programmers to group the members of that data and function by using
available access specifiers. A class is the main deciding factor of which data member
will be visible to the world or which is not.
Abstraction using header files
Another type of abstraction in the C++ programming language is related to header files.
For instance, let's consider the pow() method present in the math.h header file. If the
developer needs to calculate the power of a number, then it is called the function pow()
which is present in the math.
Example

// C++ Program to Demonstrate the working of Data Abstraction


#include <iostream.h>
Int main()
class implementAbstraction
{
private:
int A, B;
public:
// method to set values of
// private members
void set(int x, int y)
{
A = x;
B = y;
}
void display()
{
cout << "A = " << A << endl;
cout << "B = " << B << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(20, 30);
obj.display();
return 0;
}

C++ Tokens
C++ Tokens are the tiniest individual units of any program. C++ is the superset of ‘C’ and
so most constructs of ‘C’ are permissible in the ‘C++’ with their sense and usage
unaffected. So tokens, expressions, and the data types are equal to that of ‘C’.C++
Tokens are the tiniest individual units of any program. C++ is the superset of ‘C’ and so
most constructs of ‘C’ are permissible in the ‘C++’ with their sense and usage unaffected.
So tokens, expressions, and the data types are equal to that of ‘C’.
Following, given below are the ‘C++’ tokens: (most of the ‘c++’ tokens are basically equal
to the ‘C’ tokens, respectively)
• Keywords
• Identifiers
• Constants
• Variables
• Operators

Keywords
These are the reserved words that have a fixed and definite meaning, and their sense
cannot be changed or modified. Moreover, the meaning and the working process of these
keywords are already known to the compiler. ‘C++’ has more numbers of keywords as
compared to ‘C’, and those extra ones are having special working abilities.
There are a total of 32 of these, and these are as follows:
auto const double float int short struct unsigned
break continue elseforlong signed switch void
case default enumgoto register sizeof typedef volatile
char do extern if return static unionwhile
There are additional 30 reserved words that were not in ‘C’, these are therefore new
to the ‘C++’, and these are as follows:
asm dynamic_cast namespace reinterpret_cast try
bool explicit new static_cast typeid
catch false operator template typename
class friend privatethis using
const_cast inline public throw virtual
delete mutable protected true wchar_t
Browse more Topics Under Getting Started with C++
• C++ Character Set
• Structure of a C++ Program
• Header Files
• Use of I/O Operators
• Use of endl and setw
• Cascading of I/O Operators
• Compilation in C++
• Error Messages
• Use of Editor
• Basic Commands of Editor
• Linking in C++
• Execution in C++
Identifiers
Identifiers are the names that are given to the different entries just like variables,
structures, as well as functions. Also, the names of the identifiers should be unique
because these entities are applicable to the implementation of the program.
Identifier naming conventions
Only the alphabetic characters, digits, and underscores are allowed.
The first letter should be an alphabet or an underscore (_).
The identifiers are case-sensitive.
Keywords that are reserved can’t be used as the name of the identifier.
Constants
Constants are similar to a variable, except for one thing, that is their value which never
changes during the execution process once defined.
There are two more different ways of defining the constants in ‘C++’. These are as
follows:
By the use of the ‘const’ keyword
By the use of the ‘#define’ pre-processor
Declaration of a constant:
const [data_type] [constant_name]=[value];
Variable
A variable is a name that is meaningful. In addition, this name is basically of the data
storage location in a computer system’s memory. Similarly, when we use a variable we
refer to the memory address of the computer system.
Syntax to declare a variable
[data_type] [variable_name];
Example

#include

int main() {

int a,b;// a and b are integer variable

cout<<” Enter first number :”;

cin>>a;

cout<<” Enter the second number:”;

cin>>b;

int sum;

sum=a+b;

cout<<” Sum is : “<<sum;


return 0;
}
Operator
‘C++’ operator is a symbol that we use for performing mathematical or logical
manipulations. C++ Operators
Operators are used to perform operations on variables and values.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic Operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y


- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Example:
#include <iostream.h>

int main() {
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
cout << sum1 << "\n";
cout << sum2 << "\n";
cout << sum3;
return 0;
}
• Assignment operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10
to a variable called x:

Example
int x = 10;
The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator Example Same As
= 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
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
FAQ on C++ Tokens
Comparison operators
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important
in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0).
These values are known as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater
than 3:
A list of all comparison operators:
In C++, comparison operators are used to compare two values or expressions. They
yield a boolean result (true or false) based on the outcome of the comparison. Here are
the primary comparison operators available in C++:
1. Equal to (==):
o Syntax: a == b
o Checks if a is equal to b.
o Example: if (x == 10) { /* ... */ }
2. Not equal to (!=):
o Syntax: a != b
o Checks if a is not equal to b.
o Example: if (x != 10) { /* ... */ }
3. Greater than (>):
o Syntax: a > b
o Checks if a is greater than b.
o Example: if (x > 10) { /* ... */ }
4. Less than (<):
o Syntax: a < b
o Checks if a is less than b.
o Example: if (x < 10) { /* ... */ }
5. Greater than or equal to (>=):
o Syntax: a >= b
o Checks if a is greater than or equal to b.
o Example: if (x >= 10) { /* ... */ }
6. Less than or equal to (<=):
o Syntax: a <= b
o Checks if a is less than or equal to b.
o Example: if (x <= 10) { /* ... */ }

#include <iostream.h>
int main() {
int a = 10, b = 20;

if (a == b) {
cout << "a is equal to b" << endl;
} else if (a != b) {
cout << "a is not equal to b" << endl;
}

if (a < b) {
cout << "a is less than b" << endl;
}

if (a > b) {
cout << "a is greater than b" << endl;
}

if (a <= b) {
cout << "a is less than or equal to b" << endl;
}

if (a >= b) {
cout << "a is greater than or equal to b" << endl;
}

return 0;
}
Logical operators in C++ are used to perform logical operations on boolean values.
Here are the key logical operators:
1. Logical AND (&&):
o Syntax: expr1 && expr2
o Returns true if both expr1 and expr2 are true; otherwise, returns false.
o Example: if (x > 0 && y > 0) { /* ... */ }
2. Logical OR (||):
o Syntax: expr1 || expr2
o Returns true if either expr1 or expr2 is true; otherwise, returns false.
o Example: if (x > 0 || y > 0) { /* ... */ }
3. Logical NOT (!):
o Syntax: !expr
o Returns true if expr is false; otherwise, returns false.
o Example: if (!(x > 0)) { /* ... */ }
Examples:

#include <iostream.h>
int main() {
bool a = true, b = false;

// Logical AND
if (a && b) {
cout << "Both a and b are true" << endl;
} else {
cout << "At least one of a or b is false" << endl;
}

// Logical OR
if (a || b) {
cout << "At least one of a or b is true" << endl;
}

// Logical NOT
if (!b) {
cout << "b is false" << endl;
}

return 0;
}
Key Points:
• Logical operators are often used in conditional statements and loops to combine
or invert boolean conditions.
• They perform short-circuit evaluation: in &&, if the first expression is false, the
second expression is not evaluated; in ||, if the first expression is true, the second
expression is not evaluated.
Bitwise operators
itwise operators in C++ operate on the binary representations of integers. They perform
operations on the individual bits of the values. Here's a rundown of the main bitwise
operators:
1. Bitwise AND (&):
o Syntax: a & b
o Performs a bitwise AND operation between each bit of a and b. The result
has a bit set to 1 if both corresponding bits of a and b are 1.
o Example: 0101 & 0011 = 0001
2. Bitwise OR (|):
o Syntax: a | b
o Performs a bitwise OR operation between each bit of a and b. The result
has a bit set to 1 if at least one of the corresponding bits of a or b is 1.
o Example: 0101 | 0011 = 0111
3. Bitwise XOR (^):
o Syntax: a ^ b
o Performs a bitwise XOR (exclusive OR) operation between each bit of a
and b. The result has a bit set to 1 if exactly one of the corresponding bits
of a or b is 1.
o Example: 0101 ^ 0011 = 0110
4. Bitwise NOT (~):
o Syntax: ~a
o Performs a bitwise NOT operation on a. It inverts all the bits in a, turning
0s into 1s and 1s into 0s.
o Example: ~0101 = 1010 (for a 4-bit number)
5. Bitwise Shift Left (<<):
o Syntax: a << n
o Shifts the bits of a to the left by n positions. Zeroes are shifted into the
vacated positions on the right.
o Example: 0001 << 2 = 0100
6. Bitwise Shift Right (>>):
o Syntax: a >> n
o Shifts the bits of a to the right by n positions. The vacated positions on the
left are filled with zeros for unsigned types, or with the sign bit for signed
types (arithmetic shift).
o Example: 0100 >> 2 = 0001
Examples:

#include <iostream.h>

int main() {
unsigned int a = 5; // Binary: 0101
unsigned int b = 3; // Binary: 0011

cout << "a & b: " << (a & b) << endl; // Binary: 0001, Decimal: 1
cout << "a | b: " << (a | b) << endl; // Binary: 0111, Decimal: 7
cout << "a ^ b: " << (a ^ b) << endl; // Binary: 0110, Decimal: 6
cout << "~a: " << (~a) << endl; // Binary: ...1111010 (depending on integer size)
cout << "a << 1: " << (a << 1) << endl; // Binary: 1010, Decimal: 10
cout << "a >> 1: " << (a >> 1) << endl; // Binary: 0010, Decimal: 2

return 0;
}
Key Points:
• Bitwise AND: Useful for masking specific bits.
• Bitwise OR: Useful for setting specific bits.
• Bitwise XOR: Useful for toggling specific bits.
• Bitwise NOT: Useful for inverting all bits.
• Bitwise Shift Left/Right: Useful for multiplying or dividing by powers of two, or
for bit manipulation tasks.
These operators are particularly useful in low-level programming, such as system
programming, embedded systems, and performance-critical applications where direct
bit manipulation is necessary.
Expression and control structure
In C++, expressions and control statements are fundamental constructs that dictate the
flow and behavior of a program.
Expressions
An expression in C++ is a combination of variables, constants, operators, and functions
that evaluates to a value. Expressions can be simple or complex:
1. Arithmetic Expressions:
o Perform mathematical operations.
o Example: a + b, x * y / 2
2. Relational Expressions:
o Compare values and return boolean results.
o Example: a > b, x == 10
3. Logical Expressions:
o Use logical operators to combine boolean values.
o Example: (a > b) && (x < y)
4. Assignment Expressions:
o Assign a value to a variable.
o Example: x = 5, a += 10
Control Statements
Control statements manage the flow of execution in a program. They include:
1. Conditional Statements:
o if:
▪ Executes a block of code if a condition is true.
▪ Example:

if (x > 0) {
// Code to execute if x is greater than 0
}
o if-else:
▪ Executes one block of code if the condition is true, and another
block if false.
▪ Example:

if (x > 0) {
// Code for true condition
} else {
// Code for false condition
}
o else if:
▪ Provides additional conditions to test if the previous conditions are
false.
▪ Example:

if (x > 0) {
// Code for x > 0
} else if (x == 0) {
// Code for x == 0
} else {
// Code for x < 0
}
2. Switch Statement:
o Chooses among multiple options based on the value of a variable.
o Example:

switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
// More cases...
default: cout << "Invalid day"; break;
}
3. Loops:
o for:
▪ Repeats a block of code a specific number of times.
▪ Example:

for (int i = 0; i < 10; ++i) {


// Code to execute
}
o while:
▪ Repeats a block of code as long as a condition is true.
▪ Example:

while (x < 10) {


// Code to execute
++x;
}
o do-while:
▪ Similar to while, but guarantees at least one execution of the code
block.
▪ Example:

do {
// Code to execute
++x;
} while (x < 10);
4. Jump Statements:
o break:
▪ Exits the current loop or switch statement.
▪ Example: Used inside loops or switch cases to exit early.
o continue:
▪ Skips the rest of the current loop iteration and proceeds to the next
iteration.
▪ Example: Used to skip certain iterations in a loop.
o return:
▪ Exits a function and optionally returns a value.
▪ Example: return 0; exits the function and returns 0.
Examples:

#include <iostream.h>

int main() {
int x = 5;

// Conditional Statement
if (x > 0) {
cout << "x is positive" << endl;
} else {
cout << "x is not positive" << endl;
}

// Switch Statement
int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
default: cout << "Invalid day"; break;
}
cout << endl;

// Loop
for (int i = 0; i < 5; ++i) {
cout << "i = " << i << endl;
}

return 0;
}
Key Points:
• Expressions evaluate to values and can be used anywhere in the code.
• Control statements alter the flow of execution based on conditions or loops.
Symbolic Constants
In C++, symbolic constants are named constants whose values are set at compile-time
and cannot be changed during program execution. They enhance code readability and
maintainability by giving meaningful names to constant values. Here’s how you can
define and use symbolic constants:
Defining Symbolic Constants
1. Using const Keyword:
o Syntax: const type name = value;
o Example:

const int MAX_USERS = 100;


2. Using constexpr Keyword (introduced in C++11):
o Guarantees that the constant expression is evaluated at compile time.
o Syntax: constexpr type name = value;
o Example:

constexpr double PI = 3.14159;


3. Using enum:
o For a set of related constants.
o Syntax:

enum { MAX_SIZE = 100, MIN_SIZE = 10 };


o Example:

enum Color { RED, GREEN, BLUE };


4. Using enum class (introduced in C++11):
o Scoped enumeration for better type safety.
o Syntax:

enum class Direction { NORTH, SOUTH, EAST, WEST };


o Example:

Direction dir = Direction::NORTH;


5. Using #define Preprocessor Directive:
o Defines a constant value before compilation.
o Syntax: #define NAME value
o Example:
#define MAX_BUFFER_SIZE 1024
Examples:
#include <iostream.h>

// Using const
const int MAX_USERS = 100;
constexpr double PI = 3.14159;

// Using enum
enum class Status { OK, ERROR, UNKNOWN };

int main() {
cout << "Max users: " << MAX_USERS << endl;
cout << "Value of PI: " << PI << endl;

Status currentStatus = Status::OK;


if (currentStatus == Status::OK) {
cout << "Status is OK" << endl;
}

return 0;
}
Key Points:
• const and constexpr are type-safe and scoped within their declaration.
• enum and enum class are used for groups of related constants, with enum
class providing better type safety and scoping.
• #define is a preprocessor directive and lacks type safety and scope control
compared to the other methods.
Type Compatability
type compatibility in C++ refers to how types interact with each other in expressions and
assignments. Understanding type compatibility is crucial for writing correct and efficient
C++ code. Here’s a brief overview:
1. Implicit Type Conversion (Type Promotion)
C++ performs automatic type conversion when types in an expression are mixed. This
is known as type promotion or implicit conversion.
• Numeric Promotion: Smaller integer types (char, short) are promoted to int.
Floating-point types (float) are promoted to double.
int a = 5;
double b = 2.5;
double result = a + b; // 'a' is promoted to double
• Integer Promotion: If an int is involved in operations with a long, the int is
promoted to long.
2. Type Casting
Explicit conversion between types can be performed using type casting.
• static_cast: Used for safe, compile-time checks for conversions.
double pi = 3.14;
int intPi = static_cast<int>(pi); // Converts double to int
• dynamic_cast: Used for safely downcasting in polymorphic class hierarchies
(requires RTTI).
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe downcasting
• const_cast: Used to add or remove const from a variable.
const int x = 10;
int& y = const_cast<int&>(x); // Removes const-ness
• reinterpret_cast: Used for low-level casting, often between unrelated types.
int* p = reinterpret_cast<int*>(0x12345678); // Treats the address as an int
pointer
3. Type Compatibility Rules
• Assignment Compatibility: When assigning one type to another, the compiler
checks if the source type can be converted to the destination type. For example,
double can be assigned to int with implicit conversion (but it may lose data).
int a = 10;
double b = a; // Implicit conversion from int to double
• Function Overloading: Functions can be overloaded based on different
parameter types. The best match is selected based on type compatibility.
void print(int x);
void print(double x);
• Type Compatibility in Templates: C++ templates need to handle type
compatibility, template <typename T>
void func(T a) {
// Function implementation
}
Examples:
#include <iostream.h>

int main() {
int i = 10;
double d = 5.5;
double result = i + d; // 'i' is promoted to double

// Static cast
int intResult = static_cast<int>(result);

// Dynamic cast example (with polymorphism)


class Base { virtual void foo() {} };
class Derived : public Base {};
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
cout << "Result: " << intResult << endl;

return 0;
}
Key Points:
• Implicit Conversions: Automatic conversions based on type promotion rules.
• Explicit Casts: Controlled type conversion using static_cast, dynamic_cast,
const_cast, and reinterpret_cast.
• Type Compatibility Rules: Ensure operations and assignments between types
are valid according to C++ rules.
Understanding these concepts helps prevent type-related errors and ensures that type
conversions
Variables
In C++, variables are named storage locations used to hold data that can be modified
and accessed throughout the program. Here’s a concise overview of variables in C++:
1. Declaration and Initialization
• Declaration: Specifies the type and name of the variable.
int age; // Declares an integer variable named age
• Initialization: Assigns a value to a variable at the time of declaration.
int age = 25; // Declares and initializes the variable age
2. Variable Types
• Basic Data Types:
o int - Integer type.
o float - Single-precision floating-point.
o double - Double-precision floating-point.
o char - Single character.
o bool - Boolean (true or false).
• Derived Data Types:
o Arrays: Collection of elements of the same type.
int numbers[5]; // Array of 5 integers
o Pointers: Variables that hold memory addresses.
int* ptr; // Pointer to an integer
o References: Alias for another variable.
int value = 10;
int& ref = value; // Reference to value
o Structures: User-defined types that group variables.
struct Person {
string name;
int age;
};
union Data {
int intValue;
float floatValue;
};
o Enumerations: Defines a set of named integral constants.
enum Color { RED, GREEN, BLUE };
3. Scope and Lifetime
• Local Variables: Declared inside a function or block; accessible only within that
scope.
void func() {
int localVar = 10; // Local variable
}
• Global Variables: Declared outside all functions; accessible throughout the
program.
int globalVar = 20; // Global variable
• Static Variables: Retain their value between function calls.
void func() {
static int count = 0; // Static variable
count++;
}
• Dynamic Variables: Allocated at runtime using new and deallocated with delete.
int* p = new int; // Dynamically allocated integer
delete p; // Deallocate memory
Examples:
#include <iostream.h>
#include <string>

struct Person {
string name;
int age;
};

int globalVar = 100;

int main() {
// Local Variable
int localVar = 10;

// Array
int numbers[3] = {1, 2, 3};

// Pointer
int* ptr = &localVar;

// Reference
int& ref = localVar;

// Static Variable
static int staticVar = 0;
staticVar++;

// Dynamic Variable
int* dynamicVar = new int(50);

Person person;
person.name = "Alice";
person.age = 30;

cout << "Local Variable: " << localVar << endl;


cout << "Pointer Value: " << *ptr << endl;
cout << "Reference Value: " << ref << endl;
cout << "Static Variable: " << staticVar << endl;
cout << "Dynamic Variable: " << *dynamicVar << endl;
cout << "Person Name: " << person.name << ", Age: " << person.age << endl;

delete dynamicVar; // Free dynamically allocated memory


return 0;
}
Key Points:
• Variables store data and are essential for performing computations and
manipulating data.
• Types define the kind of data a variable can hold.
• Scope and Lifetime determine where and how long a variable exists and is
accessible.
• Dynamic Memory allows for flexible memory management during runtime.
Understanding these concepts is crucial for effective programming and managing data
in C++.
Scope Resolution Operator
In C++, the scope resolution operator (::) is used to specify the scope in which a
particular identifier (like a variable, function, or class) resides. It helps resolve
ambiguities and access members of classes or namespaces. Here’s a detailed overview
of the scope resolution operator:
1. Accessing Global Variables
When a local variable or function name hides a global variable or function, the scope
resolution operator can be used to access the global version.
#include <iostream.h>

int value = 10; // Global variable

void func() {
int value = 20; // Local variable
cout << "Local value: " << value << endl;
cout << "Global value: " << ::value << endl; // Access global variable
}

int main() {
func();
return 0;
}
2. Accessing Namespace Members
Namespaces help organize code into logical groups and prevent name conflicts. The
scope resolution operator is used to access members of a namespace.
#include <iostream.h>

namespace MyNamespace {
int value = 42;
}

int main() {
cout << "Namespace value: " << MyNamespace::value << endl; // Access
namespace member
return 0;
}
3. Defining Class Members Outside the Class
When defining a member function of a class outside the class definition, the scope
resolution operator is used to specify which class the function belongs to.
#include <iostream.h>

class MyClass {
public:
void display();
};

void MyClass::display() { // Definition of display() outside MyClass


cout << "Hello from MyClass::display()" << endl;
}

int main() {
MyClass obj;
obj.display(); // Call member function
return 0;
}
4. Accessing Base Class Members
In derived classes, the scope resolution operator can be used to access members of the
base class that might be hidden by derived class members.

#include <iostream.h>

class Base {
public:
void show() { cout << "Base show()" << endl; }
};

class Derived : public Base {


public:
void show() { << "Derived show()" << endl; }
void showBase() { Base::show(); } // Access base class method
};

int main() {
Derived obj;
obj.show(); // Calls Derived's show()
obj.showBase(); // Calls Base's show()
return 0;
}
5. Using :: for Member Function Templates
When dealing with class templates, the scope resolution operator is used to define
member functions outside the class template definition.
#include <iostream.h>

template <typename T>


class MyClass {
public:
void display();
};

// Definition of display() for template


template <typename T>
void MyClass<T>::display() {
cout << "Displaying in MyClass" << endl;
}

int main() {
MyClass<int> obj;
obj.display(); // Calls the template member function
return 0;
}
Key Points:
• Global Scope Access: Use :: to access global variables or functions when their
names are hidden by local variables.
• Namespace Scope: Use :: to access elements within a namespace.
• Class Member Definitions: Use :: to define member functions outside the class
definition.
• Base Class Access: Use :: to access base class members in derived classes.
• Template Member Functions: Use :: to define member functions of class
templates outside the class definition.
The scope resolution operator helps manage the visibility of identifiers and resolve
ambiguities in C++ programs, ensuring that the correct variables, functions, or class
members are accessed as intended.
Member Referencing Operators

In C++, member referencing operators are used to access or modify members of a


class or structure. The primary member referencing operators are:
1. Dot Operator (.)
Used to access members of an object through its name.
• Syntax: object.member
• Example:
#include <iostream.h>

class Person {
public:
string name;
int age;
};

int main() {
Person person;
person.name = "Alice"; // Using dot operator to access member
person.age = 30;

cout << "Name: " << person.name << ", Age: " << person.age << endl;
return 0;
}
2. Arrow Operator (->)
Used to access members of an object through a pointer to that object.
• Syntax: pointer->member
• Example:
#include <iostream.h>

class Person {
public:
string name;
int age;
};

int main() {
Person person;
Person* ptr = &person;
ptr->name = "Bob"; // Using arrow operator to access member
ptr->age = 25;

cout << "Name: " << ptr->name << ", Age: " << ptr->age << endl;
return 0;
}
3. Pointer-to-Member Operator (.*)
Used to access a member of an object through a pointer to a member, often in
conjunction with a pointer to an object.
• Syntax: object.*memberPointer
• Example:
#include <iostream.h>

class Person {
public:
string name;
int age;
};

int main() {
Person person;
person.name = "Charlie";
person.age = 40;

string Person::*ptrToName = &Person::name;


int Person::*ptrToAge = &Person::age;

cout << "Name: " << person.*ptrToName << endl; // Accessing member
through pointer-to-member
cout << "Age: " << person.*ptrToAge << endl;
return 0;
}
4. Pointer-to-Member Function Operator (->*)
Used to call a member function on an object through a pointer to that member function.
• Syntax: object->*memberFunctionPointer()
• Example:

#include <iostream.h>

class Person {
public:
void greet() const {
cout << "Hello!" << endl;
}
};

int main() {
Person person;
void (Person::*ptrToGreet)() const = &Person::greet;

(person.*ptrToGreet)(); // Calling member function through pointer-to-member-


function
return 0;
}
Key Points:
• Dot Operator (.): Accesses members of an object directly.
• Arrow Operator (->): Accesses members through a pointer to the object.
• Pointer-to-Member Operator (.*): Accesses members using a pointer to a
member of the class.
• Pointer-to-Member Function Operator (->*): Calls member functions using a
pointer to a member function.
These operators are crucial for working with objects and pointers in C++, providing the
means to interact with and manipulate class members effectively.
Memory Management Operators
In C++, memory management operators handle dynamic memory allocation and
deallocation. These operators are essential for managing memory manually, especially
in resource-constrained environments or when precise control over memory is needed.
1. new Operator
Allocates memory for an object or array on the heap and returns a pointer to the
allocated memory.
• Syntax:
type* pointer = new type; // Single object
type* arrayPointer = new type[size]; // Array of objects
• Example:
#include <iostream.h>

int main() {
int* p = new int; // Allocate memory for a single integer
*p = 10;
cout << "Value: " << *p << endl;
delete p; // Deallocate memory

int* arr = new int[5]; // Allocate memory for an array of 5 integers


for (int i = 0; i < 5; ++i) {
arr[i] = i * 2;
}
for (int i = 0; i < 5; ++i) {
cout << "arr[" << i << "] = " << arr[i] << endl;
}
delete[] arr; // Deallocate array memory

return 0;
}
2. delete Operator
Deallocates memory previously allocated with new. It should be used for single object
deallocation.
• Syntax:
delete pointer;
• Example:
int* p = new int;
delete p; // Correct usage
3. delete[] Operator
Deallocates memory previously allocated with new[]. It is used for arrays.
• Syntax:
delete[] arrayPointer;
• Example:
int* arr = new int[5];
delete[] arr; // Correct usage for arrays
4. new and delete with Class Objects
When working with class objects, new and delete operate similarly, allocating and
deallocating memory for objects.
• Example:
class MyClass {
public:
MyClass() { cout << "Constructor called" << endl; }
~MyClass() { cout << "Destructor called" << endl; }
};

int main() {
MyClass* obj = new MyClass; // Allocate memory for MyClass object
delete obj; // Deallocate memory

MyClass* objArray = new MyClass[3]; // Allocate array of MyClass objects


delete[] objArray; // Deallocate memory for array

return 0;
}
Key Points:
• new: Allocates memory and returns a pointer to the allocated memory.
• delete: Deallocates memory for a single object allocated with new.
• new[]: Allocates memory for an array of objects and returns a pointer to the first
element.
• delete[]: Deallocates memory for an array of objects allocated with new[].
Proper use of these operators ensures efficient memory management and helps avoid
memory leaks and dangling pointers.
Manipulators
In C++, manipulators are used to format the output and control the behavior of the
input/output streams. They are part of the I/O library (<iostream.h>) and help in
adjusting the appearance of output, such as setting the width, precision, and format of
data.
Commonly Used I/O Manipulators
1. endl
• Function: Inserts a newline character into the output stream and flushes the
stream.
• Syntax: cout << endl;
• Example:
#include <iostream.h>

int main() {
cout << "Hello, World!" << endl;
return 0;}
2. setw
• Function: Sets the width of the next input/output field.
• Syntax: setw(width)
• Example:
#include <iostream.h>
#include <iomanip> // For setw

int main() {
cout << setw(10) << 42 << endl; // Right-aligned by default
return 0;
}
3. setfill
• Function: Sets the fill character used when outputting fields with setw.
• Syntax: setfill(char)
• Example:
#include <iostream.h>
#include <iomanip> // For setfill

int main() {
cout << setw(10) << setfill('*') << 42 << endl;
return 0;
}
4. setprecision
• Function: Sets the number of digits to be displayed after the decimal point for
floating-point numbers.
• Syntax: setprecision(precision)
• Example:
#include <iostream.h>
#include <iomanip> // For setprecision

int main() {
double pi = 3.141592653589793;
cout << fixed << setprecision(2) << pi << endl;
return 0;
}
5. fixed and scientific
• Function: Controls the format of floating-point numbers. fixed shows numbers in
fixed-point notation, and scientific shows them in scientific notation.
• Syntax: fixed, scientific
• Example:
#include <iostream.h>
#include <iomanip> // For fixed and scientific

int main() {
double number = 123456.789;
cout << fixed << number << endl;
cout << scientific << number << endl;
return 0;
}
6. hex, dec, and oct
• Function: Changes the number base for integer output. hex for hexadecimal,
dec for decimal, and oct for octal.
• Syntax: hex, dec, oct
• Example:
#include <iostream.h>
#include <iomanip> // For hex, dec, and oct

int main() {
int number = 255;
cout << hex << number << endl; // Hexadecimal
cout << dec << number << endl; // Decimal
cout << oct << number << endl; // Octal
return 0;
}
7. boolalpha and noboolalpha
• Function: Controls the display of boolean values. boolalpha prints true or false,
while noboolalpha prints 1 or 0.
• Syntax: boolalpha, noboolalpha
• Example:
#include <iostream.h>
#include <iomanip> // For boolalpha and noboolalpha

int main() {
bool flag = true;
cout << boolalpha << flag << endl; // Prints "true"
cout << noboolalpha << flag << endl; // Prints "1"
return 0;
}
Key Points:
• endl: Inserts a newline and flushes the stream.
• setw: Sets the width of the next field.
• setfill: Sets the fill character for fields.
• setprecision: Sets the precision for floating-point numbers.
• fixed and scientific: Control the format of floating-point numbers.
• hex, dec, and oct: Control the integer base format.
• boolalpha and noboolalpha: Control the boolean output format.
These manipulators are integral to formatting output in C++ and help in producing well-
structured and readable data presentations.

Type Casting
In C++, Type Casting can be performed using several different operators, each serving
a specific purpose. Here’s a breakdown of the type casting operators available in C++:
1. C-Style Cast
This is the traditional cast inherited from C and is the most general form of casting. It
tries different cast operations to convert the type.
int a = 10;
float b = (float)a; // C-style cast from int to float
2. static_cast
static_cast is used for conversions between types that are related by inheritance or are
of a known, safe conversion type. It is the most common cast used for basic type
conversions.
int a = 10;
float b = static_cast<float>(a); // static_cast from int to float

// Example with class inheritance


class Base {};
class Derived : public Base {};
Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr); // static_cast for safe
downcasting
3. dynamic_cast
dynamic_cast is used for safely downcasting in class hierarchies. It is particularly useful
for handling polymorphic types and checking types at runtime. dynamic_cast requires
that the class be polymorphic (i.e., have at least one virtual function).
class Base {
public:
virtual ~Base() {} // Polymorphic base class
};

class Derived : public Base {};

Base* basePtr = new Derived();


Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // dynamic_cast for
downcasting

if (derivedPtr) {
// Successful cast
} else {
// Failed cast
}
4. const_cast
const_cast is used to add or remove const or volatile qualifiers from a variable. It is
useful when you need to modify a variable that was originally defined as const.
const int a = 10;
int* b = const_cast<int*>(&a); // Removing const qualifier
*b = 20; // Modifying the value
5. reinterpret_cast
reinterpret_cast is used for low-level casting that converts any pointer type to any other
pointer type. It’s often used for casting between incompatible types and should be used
with caution as it can lead to undefined behavior if not used properly.
int a = 65;
char* p = reinterpret_cast<char*>(&a); // Reinterpreting the int as char
Summary
• C-Style Cast: General cast, not type-safe, syntax: (target_type)value.
• static_cast: Safe for well-defined conversions, including basic type conversions
and class hierarchies.
• dynamic_cast: Used for safe downcasting and checking type at runtime
(requires polymorphism).
• const_cast: Adds or removes const or volatile qualifiers.
• reinterpret_cast: Low-level cast for converting between unrelated types, should
be used with care.
Each cast operator serves different purposes and should be chosen based on the type
of conversion and safety requirements.

Control Statements
If ... Else
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
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";
}
Try it Yourself »
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Try it Yourself »
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y
(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18,
we print to the screen that "x is greater than y".
C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of
this, we move on to the else condition and print to the screen "Good evening". If the
time was less than 18, the program would print "Good day".
Short Hand If Else
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands. It can be used to replace multiple lines of code with a single
line. It is often used to replace simple if else statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
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
}
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 chapter
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:
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.
While Loop
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.

While Loop
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:

Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
The Do/While Loop
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);
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 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

You might also like