CMP 212 2024 Lecture Note Part One

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Lecture Note

Department of Computer Science,


Faculty of Computing,
Federal University Dutsin-Ma, Katsina – Nigeria

CMP212
Computer Programming II
(C++ Programming Language)
PART ONE

2024
COURSE SYLLABUS
1. Course Code and Title: CMP212 – Computer Programming II (Programming with
C++)
2. Credit Units/Contact Hours: 3/2
3. Semester/Session: Second - 2022/2023
3. Program: 200 Level Computer Science
4. Course Lecturers: Yusuf Surajo (CC), Mukhtar Abubakar, Stephen Luka,
Ahmad Mahmud Ibrahim and Sirajo Musa

5. Recommended Textbooks

a. Perry, G. (1992) C++ by Example, lloyed short.


b. Hubbard, J.R. (2000) Programming with C++, Tata McGraw-Hill, New Delhi, India
(Second Edition)
c. Paul and Harvey Deitel (2013) C++ How to Program, Pearson Horizon Editions, Eight
Edition
d. C++ for Dummies (2004), 5th Edition

1
6. Specific Course Information

This course will provide the students with a solid theoretical understanding as well as practical
skills of C++ Programming. The primary aim of the Course is to enable the students to tackle
programming problems, making good use of the C++ programming in the context of Object
Oriented method to simplify the design and implementation process.

7. Specific Goals for the Course


On completion of the course the students should be able to:

a. Install C++ Programming Compiler


b. Understand the basic concept of C++ Programming
c. Create C++ programming class hierarchies using the object-oriented design process
d. Design and implement C++ programs for Simple and complex problems, making good
use of the features of the language such as classes, inheritance and templates.
e. Detect bug and errors in C++ Programs.
f. Understand generic classes and functions.

8. Course Outline

Problem Solving, Program, Programming Languages Level, C++ Programming Language,


Compilers and Interpreters, Errors, C++ as an Object – Oriented Programming, C++ Syntax and
Structure, Comments, Variables, Identifiers, Constants, Data Types, Operators, C++ Math
Library, Conditions and Loops Statements, Arrays, Functions, Parameters and Arguments,
Constructor, Object-Oriented Programming; Classes and Objects, Encapsulation, Inheritance,
Polymorphism, Data Hiding, C++ Files, Exceptions.

9. Assessment method
Students will be graded based on the following criteria:
a. First C.A Test: 15%
b. Second C.A Test: 15%
c. Practical Classes Assessment: 10%
d. Final exam: 60%

10. Lectures’ Schedules and the grouping


 Group A: Computer Science & Mathematics Students (PART_ONE) Stephen Luka
 Group A: Computer Science & Mathematics Students (PART_TWO) Ahmad Mahmud I.
 Group A: Computer Science & Mathematics Students (PART_THREE) Yusuf Surajo
 Group B: Applied Chemistry & Education Students (PART_ONE) Sirajo Musa
 Group B: Applied Chemistry & Education Students (PART_TWO) Sirajo Musa
 Group B: Applied Chemistry & Education Students (PART_THREE) Mukhtar Abubakar

2
INTRODUCTION

Suppose a particular person is giving travel directions to a friend, that person might explain those
directions in any one of several languages, such as English, Hausa, Yoruba, or Igbo. The
directions are the same no matter which language is used to explain them, but the manner in
which the directions are expressed is different. Furthermore, the friend must be able to
understand the language being used in order to follow the directions.

Similarly, a problem can be solved by writing a program in one of many programming languages,
such as C++, Java, Pascal, and Smalltalk. The purpose of the program is essentially the same no
matter which language is used, but the particular statements used to expressed the instructions,
and the overall organization of those languages, vary with each language. Furthermore, a
computer must be able to understand the instructions in order to carry them out.

PROBLEM SOLVING

The purpose of writing a program is to solve a problem. Problem solving, in general, consists of
multiple steps:

1. Understand the problem

2. Breaking the problem in to manageable pieces

3. Designing a solution

4. Considering alternatives to the solution and refining the solution

