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

BTech C++-1

The document provides an introduction to computer technology, covering topics such as computer organization, components, input/output devices, and programming. It explains the functionalities of computers, differentiates between hardware and software, and describes algorithms and flowcharts used in programming. Additionally, it outlines the roles of the CPU, BIOS, and boot loader, as well as the importance of proper program design and documentation.

Uploaded by

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

BTech C++-1

The document provides an introduction to computer technology, covering topics such as computer organization, components, input/output devices, and programming. It explains the functionalities of computers, differentiates between hardware and software, and describes algorithms and flowcharts used in programming. Additionally, it outlines the roles of the CPU, BIOS, and boot loader, as well as the importance of proper program design and documentation.

Uploaded by

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

INTRODUCTION TO COMPUTER

TECHNOLOGY

BEEE 165

[email protected]
OBJECTIVES

 To introduce students to computer organization,


input/output devices and computer programming
COMPUTERS

 Computers are intelligent devices that mimic human behavior with


respect to remembering data and events, processing information, and
making logical decisions.
 Information is stored, recalled, manipulated, and combined in their
circuitry to achieve a desired effect.
Functionalities of a computer
Any digital computer carries out five functions in gross terms:

Takes data as input


Stores the data/instructions in its memory and use them when
required.
Processes the data and converts it into useful information
Generates the output
Controls all the above four steps.
Computer Components
Any kind of computers consists of HARDWARE
AND SOFTWARE
HARDWARE

Computer hardware is the collection of physical


elements that constitutes a computer system.
Computer hardware refers to the physical parts
or components of a computer such as the
monitor, mouse, keyboard, computer data
storage, hard drive disk (HDD), system unit
(graphic cards, sound cards, memory,
motherboard and chips), etc. all of which are
physical objects that can be touched.
COMPUTER HARDWARE

 Physical components including wires, electronics, circuits, cards,


boards, and various peripheral devices are classified as hardware.
Information is stored on permanent recordable media such as hard
disk drives (HDD), commonly called hard drives (HD), compact disks
with read-only memory (CD-ROM), and digital versatile discs (DVD).
Input Devices
Input device is any peripheral (piece
of computer hardware equipment to
provide data and control signals to an
information processing system such as
a computer or other information
appliance.
Input device Translate data from form
that humans understand to one that the
computer can work with. Most
common are keyboard and mouse
Example of Input Devices

1. Keyboard 2. Mouse (pointing device) 3. Microphone


4. Touch screen 5. Scanner 6. Webcam
7. Touchpads 8. MIDI keyboard 9. Gamepad
10. Graphics Tablets 11. Cameras 12. Pen Input
13. Barcode reader 14. Microphone 15. Barcode reader
16. Electronic Whiteboard 17. Digital camera 18. Joystick

Note: The most common use keyboard is the QWERTY keyboard.


Generally standard Keyboard has 104 keys.
Central Processing Unit (CPU)
A CPU is brain of a computer. It is responsible for all functions and processes. Regarding computing power, the
CPU is the most important element of a computer system.
The CPU is comprised of three main parts :
* Arithmetic Logic Unit (ALU): Executes all arithmetic and logical operations. Arithmetic calculations like as
addition, subtraction, multiplication and division. Logical operation like compare numbers, letters, or special
characters
* Control Unit (CU): controls and co-ordinates computer components.

1. Read the code for the next instruction to be executed.
2. Increment the program counter so it points to the next instruction.
3. Read whatever data the instruction requires from cells in memory.

1. Provide the necessary data to an ALU or register.

1. If the instruction requires an ALU or specialized hardware to complete, instruct the hardware to perform
the requested operation.

• Registers :Stores the data that is to be executed next, "very fast storage area".
Output devices
An output device is any piece of computer hardware
equipment used to communicate the results of data
processing carried out by an information processing system
(such as a computer) which converts the electronically
generated information into human-readable form.
Note
Basic types of monitors are
• Cathode Ray Tube (CRT).
• Liquid Crystal Displays (LCD)
• Light-emitting diode (LED). 1. Monitor 2. LCD Projection Panels

3. Printers (all types) 4. Projector


Printer types:
• Laser Printer. 5. Plotters 6. Speaker(s)

• Ink Jet Printer.


• Dot Matrix Printer
COMPUTER SOFTWARE

Software is a generic term for organized collections of computer data and


instructions, often broken into two major categories: system software that
provides the basic non-task-specific functions of the computer, and application
software which is used by users to accomplish specific tasks.
Software Types
A. System software is responsible for controlling, integrating, and managing the individual hardware components of a
computer system so that other software and the users of the system see it as a functional unit without having to be
concerned with the low-level details such as transferring data from memory to disk, or rendering text onto a display.
Generally, system software consists of an operating system and some fundamental utilities such as disk formatters, file
managers, display managers, text editors, user authentication (login) and management tools, and networking and device
control software.

B. Application software is used to accomplish specific tasks other than just running the computer system. Application
software may consist of a single program, such as an image viewer; a small collection of programs (often called a software
package) that work closely together to accomplish a task, such as a spreadsheet or text processing system; a larger
collection (often called a software suite) of related but independent programs and packages that have a common user
interface or shared data format, such as Microsoft Office, which consists of closely integrated word processor, spreadsheet,
database, etc.; or a software system, such as a database management system, which is a collection of fundamental programs
that may provide some service to a variety of other independent applications.
Comparison Application Software and System Software
System Software Application Software
Computer software, or just software is a

general term primarily used for digitally stored Application software, also known as an

data such as computer programs and other application or an "app", is computer software

kinds of information read and written by designed to help the user to perform specific

computers. App comes under computer tasks.

software though it has a wide scope now.


Example: 1) Opera (Web Browser)
1) Microsoft Windows
2) Microsoft Word (Word Processing)
2) Linux
3) Microsoft Excel (Spreadsheet software)
3) Unix
4) MySQL (Database Software)
4) Mac OSX
5) Microsoft PowerPoint (Presentation Software)
5) DOS
6) Adobe Photoshop (Graphics Software)
Interaction: Users always interact with application software
Generally, users do not interact with system
while doing different activities.
software as it works in the background.

