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

CPE 204 Lecture Notes

C++ is a middle-level programming language developed by Bjarne Stroustrup, combining features of both high-level and low-level languages, and is widely used for software development across various platforms. It supports object-oriented programming concepts and offers advantages such as performance efficiency, a rich standard library, and hardware independence, while also having a steep learning curve and complex syntax. C++ finds applications in operating systems, game development, and embedded systems, making it a valuable skill for software developers.

Uploaded by

Muhammad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CPE 204 Lecture Notes

C++ is a middle-level programming language developed by Bjarne Stroustrup, combining features of both high-level and low-level languages, and is widely used for software development across various platforms. It supports object-oriented programming concepts and offers advantages such as performance efficiency, a rich standard library, and hardware independence, while also having a steep learning curve and complex syntax. C++ finds applications in operating systems, game development, and embedded systems, making it a valuable skill for software developers.

Uploaded by

Muhammad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

C++ NOTE

What is C++?

C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at


Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. C++ is an extension of C programming language with object-oriented
programming concepts. In other word "C++ is a super set of C programming with additional
implementation of object-oriented concepts.

Why to Learn C++ ?

C++ is an important programming language for students and working professionals to become a
great Software Developer. The key advantages of learning C++ are:

 C++ is very close to hardware, it works at a low level which gives a full control in terms
of memory management, better performance and finally a robust software development.
 C++ programming gives you a clear understanding about Object Oriented Programming.
You will understand low level implementation of polymorphism when you will implement
virtual tables and virtual table pointers, or dynamic type identification.
 C++ is one of the every green programming languages and loved by millions of software
developers. If you are a great C++ programmer then you will never sit without work and
more importantly you will get highly paid for your work.
 C++ is the most widely used programming languages in application and system
programming. So you can choose your area of interest of software development.
 C++ really teaches you the difference between compiler, linker and loader, different data
types, storage classes, variable types their scopes etc.

Hello, World! Program Using C++

Just to give you a little excitement about C++ programming, Lets see a small conventional C++
Hello World program as shown below.

There are many C++ compilers available which you can use to compile and run above program:

 Apple C++. Xcode


 Bloodshed Dev-C++
 Clang C++
 Cygwin (GNU C++)
 Mentor Graphics
 GNU CC source
 IBM C++
 Intel C++
 Microsoft Visual C++
 Oracle C++
 HP C++

Features of C++

The following are the features of C++ programming language −

 C language compatibility: C++ provides backward compatibility with C, it supports


all features of C language.
 Object-oriented programming: C++ supports the concepts of OOPs such as objects &
classes, encapsulation, data binding, inheritance, and polymorphism.
 Compiled language: C++ is a compiler language where the complete code is converted
into machine language, which makes it a faster programming language.
 Standard template library: C++ provides many data structures and algorithms-related
library collections, such as template libraries for contains, iterators, algorithms, etc.
 Dynamic memory management: C++ provides two operators new and delete that help to
allocate and deallocate memory blocks dynamically.
 Exceptional handling: C++ provides try, catch, and throw blocks for exceptional
handling, which were not available in C programming.

Applications of C++ Programming

As stated earlier, C++ is one of the most widely used programming languages. It has it's presence
in almost every area of software development.

 Application Software Development - C++ programming has been used in developing


almost all the major Operating Systems like Windows, Mac OSX and Linux. Apart from
the operating systems, the core part of many browsers like Mozilla Firefox and Chrome
have been written using C++. C++ also has been used in developing the most popular
database system called MySQL.
 Programming Languages Development - C++ has been used extensively in developing
new programming languages like C#, Java, JavaScript, Perl, UNIX's C Shell, PHP, Python,
and Verilog etc.
 Computation Programming - C++ is the best friends of scientists because of fast speed
and computational efficiencies.
 Games Development - C++ is extremely fast which allows programmers to do procedural
programming for CPU intensive functions and provides greater control over hardware,
because of which it has been widely used in development of gaming engines.
 Embedded System - C++ is being heavily used in developing Medical and Engineering
Applications like softwares for MRI machines, high-end CAD/CAM systems etc.

This list goes on, there are various areas where software developers are happily using C++ to
provide great softwares. C++ is a statically typed, compiled, general-purpose, case-sensitive,
free-form programming language that supports procedural, object-oriented, and generic
programming.
C++ as Object-Oriented Programming

C++ fully supports object-oriented programming, including the four pillars of object-oriented
development −

 Classes and Objects


 Encapsulation
 Data hiding
 Inheritance
 Polymorphism

C++ Hello World

Get started learning C++ with the first program by printing "Hello World" on the console −

Advantages of C++

C++ programming language has many advantages over other languages. Some of these
advantages are listed as follows −

 Rich Standard Library: C++ language provides the users with a rich and useful Standard