5. Implementing the solution

6. Testing the solution and fixing any problems that exist

Although this approach applies to any kind of problem solving, it works particularly well when
developing software.

The first step, Understanding the Problem, may sound obvious, but a lack of attention to this
step has been the cause of many misguided efforts. If we attempt to solve a problem we don’t
completely understand, we often end up solving the wrong problem or at least going off on
improper tangents. We must understand the needs of the people who will use the solution. These
needs often include subtle nuances that will affect our approach to the solution.

3
After we thoroughly understand the problem, we then Break the problem into manageable
pieces and design a solution. These steps go hand in hand. A solution to any problem can rarely
be expressed as one big activity. Instead, it is a series of small cooperation tasks that interact to
perform a larger task. When developing software, we don’t write one big program. We design
separate pieces that are responsible for certain parts of the solution, subsequently integrating
them with other parts.

Our first inclination toward a solution may not be best one. We must always Consider
alternatives and refine the solution as necessary. The earlier we consider alternatives, the
easier it is to modify our approach.

Implementing the solution is the act of taking the design and putting in a usable form. When
developing a software solution to a problem, the implementation stage is the process of actually
writing the program. Too often programming is thought of a writing code. But in most cases, the
final implantation of the solution is one of the last and easiest steps. The act of designing the
program should be more interesting and creative than the process of implanting the design in a
particular programming language.

Finally, we Test our solution to find any errors that exist so that we can fix them and
improve the quality of the software. Testing efforts attempt to verify that the program correctly
represents the design, which in turn provides a solution to the problem.

WHAT IS A PROGRAM?

This section introduces you to fundamental programming concepts and levels of programming
language. The task of programming computers has been described as rewarding, challenging,
easy, difficult, fast, and slow. Actually, it is a combination of all these descriptions. Writing
complex programs to solve advanced problems can be frustrating and time-consuming, but you
can have fun along the way, especially with the rich assortment of features that programming
language has to offer.

This section also describes the concept of programming, from a program’s inception to its
execution on your computer. The most difficult part of programming is breaking the problem
into logical steps that the computer can execute.

NOTE: A program is a list of instructions that tells the computer to do things.

4
Keep in mind that computers are only machines. They’re not smart; in fact, they’re quite the
opposite! They don’t do anything until they are given detailed instructions. A word processor, for
example, is a program somebody wrote—in a language such as C++—that tells your computer
exactly how to behave when you type words into it.

You are familiar with the concept of programming if you have ever followed a recipe, which is a
“program,” or a list of instructions, telling you how to prepare a certain dish. A good recipe lists
these instructions in their proper order and with enough description so you can carry out the
directions successfully, without assuming anything.

PROGRAMMING LANGUAGES LEVEL

Programmers write instructions in various programming languages, some directly understandable


by computers and others requiring intermediate translation steps. Hundreds of such languages are
used today. Programming languages are often categorized in to the following four groups. These
groups basically reflect the historical development of computer languages.

 Machine language

 Assembly language

 High- level language

Machine Language

Any computer can directly understand only its own machine language, defined by its hardware
design, machine language generally consist of string of numbers (ultimately reduced to 1s and 0s)
that instruct computers to perform their most elementary operations one at a time. Machine
language are independent (a particular machine language can be used on only one type of
computer); such languages are cumbersome for humans. In order for a program to run on a
computer, it must be expressed in that computer’s machine language. Each type of CPU has its
language. For that reason, we can’t run a program specifically written for sun work station with
its Sparc processor, or IBM PC, with its Intel processor.

Each machine language instruction can accomplish only a simple task, for example, a single
machine instruction might copy a value in to a register or compare a value to zero. It might take
four separate machine language instruction to add two numbers together and to store the result.

5
However, a computer can do millions of these instructions in a second, and therefore many
simple commands can be quickly executed to accomplish complex task.

Machine language code is expressed as a series of binary digits and is extremely difficult for
humans to reads and writes. Originally, programs were entered in to the computer using switches
or some similarly tedious method. Early programmers found these techniques to be time
consuming and error prone.