Dependency: System software can run independently of the Application software cannot run without the

application software. presence of the system software.


BIOS
The basic input/output system (BIOS) is a small set of instructions
executed when the computer is first switched on.
The BIOS is unrelated to the installed operating system (OS), and is
specific to the electronic hardware.
Its purpose is to activate the keyboard and monitor, and then run a
small program called the boot loader which, in turn, launches the
operating system.
THE BOOT LOADER
The boot loader resides in the first partition of a permanent recordable medium, called the boot sector

or master boot record (MBR).

If multiple media are present, the BIOS searches through a pre-determined yet programmable list, and

launches the first available boot loader.

Dual-boot computers allow the alternative loading of multiple operating systems with the help of an

advanced boot loader such as the GRand Uni-fied Bootloader (GRUB).

GRUB Stage 1, residing in the master boot record, launches GRUB Stage 2, residing anywhere in the

disk. A menu of options is then presented and the OS of choice is loaded.


ASSIGNMENT ONE (1)

 Conduct an Internet search to compile a list of six operating systems


currently in use.
 Conduct an Internet search to learn whether the BIOS also initializes
the mouse.
INTRODUCTION TO COMPUTER
PROGRAMMING
The sequence of steps to be performed in order to solve a problem by
the computer is known as an algorithm.
Flowchart is a graphical or symbolic representation of an algorithm. It is
the diagrammatic representation of the step-by-step solution to a given
problem.
Program Design consists of the steps a programmer takes before they
start coding the program in a specific language. Proper program design
helps other programmers to maintain the program in the future.
AL GORITHM

The sequence of steps to be performed in


order to solve a problem by the computer is
known as an algorithm

In mathematics, computer science, and


related subjects, an algorithm is a finite
sequence of steps expressed for solving a
problem. An algorithm can be defined as
“a process that performs some sequence of
operations in order to solve a given
problem”. Algorithms are used for
calculation, data processing, and many
other fields.
ALGORITHM
In computer programming, there are often many different algorithms
to accomplish any given task.
Each algorithm has advantages and disadvantages in different
situations.
Sorting is one place where a lot of research has been done, because
computers spend a lot of time sorting lists.
ALGORITHM
For example, consider that we need to find the sum, average and
product of 3 numbers given by the user.

Algorithm for the given problem is as follows:

Read X, Y, Z
Compute Sum (S) as X + Y + Z
Compute Average (A) as S / 3
Compute Product (P) as X x Y x Z
3 REASONS FOR USING ALGORITHMS

Reasons for using algorithms are:


Efficiency

Abstraction

Reusability
EFFICIENCY

 Certain types of problems, like sorting, occur often in computing.


Efficient algorithms must be used to solve such problems considering
the time and cost factor involved in each algorithm.
ABSTRACTION
 Algorithms provide a level of abstraction in solving problems because many
seemingly complicated problems can be distilled into simpler ones for which well
known algorithms exist.
Once we see a more complicated problem in a simpler light, we can think of the
simpler problem as just an abstraction of the more complicated one. For example,
imagine trying to find the shortest way to route a packet between two gateways in
an internet.
Once we realize that this problem is just a variation of the more general shortest
path problem, we can solve it using the generalised approach.
REUSABILITY

Algorithms are often reusable in many different situations. Since


many well-known algorithms are the generalizations of more
complicated ones, and since many complicated problems can be
distilled into simpler ones, an efficient means of solving certain
simpler problems potentially lets us solve many complicated
problems.
FLOWCHART
A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or

process. Each step in the process is represented by a different symbol and contains a short
description of the process step.

The flow chart symbols are linked together with arrows showing the process flow direction.

A flowchart typically shows the flow of data in a process, detailing the operations/steps in a

pictorial format which is easier to understand than reading it in a textual format

A flowchart describes what operations (and in what sequence) are required to solve a given

problem
WHAT FLOWCHART ARE USED FOR
The purpose of all flow charts is to communicate how a process
works or should work without any technical or group specific jargon.
Flowcharts are used in analyzing, designing, documenting or
managing a process or program in various fields.
FLOWCHART
Write (Display) the Sum, Average and Product

Flowchart for the above problem will look like


ADVANTAGES OF USING
FLOWCHARTS
 Communication: Flowcharts are better way of communicating the logic of a system to all concerned.

 Effective analysis: With the help of flowchart, problem can be analysed in more effective way.

 Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various

purposes.

 Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program

development phase.

 Proper Debugging: The flowchart helps in debugging process.

 Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart.

It helps the programmer to put efforts more efficiently on that part.


LIMITATIONS OF USING
FLOWCHARTS
Although a flowchart is a very useful tool, there are a few limitations in using flowcharts

which are listed below:

Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart

becomes complex and clumsy.

Alterations and Modifications: If alterations are required the flowchart may require re-drawing

completely.

Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a

problem.

The essentials of what is done can easily be lost in the technical details of how it is done.
WHEN TO USE A FLOWCHART
 To communicate to others how a process is done.

 A flowchart is generally used when a new project begins in order to plan for the project.

 A flowchart helps to clarify how things are currently working and how they could be improved. It also assists in finding the key

elements of a process, while drawing clear lines between where one process ends and the next one starts.

 Developing a flowchart stimulates communication among participants and establishes a common understanding about the process.