Template Library (STL). This library has a lot of in-built methods and data structure
templates to make coding in this language efficient and quick.
 OOPS Concepts: C++ language provides users with Object-Oriented Programming
concepts like class, object, abstraction, polymorphism and much more. Hence, it acts as a
modified and better version of C programming language.
 Faster Performance: C++ language is faster in comparison to other languages
like Python, Go, C#, and many more. This makes it very useful in embedded systems and
gaming processors.
 Efficient Compiler: C++ is a compiled language. C++ compiler is very versatile, and it
can accept both procedural programs as well as object oriented programs.
 Hardware Independent: C++ language is independent of any hardware or system design.
C++ programs work on any system that has a C++/GCC compiler installed and enabled in
it.
 Large Support Base: C++ is one of the most widely used programming languages across
the globe. It has a vast community of developers and programmers. This can be explored
on platforms like Github, Reddit, Discord, DEV, Stack Overflow, and many more.

Disadvantages of C++

C++ programming language also has some disadvantages, which are listed below:

 Error Detection: C++ provides the facility of low-level design and is very close to the
hardware of the system. Hence, this may lead the user to carry out small errors that are
difficult to observe and detect.
 Large Syntax: C++ has a very lengthy code base, and many programmers find it difficult
to write such a lengthy syntax. This has drawn backlash from the user-base of languages
like Python, Go, etc., which are easier to code and simpler to execute.
 Learning Curve: As compared to Python and Go, C++ has a very steep learning curve.
Users feel that the initial building phase is very tough to learn, and there are many concepts
that beginners find difficult to understand.

Facts about C++

Here are some interesting and lesser-known facts about the C++ programming language −

 C++ language was invented at the AT&T Bell Labs, the same place where C language was
invented.
 C++ language is heavily used in NASA, where it finds applications in flight software and
command design.
 C++ is the successor of the C language. The name C++ has been taken from C only, and
the increment operator ('++') signifies that this language is the next version of C.
 C++ is widely used in areas like game development, server-side networking, TCP/IP
connections, low-level design, and many more.
 C++ programs begin by executing the main() function, and other functions are redirected
using the main() function only.
 C++ has inherited almost all features of C, and it has incorporated OOPS concepts from
Simula68 programming language.
 C++ does not support pure object-oriented programming. Programs can be executed
without the use of classes and objects, just like in procedural languages.
 There are many languages that are conceptualized using C++, and some of those are
C#, Java, JavaScript, and many more.

C++ Basic Syntax

When we consider a C++ program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what a class, object, methods,
and 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 − 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.

C++ Program Structure

The basic structure of a C++ program consists of the following parts:

 Header file section: This is the section where we include all required header files whose
functions we are going to use in the program.
 Namespace section: This is the section where we use the namespace.
 The main() section: In this section, we write our main code. The main() function is an
entry point of any C++ programming code from where the program's execution starts.
Example

Let us look at a simple code that would print the words Hello World.

Explanations to the above code

Let us look at the various parts of the above program −

 The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed.
 The line using namespace std; tells the compiler to use the std namespace. Namespaces
are a relatively recent addition to C++.
 The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
 The line int main() is the main function where program execution begins.
 The next line cout << "Hello World"; causes the message "Hello World" to be displayed
on the screen.
 The next line return 0; terminates main() function and causes it to return the value 0 to the
calling process.

Semicolons and Blocks in C++

In C++, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −

A block is a set of logically connected statements that are surrounded by opening and closing
braces. For example –

C++ does not recognize the end of the line as a terminator. For this reason, it does not matter
where you put a statement in a line. For example –

is the same as

C++ Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores, and digits (0 to 9). C++ does not allow punctuation characters
such as @, $, and % within identifiers. C++ is a case-sensitive programming language.
Thus, CPE and cpe are two different identifiers in C++.

Here are some examples of acceptable identifiers −

C++ Keywords

The following list shows the reserved words in C++. These reserved words may not be used as
constant or variable or any other identifier names.
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.

Types of C++ Comments

C++ supports two types of comments: single-line comments and multi-line comments. All
characters available inside any comment are ignored by the C++ compiler.

1. C++ Single-line Comments

A single-line comment starts with //, extending to the end of the line. These comments can last
only till the end of the line, and the next line leads to a new comment.

Syntax of single line comment

The following syntax shows how to use a single-line comment in C++:

Example

In the following example, we are creating single-line comments −


2. C++ Multi-line Comments

Multi-line comments start with /* and end with */. Any text in between these symbols is treated
as a comment only.

Syntax

The following syntax shows how to use a multi-line comment in C++:

Example

In the following example, we are creating multi-line comments −

Comments within Statements


We can also comment-out specific statements within a code block inside a C++ program. This is
done using both types of comments.

Example

The following example explains the usage of multi-line comments within statements −

Example

The following example explains the usage of single-line comments within statements −