Assembly Language

These problems gave rise to the use of assembly language, which replaced binary digits with
mnemonics, short English – like words that represent commands or data. It is much easier for
programmers to deal with words then with binary digits. However, an assembly language
program cannot be executed directly on a computer. It must first be translated in to machine
language.

Generally, each assembly language instruction corresponds to an equivalent machine language.


Therefore, similar to machine language, each assembly language instruction accomplishes only a
simple operation. Although assembly language is an improvement over machine code from a
programmer’s perspective, it is still tedious to use. Translator programs called assembles were
developed to convert early assembly language programs to machine language at computer speeds,
although such assembly language is clearer to human but in incomprehensible to computers until
translated to machine language. Both assembly language and machine language are considered
low – level languages.

High - Level Language

Today, most programmers use a high – level language to write software. A high - level language
is express in English – like phrase, and thus is easier for programmers to read and write. A single
high – level language programming statements are expressed in a form approaching natural
language, far removed from the machine language that is ultimately executed. C++ is a high –
level language, C, Java, and Smalltalk.

High – level language code must be translated in to machine language in order to be executed by
a translator programs called compilers. A high – level language insulates programmers from
needing to know the underlying machine language for the processor on which they are working.

6
WHAT IS C++?

C++ is a general purpose, case-sensitive, free-form programming language that supports object
oriented, procedural programming paradigms.

C++ is a cross-platform language that can be used to create high-performance applications.

C++ is a middle-level language, as it encapsulates both high and low level language features. It
supports the four major pillars of object oriented programming; Inheritance, Polymorphism,
Encapsulation, and Abstraction.

C++ is a powerful computer programming language that’s appropriate for technically oriented
people with little or no programming experience, and for experienced programmers to use in
building substantial information systems. You’re already familiar with the powerful tasks
computers perform. Using this lecture note, you will write instructions commanding computers
to perform those kinds of tasks. Software (i.e. the instructions you write) controls hardware (i.e.
computer and its peripherals). Computers process data under the control of sets of instruction
called computer programs as explained earlier – these programs guide the computer through
orderly sets of actions specified by people called computer programmers. The programs that runs
on a computer are referred to as software, in this note, you’ll learn today’s key programming
methodology that’s enhancing programmer productivity, thereby reducing software –
development cost; object – oriented programming.

Why Use C++?

 C++ is one of the world's most popular programming languages.


 C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
 C++ is an object-oriented programming language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
 C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
 C++ is fun and easy to learn!
 As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or
vice versa

7
C++ Get Started

To start using C++, you need two things:

 A text editor (IDE - Integrated Development Environment) is used to edit and compile
the code. Popular IDE's include: Notepad, Notepad++, sublime text, Blocks, Eclipse, and
Visual Studio etc. These are all free, and they can be used to both edit and debug C++
code.

 A compiler, like MinGW /GCC, Borland C++, Dev C++, Embracadero, Clang, Visual
C++, Intel C++, Code Block., to translate the C++ code into a language that the computer
will understand

There are many text editors and compilers to choose from. In our lectures and practical sessions,
we will use an IDE.

Note: Web-based IDE's can work as well, but functionality is limited.

We will use Borland C++ or Dev C++ in our tutorial, which we believe is a good place to start.

To give C++ programming instructions to your computer as we are explaining, you need an
editor and a C++ compiler. An editor is similar to a word processor; it is a program that enables
you to type a C++ program into memory, make changes (such as typing, moving, copying,
inserting, and deleting text), and save the program more permanently in a disk file, save the
program/file as “program/file.cpp”, because C++ programs are saved with
extensions .C, .cc, .cpp, .cxx depending on the platform you are working upon. After using the
editor to type and save the program, you must compile it before you can run it. The C++
programming language is called a compiled language.

You cannot write a C++ program and run it on your computer unless you have a C++ compiler.
This compiler takes your C++ language instructions and translates them into a form that your
computer can read. A C++ compiler is the tool your computer uses to understand the C++
language instructions in your programs. Many compilers come with their own built-in editor. If
yours does, you probably feel that your C++ programming is more integrated.