Flowcharts also uncover steps that are redundant or misplaced.

 Flowcharts are used to help team members, to identify who provides inputs or resources to whom, to establish important areas for

monitoring or data collection, to identify areas for improvement or increased efficiency, and to generate hypotheses about causes.

 It is recommended that flowcharts be created through group discussion, as individuals rarely know the entire process and the

communication contributes to improvement.

 Flowcharts are very useful for documenting a process (simple or complex) as it eases the understanding of the process.

 Flowcharts are also very useful to communicate to others how a process is performed and enables understanding of the logic of a

process.
FLOWCHART SYMBOLS &
GUIDELINES
Flowcharts are usually drawn using some standard symbols; however,
some special symbols can also be developed when required. Some
standard symbols, which are frequently required for flowcharting
many computer programs are shown below.
Terminator: An oval flow chart shape indicates the start or end of the
process, usually containing the word “Start” or “End”.
FLOWCHART SYMBOLS &
GUIDELINES
Process: A rectangular flow chart shape indicates a normal/generic process flow
step. For example, “Add 1 to X”, “M = M*F” or similar.

Decision: A diamond flow chart shape indicates a branch in the process flow. This
symbol is used when a decision needs to be made, commonly a Yes/No question or
True/False test.

Connector: A small, labelled, circular flow chart shape used to indicate a jump in
the process flow. Connectors are generally used in complex or multi-sheet
diagrams.
FLOWCHART SYMBOLS &
GUIDELINES
Data: A parallelogram that indicates data input or output (I/O) for a process.
Examples: Get X from the user, Display X.
Delay: used to indicate a delay or wait in the process for input from some other
process.
Arrow: used to show the flow of control in a process. An arrow coming from one
symbol and ending at another symbol represents that control passes to the symbol
the arrow points to.

These are the basic symbols used generally


BASIC GUIDELINES FOR DRAWING A
FLOWCHART
 . Now, the basic guidelines for drawing a flowchart with the above symbols are that:

 In drawing a proper flowchart, all necessary requirements should be listed out in logical order.

 The flowchart should be neat, clear and easy to follow. There should not be any room for ambiguity in

understanding the flowchart.

 The flowchart is to be read left to right or top to bottom.

 A process symbol can have only one flow line coming out of it.

 For a decision symbol, only one flow line can enter it, but multiple lines can leave it to denote possible

answers.

 The terminal symbols can only have one flow line in conjunction with them.
BASIC FLOWCHART
Example: Consider a problem of finding the largest number between A and
B
Algorithm for the above problem is as follows:
Read A, B
If A is less than B
BIG=B
SMALL = A
Else
BIG=A
SMALL = B

 Write (Display) BIG, SMALL Flowchart for the above algorithm will look like:
Given below is the Detailed Flowchart
of an Order Filling Process which
shows the sub-steps involved in the
process and also reveals the delays that
occur when the materials required are
not available in the inventory

Using the flowchart write the algorithm


for Order Filling Process. (20marks)
C++ INTRODUCING
C++ is a general purpose programming language that supports various
computer programming models such as object-oriented programming and
generic programming. It was created by Bjarne Stroustrup and, “Its main
purpose was to make writing good programs easier and more pleasant for the
individual programmer.”

By learning C++, you can create applications that will run on a wide variety of
hardware platforms such as personal computers running Windows, Linux,
UNIX, and Mac OS X, as well as small form factor hardware such as Arduino–
based boards
WHY LEARN C++ PROGRAMMING?

The C++ language is favored by many professional programmers because

it allows them to create fast, compact programs that are robust and
portable.

Using a modern C++ Integrated Development Environment (IDE), such as

Microsoft’s Visual Studio Community Edition, the programmer can


quickly create complex applications. But to use these tools to greatest
effect, the programmer must first learn quite a bit about the C++ language
itself.
SHOULD I LEARN C FIRST?

Opinion is divided on the question of whether it is an advantage to be


familiar with C programming before moving on to C++. It would seem
logical to learn the original language first in order to understand the
larger extended language more readily. However, C++ is not simply a
larger version of C, as the approach to object-oriented programming
with C++ is markedly different to the procedural nature of C. It is,
therefore, arguably better to learn C++ without previous knowledge of
C to avoid confusion.
COMPILER

Compilers refer to the process of turning your code into executable


form. Each platform or operating system may have different compilers
available from different providers such as Microsoft, Intel, or Oracle.
A C++ program has a very specific structure in terms of how the code is
written and some key elements that you use in your C++ programs. The
simplest of C++ programs is shown here.
1. #include <iostream>
2. int main()
3. {
4. std::cout << "Hello World!";
5. return 0;
6. }
In this simple program we notice some elements listed. The line numbers are used for reference

only and are not part of the program code.

Line 1: this is known as a pre-processor directive. it instructs the compiler to locate the file that

contains code for a library known as iostream. This library contains code that allows for input

and output to streams, such as the console window.

Line 2: Every C++ program must have a method known as main(). It is referred to as the entry

point for the application when you start execution of the program on your computer. The int

portion is the return type of the method. The empty parentheses () after the method name

indicate that this is a method and that it takes no arguments, in other words, there are no

parameters for passing in values.


Line 3: Method bodies in C++ start with an open curly brace. Line 4: This code uses a method known as cout

(pronounced "see out") to send the text Hello World! to the console for output and display. The std:: prefix to this

command is a way of indicating that cout is part of a namespace known as std. The :: is used to indicate that cout

is part of the std namespace.

Also notice that the line ends with a semi-colon. C++ statements are terminated with semi-colons.

Line 5: The return statement is used to end a function or method when a value is expected to be sent back to a

caller. In this case, the caller is the operating system and the value returned is an integer value of 0. If the program