Purpose of Comments

Comments are used for various purposes in C++. Some of the main areas of application of
comments are given as follows:

 To represent a short and concise step in the program for users to understand better.
 To explain a step in a detailed way that is not expressed explicitly in the code.
 To leave different hints for users to grab in the code itself.
 To leave comments for fun or recreation.
 To temporarily disable part of the code for debugging purposes.
 To add metadata to the code for future purposes.
 To create documentation for the code, for example, in Github pages.

C++ Data Types


While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, integer, floating point,
double floating point, boolean etc. Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved memory.

Primitive Built-in Types

C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −

The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.

The size of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.
Example

Following is the example, which will produce correct size of various data types on your
computer.

This example uses endl, which inserts a new-line character after every line and << operator is
being used to pass multiple values out to the screen. We are also using sizeof() operator to get
size of various data types.

Derived Data Types

Data types which are obtained from pre-defined data types in C++ are known as Derived Data
Types. These can be classified into four categories, namely −

1. Function

A function is the simplest form of user-defined data type. It includes a return type, a function
name and input parameters.

Syntax
Example

2. Array

An array is a series of elements of same data type. Elements of an array are stored in contiguous
memory locations in the storage.

Syntax

Example
3. Pointer

A pointer is a reference to an element defined previously. The value of the pointer returns the
address location of the element which is associated with it.

Syntax

User-Defined Data Types

Data types which are defined by the user intuitively without using any pre-defined data types are
known as User-Defined Data Types. These data types can be further categorized into five types,
namely:

1. Class

A class is a defined in Object Oriented Programming as a custom data type which is used to
construct an object. It is the framework of an object, and it can include constructors, methods and
OOP concepts like Polymorphism, Inheritance, etc.
Syntax

Example

C++ Numeric Data Types

1. The int Data Type

The int data type is short for integer, which takes numeric values from -231 to (231-1). It takes 4
Bytes (i.e., 32 bits) in the memory.

Syntax
int variable_name;

2. The float data type


The float data type is used for floating-point elements, which are numbers that are followed by a
decimal part. This data type takes 4 Bytes (i.e., 32 bits) of memory.

Syntax
float elem_name;

3. The double data type

The double data type is used to store floating-point elements with double precision as compared
to float. This data type takes 8 Bytes (i.e., 64 bits) of memory.

Syntax
double elem_name;

C++ Variables and Types

C++ Variable

A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.

C++ Variable Naming

The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++
is case-sensitive.

Some other rules for variable naming conventions in C++ −

 Keywords cannot be used as variable names.


 The variable name cannot contain spaces.
 Hyphen (-) cannot be used within the variable names.
 Variable names must not start with special characters and numbers. It should be either an
uppercase or lowercase character or an underscore (_).
Example of Valid Variable Names

Some of the valid variable names are −

Types of C++ Variables

There are following basic types of variable in C++


Variable Scope in C++

A scope is a region of the program and broadly speaking there are three places, where variables
can be declared. C++ variables scopes are categorized into two parts −

 Local Variables
 Global Variables

Local Variables

Variables that are declared inside a function or block are local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
Example

Following is the example using local variables −

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.

Example

Following is the example using global and local variables −

Local and Global Variables with Same Names


A program can have same name for local and global variables but value of local variable inside a
function will take preference.

Example

When the above code is compiled and executed, it produces the following result − 10

Accessing Global Variable

You can access a global variable when there is a local variable with the same name by using
the SRO (Scope Resolution Operator) :: before the name of that variable.

Example

In the following example, we have global and local variables with the same name, and accessing
and printing the value of the global variable −
When the above code is compiled and executed, it produces the following result −

Value of g (Local variable): 10


Value of g (Global variable): 20

C++ Basic Input/Output

The C++ standard libraries provide an extensive set of input/output capabilities. This chapter will
discuss very basic and most common I/O operations required for 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.

C++ Header Files

There are following header files important to C++ programs –

Operators in C++

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.

1. Arithmetic Operators: Arithmetic operators in C++ are the basic operators, which are
used for basic mathematical or arithmetical operations on operands. These operators are
essential for performing calculations and manipulating data within a program.

There are following arithmetic operators supported by C++ language −

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

Example

The following is an example of arithmetic operators −

#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
return 0;

Output
Line 1 - Value of c is :31
Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1
Line 6 - Value of c is :21
Line 7 - Value of c is :22

2. Relational Operators

Relational operators are used to compare two values or expressions. These operators return a
boolean value − true if the comparison is correct, and else false. They are essential for making
decisions and controlling the flow of a program based on conditions. There are following
relational operators supported by C++ language

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


Example

The following is an example of relational operators −

#include <iostream>
using namespace std;

main() {
int a = 21;
int b = 10;
int c ;

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

if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}

/* Let's change the values of a and b */