To some beginning programmers, the process of compiling a program before running it might
seem like an added and meaningless step. If you know the BASIC programming language, you
might not have heard of a compiler or understand the need for one. That’s because BASIC (also
APL and some versions of other computer languages) is not a compiled language, but an

8
interpreted language. Instead of translating the entire program into machine-readable form (as a
compiler does in one step), an interpreter translates each program instruction—then executes it—
before translating the next one.

The difference between the two is subtle, but the bottom line is not; Compilers produce much
more efficient and faster-running programs than interpreters do. This seemingly extra step of
compiling is worth the effort (and with today’s compilers, there is not much extra effort needed).
Because computers are machines that do not think, the instructions you write in C++ must be
detailed. You cannot assume your computer understands what to do if some instruction is not in
your program, or if you write an instruction that does not conform to C++ language requirements.

BRIEF HISTORY OF C++

As object-oriented analysis, design, and programming began to catch on, Bjarne Stroustrup took
the most popular language for commercial software development, C, and extended it to provide
the features needed to facilitate object-oriented programming. He created C++ in the early 1980s,
and in less than a decade it has gone from being used by only a handful of developers at AT&T
to being the programming language of choice for an estimated one million developers worldwide.
It is expected that by the end of the decade, C++ will be the predominant language for
commercial software development.

C++ is a difficult language for at least two reasons: it inherits from the C language an economy
of expression that novices often find cryptic. And an object – oriented language, its widespread
use of classes and templates presents a challenge to those who have not thought in those terms
before.

C++ FEATURES

C++ is object oriented programming language. It provides a lot features that are given below:

 Simple: C++ is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library function, data types etc.
 Machine Independent or Portable: Unlike assembly language, C++ programs can be
executed in many machines with little bit or no change. But it is not platform –
independent.
 Mid – level programming Language: C++ is also used to do low level programming, it
is used to developed system applications such as kernel, drivers etc. It also supports the
feature of high level language. That is why it is known as mid-level language

9
 Structured Programming Language: C++ is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify.
 Rich Library: C++ provides a lot inbuilt functions that make the development fast.
 Memory Management: It supports the feature of dynamic memory allocation. In C++
language, we can free the allocated memory at any time by calling the free() function
 Speed: The compilation and execution time of C++ language is fast
 Pointers: C++ provides the feature of pointer. We can directly interact with the memory
by using the pointers. We can use pointers for memory, structures, functions, arrays etc.
 Recursion: In C++, we can call a function within the function program; this provides
code reusability for every function.
 Extensible: C++ language is extensible because it can easily adopt new features.
 Object – Oriented: C++ is object oriented programming language. OOPs makes
development and maintenance easier whereas in procedure – oriented programming,
language it is not easy to manage if code grows as project size grows.
 Compiler based: C++ is a compiler based programming language, it means without
compilation no C++ program can be executed. First we need to compile our program
using compiler and then we can execute our program.

COMPILERS AND INTERPRETERS

Several special purpose programs are needed to help with the process of developing new
programs. They are sometimes called software tools because they are used to build programs.
Examples of basic software tool include an editor, a compiler, and an interpreter.

Initially, you use editors as you type a program in to computer and store it in file. There are
many different editors with many different features. You should become familiar with editor you
will use regularly because it can dramatically affect the speed at which you enter and modify
your programs.

Each time you need to make a change to the code of your program, you open it in an editor, after
editing and saving your program, you attempt to translate it from high – level code in to a form
that can be executed. That translation may result in errors, in which case you return to the editor
to make changes to the code to fix the problems. Once the translation occurs successfully, you
can execute the program and evaluate the results. If the results are not what you want, you again
return to the editor to make changes.

The translation of source code in to (ultimately) machine language for particular type of CPU
can occur in variety of ways.