reaches this statement, returning a value of 0 is an indication to the operating system that the code has been

executed successfully. In the past, programmers would return 0 to indicate successful execution and non-zero

values to indicate that an error had occurred in the program somewhere.

Line 6: This line closes out the body of the function main() and is necessary so the compiler knows where the

function or method ends, but is also used for other purposes that will be covered later in the course on variable
C++ is a case sensitive language. Case sensitivity means that your keywords and variable
declarations must match the case. For example, a C++ keyword for a constant type is const.
If you were to type Const or CONST, the compiler would not know that your intention was to
use the keyword const.
Aside from the case sensitivity, C++ also has a defined outline for program code and specific
"elements" found in a typical C++ application. These elements consist of:
Preprocessor directives which are used to have the compiler execute tasks prior to compiling
the source code
using directives which are utilized to indicate which namespaces to include in a source code
file
a function header which consists of a return type, function name, and parameters
a function body containing the code that performs the actions required of that function
statements that are contained in the C++ source code file
comments for documenting the source code for programmers to understand what the code is intended to do

a return statement that sends data back to the function caller

curly braces to enclose bodies of statements. Commonly used to denote the body of a function or a flow

controls statement such as a for loop

C++ source code also permits judicious use of white space (tabs, spaces, new lines) to create code that is

easier to read. The compiler completely ignores the white space, with a small exception concerning if

statements that will be covered later. It is highly recommended that you make use of white space to indent

and separate lines of code to aid in readability of your source code files.

NOTE: Unlike Python, indenting lines after the for statement does not tell the compiler to execute those

indented lines as part of the for statement. In C++, multiple statements for a single for statement, must be

enclosed in curly braces. This will be covered more in Module 3, Control Statements.
C++ Statements
 A C++ program is comprised of various components such as functions, methods, classes, etc. The instructions that

form part of a C++ program typically reside inside of functions or methods. These functions are comprised of C++

statements. You will find yourself using various types of statements in your C++ code as listed here:

 declarations - these are used to declare variables and constants that will be used in your application

 assignments - these are used to assign values to variables in your application code

 preprocessor directives - covered in the topic on Code Formatting

 comments - used to document your code

 function declarations - covered in the topic on Code Formatting

 executable statements - these are used to perform operations and execute instructions. Examples would be cout <<

"Hello World!"; which outputs Hello World! to the console.

 You will use these statement types throughout this and successive courses on C++.
C++ Install IDE

• An IDE (Integrated Development Environment) is used to edit AND


compile the code.
• Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These
are all free, and they can be used to both edit and debug C++ code.
• Note: Web-based IDE's can work as well, but functionality is limited.
• We will use Code::Blocks
MY FIRST C++ PROGRAM
 #include <iostream>
using namespace std;

int main()
 {
cout << "Hello World!";
return 0;
}
 Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in
line 5). Header files add functionality to C++ programs.
 Line 2: using namespace std means that we can use names for objects and variables from the standard library.
 Don't worry if you don't understand how #include <iostream> and using namespace std works. Just think of it as
something that (almost) always appears in your program.
 Line 3: A blank line. C++ ignores white space.
 Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its
curly brackets {} will be executed.
 Line 5: cout (pronounced "see-out") is an object used to output/print text. In our example it will output "Hello World".
 Note: Every C++ statement ends with a semicolon ;.
 Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
 Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
 Line 6: return 0 ends the main function
C++ Output (Print Text)
• The cout object, together with the << operator, is used to output values/print text:
• Example:
• #include <iostream>
using namespace std;

int main()
• {
cout << "Hello World!";
return 0;
}
• You can add as many cout objects as you want. However, note that it does not insert a new line at
the end of the output:
• Example:
• #include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
C++ Comments
 Comments can be used to explain C++ code, and to make it more readable. It can also be used