a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than \ or equal to b" << endl ;
}

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

return 0;

Output
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

3. Logical Operators

Logical operators are used to perform logical operations on boolean values (true or false). These
operators are essential for controlling the flow of a program based on conditions. There are three
primary logical operators in C++ as mentioned below −

There are following logical operators supported by C++ language.

Assume variable A holds 1 and variable B holds 0, then −


Example

The following is an example of logical operators −

#include <iostream>
using namespace std;

main() {
int a = 5;
int b = 20;
int c ;

if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}

if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}

/* Let's change the values of a and b */


a = 0;
b = 10;

if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}

if(!(a && b)) {


cout << "Line 5 - Condition is true"<< endl ;
}

return 0;
}

Output
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true

4. Bitwise Operators

Bitwise operators are used to perform operations at the bit level on integer data types. These
operations work on direct manipulation of bits, such as low-level programming, graphics, and
cryptography. Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −
Example

The following is an example of bitwise operators −

#include <iostream>
using namespace std;

main() {
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;

c = a & b; // 12 = 0000 1100


cout << "Line 1 - Value of c is : " << c << endl ;

c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;

c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;

c = ~a; // -61 = 1100 0011


cout << "Line 4 - Value of c is: " << c << endl ;

c = a << 2; // 240 = 1111 0000


cout << "Line 5 - Value of c is: " << c << endl ;

c = a >> 2; // 15 = 0000 1111


cout << "Line 6 - Value of c is: " << c << endl ;

return 0;

Output
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15

5. Assignment Operators

Assignment operators are used to assign values to variables. These operators allow you to set or
update the value stored in a variable.

There are following assignment operators supported by C++ language −

Operator Description Example

Simple assignment operator, Assigns values C = A + B will assign value of A + B into


=
from right side operands to left side operand. C

Add AND assignment operator, It adds right


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

Subtract AND assignment operator, It subtracts


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

Multiply AND assignment operator, It


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

Divide AND assignment operator, It divides left


/= operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

Modulus AND assignment operator, It takes


%= modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

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


>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

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

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Example

The following is an example of assignment operators −

#include <iostream>
using namespace std;

main() {
int a = 21;
int c ;

c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;

c += a;
cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ;

c -= a;
cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ;

c *= a;
cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ;

c /= a;
cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ;

c = 200;
c %= a;
cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl ;

c <<= 2;
cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl ;

c >>= 2;
cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl ;

c &= 2;
cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl ;

c ^= 2;
cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ;

c |= 2;
cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ;
return 0;

Output
Line 1 - = Operator, Value of c = : 21
Line 2 - += Operator, Value of c = : 42
Line 3 - -= Operator, Value of c = : 21
Line 4 - *= Operator, Value of c = : 441
Line 5 - /= Operator, Value of c = : 21
Line 6 - %= Operator, Value of c = : 11
Line 7 - <<= Operator, Value of c = : 44
Line 8 - >>= Operator, Value of c = : 11
Line 9 - &= Operator, Value of c = : 2
Line 10 - ^= Operator, Value of c = : 0
Line 11 - |= Operator, Value of c = : 2

6. Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

C++ decision making statements

Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the
programming languages –
C++ programming language provides following types of decision making statements

S/No. Statement & Description

if statement
1
An ‘if’ statement consists of a boolean expression followed by one or more statements.

if...else statement
2 An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the
boolean expression is false.

switch statement
3
A ‘switch’ statement allows a variable to be tested for equality against a list of values.

nested if statements
4
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).

1. 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
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";

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

3. The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}

Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

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

Explanations

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;
cout<<”Enter day number: ”;
cin>>day;
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;
default:
cout << "Invalid choice";
}
// Outputs the day

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.

5. C++ 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++;
}

6. 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);

In this example, a program that only print even numbers between 0 and 10 (inclusive):

Example
int i = 0;

while (i <= 10) {


cout << i << "\n";
i += 2;
}

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

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}

C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can
use an array literal - place the values in a comma-separated list, inside curly braces:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};

Access the Elements of an Array


You access an array element by referring to the index number inside square brackets [].

This statement accesses the value of the first element in cars:


Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

Example
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

// Loop through strings


for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}

This example outputs the index of each element together with its value:

Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}

C++ Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():

Syntax
void myFunction() {
// code to be executed
}
Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn more about
return values later in the next chapter
 inside the function (the body), add code that defines what the function should do

Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, 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;
}
// Outputs "I just got executed!"
A function can be called multiple times:

Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Function Declaration and Definition

A C++ function consist of two parts:


 Declaration: the return type, the name of the function, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}
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;
}

void myFunction() {
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
definition below main(). This will make the code better organized and easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Function Parameters
Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the
function.

Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a function that takes a string called fname as parameter. When the
function is called, we pass along a first name, which is used inside the function to print the full
name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the function, it is called an argument. So,


from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

You might also like