10
A compiler is a program that translates code in one language to equivalent code in another
language. The original code is called source code, and the language in to which it is translated is
called the target language. For many traditional compilers, the source code is translated directly
into a particular machine language. In that case, the translation process occurs once, and the
resulting executable program can be run whenever needed. Some example of C++ compiler s are:
MinGW /GCC, Borland C++, Dev C++, Embracadero, Clang, Visual C++, Intel C++, Code
Block, as explained earlier.

An interpreter is similar to a compiler but has an important difference. An interpreter


interweaves the translation and execution activities. A small part of the source code, such as one
statement, is translated and executed. Then another statement is translated and executed, and so
on. One advantage of this technique is that, it eliminates the need for a separate compilation
phase. However, the program generally runs more slowly because the translation process occurs
during each execution.

ERRORS

Several different kinds of problems can occur in software particularly during program
development. Term computer error is often misused and varies in meaning depending on the
person using it. From the user’s point of view, anything that goes away when interacting with a
machine is often called a computer error. A computer follows the commands we give and
operates on the data we provide. If our programs are wrong or our data are inaccurate, then we
cannot expect the results to be correct. A computer phrase used to describe this situation is
“Garbage in, Garbage out.”

You will encounter three kinds of errors as you develop program:

 Compile – time error

 Runtime error

 Logical error

The compiler checks to make sure you are using the correct syntax. If you have any statements
that do not conform to the syntactic rules of the language, the compiler will produce a syntax
error. The compiler also tries to find other problems, such as the used of incompatible types of
data. The syntax might be technically correct, but you are still attempting to do something that

11
the language doesn’t semantically allow. Any error identified by the compiler is called a compile
– time error. If compile - time error occurs, an executable version of the program is not created.

The second kind of problem occurs during program execution, it is called a runtime error, and it
causes the program to terminate abnormally, for example, if we attempt to divide by zero, the
program will “crash” and halt execution at that point. Because the requested operation is
undefined, the system simply abandons its attempt to continue processing your program.

The third kind of software problem is logical error. In this case, the software compiles and
executes without any complaint, but it produce incorrect results. For example, a logical error
occurs when a value is calculated incorrectly. A programmer must test the program thoroughly,
comparing the expected results to those that actually occur. When defects are found, they must
be trace back to the source of the problem in the code and corrected. The process of finding and
correcting defects in a program is called Debugging. Logical errors can manifest themselves in
many ways, and the actual root cause might be quite difficult to discover.

C++ AS AN OBJECT – ORIENTED PROGRAMMING

C++ fully supports object-oriented principles, which includes: encapsulation, data hiding
(Abstraction), inheritance, and polymorphism.

Encapsulation

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other code
defined outside the wrapper.

Data Hiding

Data hiding is the highly valued characteristic that an object can be used without the user
knowing or caring how it works internally. Just as you can use a refrigerator without knowing
how the compressor works, you can use a well-designed object without knowing about its
internal data members.

C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. Once created, a well-defined class act as a fully encapsulated

12
entity--it is used as a whole unit. The actual inner workings of the class should be hidden. Users
of a well-defined class do not need to know how the class works; they just need to know how to
use it.

Inheritance

Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification (that is, top-down).

For example: Inheritance is like when the engineers at Ford Motors want to build a new car, they
have two choices: They can start from scratch, or they can modify an existing model. Perhaps
their Star model is nearly perfect, but they'd like to add a turbocharger and a six-speed
transmission. The chief engineer would prefer not to start from the ground up, but rather to say,
"Let's build another Star, but let's add these additional capabilities. We'll call the new model a
Quasar." A Quasar is a kind of Star, but one with new features.

C++ supports the idea of reuse through inheritance. A new type, which is an extension of an
existing type, can be declared. This new subclass is said to derive from the existing type and is
sometimes called a derived type. The Quasar is derived from the Star and thus inherits all its
qualities, but can add to them as needed.

Polymorphism

Polymorphism (from Greek, meaning “many forms”) occurs when there is a hierarchy of classes
and they are related by inheritance. C++ polymorphism means that a call to a member function
will cause a different function to be executed depending on the type of object that invokes the
function.