to prevent execution when testing alternative code. Comments can be singled-lined or
multi-lined.
 Single-line comments start with two forward slashes (//).
 Any text between // and the end of the line is ignored by the compiler (will not be executed).
 This example uses a single-line comment before a line of code:
 Example:
 // This is a comment
cout << "Hello World!";
 C++ Multi-line Comments
 Multi-line comments start with /* and ends with */.
 Any text between /* and */ will be ignored by the compiler
 Example:
 /* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
 Variables are containers for storing data values.
 In C++, there are different types of variables (defined with different
keywords), for example:
 int - stores integers (whole numbers), without decimals, such as 123 or -
123
 double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded
by double quotes
 bool - stores values with two states: true or false
Declaring (Creating) Variables
• To create a variable, you must specify the type and assign it a value:
• Syntax
• type variable = value;
• Where type is one of C++ types (such as int), and variable is the name of the variable (such as x or myName).
The equal sign is used to assign values to the variable.
• To create a variable that should store a number, look at the following example:
• Example:
• int myNum = 15;
cout << myNum;
• You can also declare a variable without assigning the value, and assign the value later:
• Example:
• int myNum;
myNum = 15;
cout << myNum;
• Note that if you assign a new value to an existing variable, it will overwrite the previous value
• Example:
• int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
• However, you can add the const keyword if you don't want others (or yourself) to override existing values (this
Other Types
A demonstration of other data types

Example:

int myNum = 5; // Integer (whole number without decimals)


double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Display Variables
• The cout object is used together with the << operator to display
variables.
• To combine both text and a variable, separate them with
the << operator
Example:
int myAge = 35;
cout << "I am " << myAge << " years old.";
Add Variables Together
• To add a variable to another variable, you can use the + operator:
• Example:
• int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
Declare Many Variables
• To declare more than one variable of the same type, you can use
a comma-separated list:
• Example:
• int x = 5, y = 6, z = 50;
cout << x + y + z;
C++ Identifiers
• All C++ variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code.
• The general rules for constructing names for variables (unique identifiers)
are:
• Names can contain letters, digits and underscores
• Names must begin with a letter or an underscore (_)
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Names cannot contain whitespaces or special characters like !, #, %, etc.
• Reserved words (like C++ keywords, such as int) cannot be used as names
C++ User Input
• You have already learned that cout is used to output (print) values. Now we will use cin to
get user input.
• cin is a predefined variable that reads data from the keyboard with the extraction operator
(>>).
• In the following example, the user can input a number, which is stored in the variable x. Then
we print the value of x:
• Example:
• int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
• In this example, the user needs to input two numbers, and then we print the sum
• Example:
• int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
C++ Data Types
• As explained in the Variables
chapter, a variable in C++ must be a specified data type:

• Example:

• int myNum = 5; // Integer (whole


number)
float myFloatNum = 5.99; // Floating point
number
double myDoubleNum = 9.98; // Floating point
number
Basic Data Types
• The data type specifies the size and type of information the variable will store:
• Data Type Size Description
• int 4 bytes : Stores whole numbers, without decimals
• float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits
• double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits
• Boolean 1 byte Stores true or false values char 1 byte Stores a single character/letter/number, or ASCII values
Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double when you need a
floating point number (with decimals), like 9.99 or 3.14515.
• Example:
• INT: int myNum = 1000;
cout << myNum;
• Float: float myNum = 5.75;
cout << myNum;
• Double :double myNum = 19.99;
cout << myNum;
Difference between float vs. double

The precision of a floating point value indicates how many digits the
value can have after the decimal point.

The precision of float is only six or seven decimal digits


while
double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.
Booleans
• A boolean data type is declared with the bool keyword and can
only take the values true or false. When the value is
returned, true = 1 and false = 0.
• Example:
• bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Characters
• The char data type is used to store a single character. The
character must be surrounded by single quotes, like 'A' or 'c':
• Example
• char myGrade = 'B';
cout << myGrade;
• Alternatively, you can use ASCII values to display certain
characters:
• Example
• char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
Strings
• The string type is used to store a sequence of characters (text). This is not a built-in type,
but it behaves like one in its most basic usage. String values must be surrounded by double
quotes:
• Example
• string greeting = "Hello";
cout << greeting;
• To use strings, you must include an additional header file in the source code,
the <string> library:
• Example
• // Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

// Output string value


cout << greeting;
C++ Operators
• Operators are used to perform operations on variables and values.
• The value is called an operand, while the operation (to be performed between the two operands) is defined
by an operator:
• Operand Operator Operand 100 + 50 In the example below, the numbers 100 and 50
are operands, and the + sign is an operator:
• Example
• int x = 100 + 50;
• Although the + operator is often used to add together two values, like in the example above, it can also be
used to add together a variable and a value, or a variable and another variable:
• Example
• int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
• C++ divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.
Operator 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 from 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


C++ 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; Operator Example Same As

The addition assignment operator (+=) adds a value to a variable: = x=5 x=5

Example += x += 3 x=x+3

int x = 10; -= x -= 3 x=x-3

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


C++ Comparison Operators
• Comparison operators are used to compare two values.
• Tip: The return value is either true (1) or false (0). You will learn more about them
and how to use them in a later chapter.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


C++ Logical Operators

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
Strings are used for storing text.
A string variable contains a collection of characters surrounded
by double quotes:
Example
Create a variable of type string and assign it a value:
string greeting = "Hello";
To use strings, you must include an additional header file in the
source code, the <string> library:
Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";
String Concatenation
The + operator can be used between strings to add them together to make a new string.
This is called concatenation:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
Note that we added a space after firstName to create a space between John and Doe on
output
String Length
• A string in C++ is actually an object, which contain functions that
can perform certain operations on strings. For example, the length
of a string can be found with the length() function:
• Example
• string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " <<
txt.length();
Access Strings
• You can access the characters in a string by referring to its index number inside square brackets [].
• This example prints the first character in myString:
• Example
• string myString = "Hello";
cout << myString[0];
// Outputs H

• Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
• This example prints the second character in myString:
• Example
• string myString = "Hello";
cout << myString[1];
// Outputs e

• To change the value of a specific character in a string, refer to the index number, and use single quotes:
• Example
• string myString = "Hello";
myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello
User Input Strings
It is possible to use the extraction operator >> on cin to display a string entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John


// Your name is: John
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only display a
single word (even if you type many words):
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe


• From the example above, you would expect the program to print "John Doe", but
it only prints "John".

That's why, when working with strings, we often use the getline() function to
read a line of text. It takes cin as the first parameter, and the string variable as
second:
• Example
• string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John Doe
Adding Numbers and Strings
• WARNING!
• C++ uses the + operator for both addition and concatenation.
• Numbers are added. Strings are concatenated.
• If you add two numbers, the result will be a number:
• Example
• int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
• If you add two strings, the result will be a string concatenation:
• Example
• string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
• If you try to add a number to a string, an error occurs:
• Example
• string x = "10";
int y = 20;
string z = x + y;
Omitting Namespace
• You might see some C++ programs that runs without the standard namespace

library. The using namespace std line can be omitted and replaced with

the std keyword, followed by the :: operator for string (and cout) objects:
• Example
• #include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
• It is up to you if you want to include the standard namespace library or not.
C++ Math
• C++ has many functions that allows you to perform mathematical tasks on numbers.Max
and min

• The max(x,y) function can be used to find the highest value of x and y:

• Example

• cout << max(5, 10);

• And the min(x,y) function can be used to find the lowest value of x and y:

• Example

• cout << min(5, 10);


C++ <cmath> Header
• Other functions, such as sqrt (square root), round (rounds a number)
and log (natural logarithm), can be found in the <cmath> header file:

• Example

• // Include the cmath library


#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);
Other Math Functions
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
A list of other
atan(x) Returns the arctangent of x, in radians
popular Math cbrt(x) Returns the cube root of x
functions (from ceil(x) Returns the value of x rounded up to its nearest integer
the <cmath> library) cos(x) Returns the cosine of x, in radians

can be found in the cosh(x) Returns the hyperbolic cosine of x, in radians

table below: exp(x) Returns the value of Ex


expm1(x) Returns ex -1
fabs(x) Returns the absolute value of a floating x
fdim(x, y) Returns the positive difference between x and y
floor(x) Returns the value of x rounded down to its nearest integer
hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow
fma(x, y, z) Returns x*y+z without losing precision
fmax(x, y) Returns the highest value of a floating x and y
fmin(x, y) Returns the lowest value of a floating x and y
fmod(x, y) Returns the floating point remainder of x/y
pow(x, y) Returns the value of x to the power of y
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of a double value
tan(x) Returns the tangent of an angle
C++ Booleans
• Very often, in programming, you will need a data type that can
only have one of two values, like:
• YES / NO
• ON / OFF
• TRUE / FALSE
• For this, C++ has a bool data type, which can take the
values true (1) or false (0).
Boolean Values
• A boolean variable is declared with the bool keyword and can only
take the values true or false:
• Example
• bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
• From the example above, you can read that a true value returns 1,
and false returns 0.
• However, it is more common to return boolean values from boolean
expressions (see below).
Boolean Expression
• A Boolean expression is a C++ expression that returns a boolean value: 1 (true) or 0 (false).
• You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:
• Example
• int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
• Or even easier:
• Example
• cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
• In the examples below, we use the equal to (==) operator to evaluate an expression:
• Example
• int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
• Example
• cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15
• Booleans are the basis for all C++ comparisons and conditions.
• You will learn more about conditions (if...else) in the next chapter.
C++ Conditions and If Statements
• 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";
}
• We can also test variables:
• Example
• int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
• 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
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
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."
• Example explained
• In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is
also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good
evening".
• However, if the time was 14, our program would print "Good day."
Short Hand If...Else (Ternary Operator)
• If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:
• Syntax
• variable = (condition) ? expressionTrue : expressionFalse;

• Instead of writing:
• Example
• int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
• You can simply write:
• Example
• int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
C++ Switch Statements
• Use the switch statement to select one of many code blocks to be • Example
executed. • int day = 4;
switch (day) {
• The switch statement allows us to execute a block of code among many case 1:
alternatives. cout << "Monday";
break;
• Syntax case 2:
• switch(expression) { cout << "Tuesday";
case x: break;
case 3:
// code block cout << "Wednesday";
break; break;
case y: case 4:
// code block cout << "Thursday";
break; break;
case 5:
default: cout << "Friday";
// code block break;
} case 6:
cout << "Saturday";
• This is how it works: break;
• The switch expression is evaluated once. case 7:
cout << "Sunday";
• The value of the expression is compared with the values of each case. break;
• If there is a match, the associated block of code is executed. default:
cout<<“ Have a nice day”;
• 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 // Outputs "Thursday" (day 4)
Flowchart of switch Statement
The break Keyword
• When C++ reaches a break keyword, it breaks out of the switch
block.
• This will stop the execution of more code and case testing inside
the block.
• When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
• A break can save a lot of execution time because it "ignores" the
execution of all the rest of the code in the switch block.
The default Keyword
• The default keyword specifies some code to run if there is no case match:
• Example
• int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
• Run example »
• Note: The default keyword must be used as the last statement in the switch, and it does not need a break.
// Program to build a simple calculator using switch
Statement cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
#include <iostream> case '-':
using namespace std; cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
int main() case '*':
{ cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
char oper; case '/':
float num1, num2; cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
cout << "Enter an operator (+, -, *, /): ";
default:
cin >> oper; // operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
cout << "Enter two numbers: " << endl;
break;
cin >> num1 >> num2; }
return 0;
}
switch (oper) {
case '+':
#include <iostream> cout << "Well done" << endl;
break;
using namespace std; case 'D' :
cout << "You passed" << endl;
break;
int main() case 'F' :
cout << "Better try again" << endl;
{ break;
// local variable declaration: default :
cout << "Invalid grade" << endl;
char grade; }
cout << "Enter your grade" << endl; cout << "Your grade is " << grade << endl;
return 0;
cin>>grade; }
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
C++ Loops
• A loop statement allows us to execute a statement or group of statements multiple times.
• It 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.
• It’s made of four types
While loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before
executing the loop body.

For loop
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

Nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
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++;
}
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);
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";
}

• Run example »
• 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";
}
C++ Break
• You have already seen the break statement used in an earlier chapter of this tutorial.
It was used to "jump out" of a switch statement.
• The break statement can also be used to jump out of a loop.
• This example jumps out of the loop when i is equal to 4:
• Example
• for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}

• Run example »
C++ Continue
• The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
• This example skips the value of 4:
• Example
• for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Break and Continue in While Loop
• You can also use break and continue in while loops:
• Break Example
• int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

• Continue Example
• int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
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.
• This statement accesses the value of the first element in cars:
• Example
• string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

• Run example »
• Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Change an Array Element
• To change the value of a specific element, refer to the index number:
• Example
• cars[0] = "Opel";

• Example
• string cars[4] =
{"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of 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
• string cars[4] =
{"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}
Omit Array Size
• You don't have to specify the size of the array. But if you don't, it will only be as big as the elements that are
inserted into it:
• string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3

• This is completely fine. However, the problem arise if you want extra space for future elements. Then you have
to overwrite the existing values:
• string cars[] = {"Volvo", "BMW", "Ford"};
string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

• If you specify the size however, the array will reserve the extra space:
• string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though
it's only three elements inside it

• Now you can add a fourth and fifth element without overwriting the others:
• string cars[3] = {"Mazda"};
string cars[4] = {"Tesla"};
Omit Elements on Declaration
• It is also possible to declare an array without specifying the
elements on declaration, and add them later:
• string cars[5];
string cars[0] = {"Volvo"};
string cars[1] = {"BMW"};
...
Creating References
• A reference variable is a "reference" to an existing variable, and it is created with
the & operator:
• string food = "Pizza"; // food variable
string &meal = food; // reference to food

• Now, we can use either the variable name food or the reference name meal to refer to
the food variable:
• Example
• string food = "Pizza";
string &meal = food;

cout << food << "\n"; // Outputs Pizza


cout << meal << "\n"; // Outputs Pizza
Memory Address
• In the example above, the & operator was used to create a reference variable. But it can also be used to get the memory
address of a variable, which is the location of where the variable is stored on the computer.
• When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the
variable, it is stored in this memory address.
• To access it, use the & operator, and the result will represent where the variable is stored:
• Example
• string food = "Pizza";

cout << &food; // Outputs 0x6dfed4

• Run example »
• Note: The memory address is in hexidecimal form (0x..). Note that you may not get the same result in your program.
• And why is it useful to know the memory address?
• References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you
the ability to manipulate the data in the computer's memory - which can reduce the code and improve the
perfomance.
• These two features are one of the things that make C++ stand out from other programming langues, like Python and
Java.
Creating Pointers
• You learned from the previous chapter, that we can get the memory address of a variable by using the & operator:
• Example
• string food = "Pizza"; // A food variable of type string

cout << food; // Outputs the value of food (Pizza)


cout << &food; // Outputs the memory address of food (0x6dfed4)

• Run example »
• A pointer however, is a variable that stores the memory address as its value.
• A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:
• Example
• string food = "Pizza"; // A food variable of type string
string* ptr = &food; // A pointer variable, with the name ptr, that stores the address of food

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)


cout << ptr << "\n";

• Run example »
• Example explained
• Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're working with.
• Use the & operator to store the memory address of the variable called food, and assign it to the pointer.
• Now, ptr holds the value of food's memory address.
• Tip: There are three ways to declare pointer variables, but the first way is preferred:
• string* mystring; // Preferred
string *mystring;
string * mystring;
Get Memory Address and Value
• In the example above, we used the pointer variable to get the memory address of a variable (used together
with the & reference operator). However, you can also use the pointer to get the value of the variable, by
using the * operator (the dereference operator):
• Example
• string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration

// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";

// Dereference: Output the value of food with the pointer (Pizza)


cout << *ptr << "\n";

• Run example »
• Note that the * sign can be confusing here, as it does two different things in our code:
• When used in declaration (string* ptr), it creates a pointer variable.
• When not used in declaration, it act as a dereference operator.
Modify the Pointer Value
• You can also change the pointer's value. But note that this will also change the value of the original variable:
• Example
• string food = "Pizza";
string* ptr = &food;

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";

// Change the value of the pointer


*ptr = "Hamburger";

// Output the new value of the pointer (Hamburger)


cout << *ptr << "\n";

// Output the new value of the food variable (Hamburger)


cout << food << "\n";
C++ Files
• The fstream library allows us to work with files.
• To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:
• Example
• #include <iostream>
#include <fstream>
• There are three objects included in the fstream library, which are used
to create, write or read files:
• Object/Data Type Description ofstream Creates and writes to files
ifstream Reads from files fstream A combination of ofstream and
ifstream: creates, reads, and writes to files
Create and Write To a File
• To create a file, use either the ofstream or fstream object, and specify the name of the file.
• To write to the file, use the insertion operator (<<).
• Example
• #include <iostream>
#include <fstream>
using namespace std;

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}
• Why do we close the file?
• It is considered good practice, and it can clean up unnecessary memory space.
Read a File
• To read from a file, use either the ifstream or fstream object, and the name of the file.
• Note that we also use a while loop together with the getline() function (which belongs to the ifstream object)
to read the file line by line, and to print the content of the file:
• Example
• // Create a text string, which is used to output the text file
string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by
line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();
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!"

• Run example »
• 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 function's name, return type, 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. It is because C++ works from top to bottom; which means that if the function is not declared above main(), the program is
unaware of it:
• Example
• int main() {
myFunction();
return 0;
}

void myFunction() {
cout << "I just got executed!";
}

// Error

• Run example »
• 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!";
}
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

• Run example »
• When a parameter is passed to the function, it is called an argument. So, from the example above: string fname is a parameter,
while Liam, Jenny and Anja are arguments.
Multiple Parameters
• You can add as many parameters as you want:
• Example
• void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Liam Refsnes. 3 years old.


// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.

• Run example »
• Note that when you are working with multiple parameters, the function call must have the same number of arguments as
there are parameters, and the arguments must be passed in the same order.
Return Values
• The void keyword, used in the examples above, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the
function:
• Example
• int myFunction(int x) {
return 5 + x;
}

int main() {
cout << myFunction(3);
return 0;
}

// Outputs 8 (5 + 3)

• Run example »
• This example returns the sum of a function with two parameters:
• Example
• int myFunction(int x, int y) {
return x + y;
}

int main() {
cout << myFunction(5, 3);
return 0;
}

// Outputs 8 (5 + 3)

• Run example »
• You can also store the result in a variable:
• Example
• int myFunction(int x, int y) {
return x + y;
}

int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
Pass By Reference
• In the examples above, we used normal variables when we passed parameters to a function. You can also
pass a reference to the function. This can be useful when you need to change the value of the arguments:
• Example
• void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}

int main() {
int firstNum = 10;
int secondNum = 20;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

return 0;
}
Function Overloading
• With function overloading, multiple functions can have the same name with different parameters:
• Example
• int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

• Consider the following example, which have two functions that adds numbers of different types:
• Example
• int plusFuncInt(int x, int y) {
return x + y;
}

double plusFuncDouble(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
• Instead of defining two functions that should do the same thing, it is better to overload one.

• In the example below, we overload the plusFunc function to work for both integers and
doubles:
Example
int plusFunc(int x, int y)
{
return x + y;
}

double plusFunc(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFunc(83, 5);
double myNum2 = plusFunc(6.3, 5.2);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
C++ Classes/Objects
• C++ is an object-oriented programming language.

• Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object.
The car has attributes, such as weight and color, and methods, such
as drive and brake.

• Attributes and methods are basically variables and functions that


belongs to the class. These are often referred to as "class members".

• A class is a user-defined data type that we can use in our program, and
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Example explained
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that members (attributes
and methods) of the class are accessible from outside the class. You will learn more about
access specifiers later.
Inside the class, there is an integer variable myNum and a string variable myString.
When variables are declared within a class, they are called attributes.
At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to
create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Create an object called "myObj" and access the attributes:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects
You can create multiple objects of one class:
Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};

int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and by using the dot syntax ( .):
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod()
{ // Method/function defined inside the class
cout << "Hello World!";
}
};

int main()
{
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}

• Run example »
To define a function outside the class definition, you have to declare it inside the class and then define it outside of the class. This is done by
Outside Example
• class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
• You can also add parameters:
• Example
• #include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
Constructors
• A constructor in C++ is a special method that is automatically called when an object of a class is created.
• To create a constructor, use the same name as the class, followed by parentheses ():
• Example
• class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the
constructor)
return 0;
}

• Run example »
• Note: The constructor has the same name as the class, it is always public, and it does not have any return value.
Constructor Parameters
• Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.
• The following class have brand, model and year attributes, and a constructor with different parameters. Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc). When we call the constructor (by creating an object of the class), we pass parameters to the constructor,
which will set the value of the corresponding attributes to the same:
• Example
• class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

• Run example »
• Just like functions, constructors can also be defined outside the class. First, declare the constructor inside the class, and then define it outside of the class by specifying the name of the class, followed by the scope resolution :: operator, followed by the name of the constructor (which is the same
as the class):
• Example
• class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Access Specifiers
• By now, you are quite familiar with the public keyword that appears in all of our class examples:
• Example
• class MyClass { // The class
public: // Access specifier
// class members goes here
};

• Run example »
• The public keyword is an access specifier. Access specifiers define how the members (attributes and methods) of a class can be accessed. In the example above, the members are public - which means that they can be accessed and modified from outside the code.
• However, what if we want members to be private and hidden from the outside world?
• In C++, there are three access specifiers:
• public - members are accessible from outside the class
• private - members cannot be accessed (or viewed) from outside the class
• protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes. You will learn more about Inheritance later.
• In the following example, we demonstrate the differences between public and private members:
• Example
• class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}

• If you try to access a private member, an error occurs:


• error: y is private
• Run example »
• Note: It is possible to access private members of a class using a public method inside the same class. See the next chapter (Encapsulation) on how to do this.
• Tip: It is considered good practice to declare your class attributes as private (as often as you can). This will reduce the possibility of yourself (or others) to mess up the code. This is also the main ingredient of the Encapsulation
concept, which you will learn more about in the next chapter.
• Note: By default, all members of a class is private if you don't specify an access specifier:
• Example
• class MyClass {
int x; // Private attribute
int y; // Private attribute
};
Encapsulation
• The meaning of Encapsulation, is to make sure that "sensitive"
data is hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside
the class). If you want others to read or modify the value of a
private member, you can provide
public getter and setter methods.
Access Private Members
• To access a private attribute, use public "getter" and "setter" methods:
• Example
• #include <iostream>
using namespace std;

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
• Run example »
• Example explained
• The salary attribute is private, which have restricted access.
• The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s).
• The public getSalary() method returns the value of the private salary attribute.
• Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set the value of the private attribute to 50000. Then we call the getSalary() method on the object to
return the value.
Why Encapsulation?
• It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better control
of your data, because you (or others) can change one part of the
code without affecting other parts
• Increased security of data
C++ Inheritance
• In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two
categories:
• derived class (child) - the class that inherits from another class
• base class (parent) - the class being inherited from
• In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):
• Example
• // Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
• Run example »
• Why And When To Use "Inheritance"?
Multilevel Inheritance
• A class can also be derived from one class, which is already derived from another class.
• In the following example, MyGrandChild is derived from class MyChild (which is derived from MyClass).
• Example
• // Base class (parent)
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Derived class (child)


class MyChild: public MyClass {
};

// Derived class (grandchild)


class MyGrandChild: public MyChild {
};

int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Multiple Inheritance
• A class can also be derived from more than one base class, using a comma-separated list:
• Example
• // Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Another base class


class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
Access Specifiers
You learned from the

Access Specifiers chapter that there are three specifiers available in C++. Until no
w, we have only used public (members of a class are accessible from outside the c
lass) and private (members can only be accessed within the class). The third specif
ier, protected, is similar to private, but it can also be accessed in the inherited class
.
• Example
// Base class
class Employee {
protected: // Protected access specifier
int salary;
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};

int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
• https://codescracker.com/cpp/program/cpp-program-calculate-stude
nt-grade.htm
• https://codingshiksha.com/c/c-program-to-build-a-student-report-car
d-of-school-or-college-management-system-full-project-for-beginners
/

You might also like