From the above example at Ford Motors, polymorphism here is when the new Quasar might
respond differently than a Star does when you press down on the accelerator. The Quasar might
engage fuel injection and a turbocharger, while the Star would simply let gasoline into its
carburetor. A user, however, does not have to know about these differences. He can just "floor
it," and the right thing will happen, depending on which car he's driving.

C++ supports the idea that different objects do "the right thing" through what is called function
polymorphism and class polymorphism. Poly means many, and morph means form.
Polymorphism refers to the same name taking many forms.

13
Quick Start
Let's create our first C++ file, Open Text editor (IDE) and go to File > New > Empty File.
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as):

#include <iostream>

using namespace std;

int main() {

cout << "Hello World!";

return 0;

Don't worry if you don't understand the code above - we will discuss it in detail. For now, focus
on how to run the code.

In a text editor, it should look like this:

Then, go to Build > Build and Run to run (execute) the program. The result will look something
to this:

Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.

Congratulations! You have now written and executed your first C++ program.

C++ Syntax

Let's break up the following code to understand it better:

14
Example
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 cout << "Hello World!";
6 return 0;
7 }
Example explained

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 together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World".

Note: Every C++ statement ends with a semicolon;. Also 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 make the code more
readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket} to actually end the main function.

Omitting Namespace

You might see some C++ programs that run without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:

Example

#include <iostream>

15
int main() {

std::cout << "Hello World!";

return 0;

It is up to you if you want to include the standard namespace library or not.

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;

New Lines

To insert a new line, you can use the \n character:

16
Example

#include <iostream>

using namespace std;

int main() {

cout << "Hello World! \n";

cout << "I am learning C++";

return 0;

Tip: Two \n characters after each other will create a blank line:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}

Another way to insert a new line is with the endl manipulator:


Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

Both \n and endl are used to break lines. However, \n is used more often and is the preferred way.

17
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!";

This example uses a single-line comment at the end of a line of code:

Example

cout << "Hello World!"; // This is a comment

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!";

Single or multi-line comments? It is up to you which you want to use. Normally, we use // for
short comments, and /* */ for longer.

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

18
Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the variable (such as x
or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

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

Other Types

A demonstration of other data types:

19
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)

You will learn more about the individual types in the Data Types this section.

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, use a comma-separated list:

Example

int x = 5, y = 6, z = 50;

cout << x + y + z;

20
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:

Example

// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

 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 number(s) or whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names

Constants

When you do not want others (or yourself) to override existing variable values, use the const
keyword (this will declare the variable as "constant", which means unchangeable and read-only):

Example

const int myNum = 15; // myNum will always be 15

myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to
change:

Example

const int minutesPerHour = 60;

const float PI = 3.14;

21
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

Note: cout is pronounced "see-out". Used for output, and uses the insertion operator (<<), cin is
pronounced "see-in". Used for input, and uses the extraction operator (>>).

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding)
the two numbers:

Example

int x, y;

int sum;

cout << "Type a number: ";

cin >> x;

cout << "Type another number: ";

cin >> y;

sum = x + y;

cout << "Sum is: " << sum;

There you go! You just built a basic calculator!

22
DATA TYPES

As explained in the Variables section, 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

char myLetter = 'D'; // Character

bool myBoolean = true; // Boolean

string myText = "Hello"; // String

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

You will learn more about the individual data types in the next sections.

23
Numeric Types

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.
int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
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.

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example

float f1 = 35e3;

double d1 = 12E4;

cout << f1;

cout << d1;

Boolean Types

A boolean data type is declared with the bool keyword and can only take the values true or false.
When the value is returned, true = 1 and false = 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

24
Boolean values are mostly used for conditional testing, 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.

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:

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

Character Types

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;

Tip: A list of all ASCII values can be found in our ASCII Table Reference (find it through
Google search engine).

String Types

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:

26
Example

// Include the string library

#include <string>

// Create a string variable

string greeting = "Hello";

// Output string value

cout << greeting;

You will learn more about strings, in our C++ Strings section.

27

You might also like