You are on page 1of 17

1 | Computer Programming 1 15

UNIT 2

Learning C++ Programming Language

2.0 Intended Learning Outcomes


On completion of the module, you should be able to:

1. Recognize the basic concept of programming.


2. Declare variables, and define data types and operators
according to correct syntax.

2.1 Introduction

In this section, we introduce you to the C++ programming language, which is


the programming language used in this course.

The first thing that people notice about the C++ language is its unusual name. Is there
a C programming language, you might ask? Is there a C− or a C−− language? Are
there programming languages named A and B? The answer to most of these questions
is no. But the general thrust of the questions is on the mark. There is a B programming
language; it was not derived from a language called A, but from a language called
BCPL. The C language was derived from the B language, and C++ was derived from
the C language. Why are there two pluses in the name C++? As you will see in the
next chapter, ++ is an operation in the C and C++ languages, so using ++ produces a
nice pun. The languages BCPL and B will not concern us. They are earlier versions of
the C programming language. We will start our description of the C++ programming
language with a description of the C language.

The C programming language was developed by Dennis Ritchie of AT&T Bell


Laboratories in the 1970s. It was first used for writing and maintaining the UNIX
operating system. (Up until that time UNIX systems programs were written either in
assembly language or in B, a language developed by Ken Thompson, who is the
originator of UNIX.) C is a general-purpose language that can be used for writing any sort
of program, but its success and popularity are closely tied to the UNIX operating
system. If you wanted to maintain your UNIX system, you needed to use C. C and
1 | Computer Programming 1 16

UNIX fit together so well that soon not just systems programs, but almost all
commercial programs that ran under UNIX were written in the C language. C became
so popular that versions of the language were written for other popular operating
systems; its use is not limited to computers that use UNIX. However, despite its
popularity, C is not without its shortcomings.

The C language is peculiar because it is a high-level language with many of the


features of a low-level language. C is somewhere in between the two extremes of a
very high-level language and a low-level language, and therein lies both its strengths
and its weaknesses. Like (low-level) assembly language, C language programs can
directly manipulate the computer’s memory. On the other hand, C has many features
of a high-level language, which makes it easier to read and write than assembly
language. This makes C an excellent choice for writing systems programs, but for
other programs (and in some sense even for systems programs), C is not as easy to
understand as other languages; also, it does not have as many automatic checks as
some other high-level languages.

2.1.1 First C++ Program – Hello World

Any meaningful program written in C++ has to contain a number of


components: the main function; some variable declarations; and some
executable statements.
For example, the following is a very basic C++ program.

On line 1, the file iostream.h is included in the file. The first character is the #
symbol, which is a signal to the preprocessor. Each time you start your
compiler, the preprocessor is run. The preprocessor reads through your source
code, looking for lines that begin with the pound symbol (#), and acts on those
lines before the compiler runs.
include is a preprocessor instruction that says, "What follows is a filename. Find
that file and read it in right here." The angle brackets around the filename tell
the preprocessor to look in all the usual places for this file. If your compiler is
1 | Computer Programming 1 17

set up correctly, the angle brackets will cause the preprocessor to look for the
file iostream.h in the directory that holds all the H files for your compiler. The
file iostream.h (Input-Output-Stream) is used by cout, which assists with
writing to the screen. The effect of line 1 is to include the file iostream.h into
this program as if you had typed it in yourself.
The preprocessor runs before your compiler each time the compiler is
invoked. The preprocessor translates any line that begins with a
pound symbol (#) into a special command, getting your code file ready
for the compiler.
Line 3 begins the actual program with a function named main(). Every C++
program has a main() function. In general, a function is a block of code that
performs one or more actions. Usually functions are invoked or called by
other functions, but main() is special. When your program starts, main() is
called automatically .main(), like all functions, must state what kind of value
it will return. The return value type for main() in HELLO.CPP is int, which
means that this function will return an integer value.
All functions begin with an opening brace ({) and end with a closing brace (}).
The braces for the main() function are on lines 4 and 7. Everything between
the opening and closing braces is considered a part of the function. The meat
and potatoes of this program is on line 5. The object cout is used to print a
message to the screen. cout is used in C++ to print strings and values to the
screen. A string is just a set of characters.

Here's how cout is used:

• type the word cout, followed by the output redirection operator(<<).

Whatever follows the output redirection operator is written to the screen. If


you want a string of characters written, be sure to enclose them in double
quotes ("), as shown on line 5. A text string is a series of printable characters.
The final two characters, \n, tell cout to put a new line after the words Hello
World! All ANSI-compliant programs declare main() to return an int. This
value is "returned" to the operating system when your program completes.
Some programmers signal an error by returning the value 1.

The main() function ends on line 7 with the closing brace.


1 | Computer Programming 1 18

2.1.2 Variables and their types

A variable is a name given to a memory location. It is the basic unit of storage in a


program.

• The value stored in a variable can be changed during program execution.


• A variable is only a name given to a memory location, all the operations done
on the variable effects that memory location.
• In C++, all the variables must be declared before use.

Rules for Declaring Variable:

1. The name of the variable contains letters, digits, and underscores.


2. The name of the variable are case sensitive (ex Arr and arr both are different
variable).
3. The name of the variable does not contain any whitespace and special
characters (ex #, $, %,* etc).
4. All the variable name must begin with a letter of the alphabet or an
underscore(_).
5. We cannot used C++ keyword(ex float, double, class)as a variable name.

How to declare variables?

A typical variable declaration is of the form:

A variable name can consist of alphabets (both upper and lower case), numbers and
the underscore ‘_’ character. However, the name must not start with a number.

datatype: Type of data that can be stored in this


variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
1 | Computer Programming 1 19

Example:

Difference between variable declaration and definition

• The variable declaration refers to the part where a variable is first declared or
introduced before its first use.
• A variable definition is a part where the variable is assigned a memory
location and a value. Most of the time, variable declaration and definition are
done together.

See the following C++ program for better clarification:


1 | Computer Programming 1 20

Output:

Types of variables

There are three types of variables based on


the scope of variables in C++:

• Local Variables
• Instance Variables
• Static Variables

Let us now learn about each one of these


variables in detail.

1. Local Variables: A variable


defined within a block or method
or constructor is called a local
variable.

• These variables are created when entered into the block or the function is
called and destroyed after exiting from the block or when the call returns from
the function.
• The scope of these variables exists only within the block in which the variable
is declared. i.e. we can access this variable only within that block.
• Initialization of Local Variable is Mandatory.

2. Instance Variables: Instance variables are non-static variables and are declared in a
class outside any method, constructor or block.

• As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier then the default access specifier will be
used.
• Initialization of Instance Variable is not Mandatory.
• Instance Variable can be accessed only by creating objects.

3. Static Variables: Static variables are also known as Class variables.

• These variables are declared similarly as instance variables, the difference is


that static variables are declared using the static keyword within a class
outside any method constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per
class irrespective of how many objects we create.
1 | Computer Programming 1 21

• Static variables are created at the start of program execution and destroyed
automatically when execution ends.
• Initialization of Static Variable is not Mandatory. Its default value is 0
• If we access the static variable like the Instance variable (through an object),
the compiler will show the warning message and it won’t halt the program.
The compiler will replace the object name with the class name automatically.
• If we access the static variable without the class name, the Compiler will
automatically append the class name.

2.1.3 Data Types

All variables use data-type during declaration to restrict the type of data to be
stored. Therefore, we can say that data types are used to tell the variables the type of
data it can store. Whenever a variable is defined in C++, the compiler allocates some
memory for that variable based on the data type with which it is declared. Every
data type requires a different amount of memory.

C++ supports a wide variety of data types and the programmer can select the data
type appropriate to the needs of the application. Data types specify the size and
types of value to be stored. However, storage representation and machine
instructions to manipulate each data type differ from machine to machine, although
C++ instructions are identical on all machines.

C++ supports the following data types:

1. Primary or Built in or Fundamental data type


2. Derived data types
3. User defined data types
1 | Computer Programming 1 22

Data types in C++ are mainly divided into three types:

1. Primitive Data Types: These data types are built-in or predefined data types
and can be used directly by the user to declare variables. example: int, char,
float, bool, etc. Primitive data types available in C++ are:

• Integer • Double Floating Point


• Character • Valueless or Void
• Boolean • Wide Character
• Floating Point

Integer: The keyword used for integer data types is int. Integers typically require 4
bytes of memory space and range from -2147483648 to 2147483647.

Character: Character data type is used for storing characters. The keyword used for
the character data type is char. Characters typically require 1 byte of memory space
and range from -128 to 127 or 0 to 255.

Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type is
bool.

Floating Point: Floating Point data type is used for storing single-precision floating-
point values or decimal values. The keyword used for the floating-point data type is
float. Float variables typically require 4 bytes of memory space.

Double Floating Point: Double Floating-Point data type is used for storing double-
precision floating-point values or decimal values. The keyword used for the double
floating-point data type is double. Double variables typically require 8 bytes of
memory space.

void: Void means without any value. void data type represents a valueless entity. A
void data type is used for those function which does not return a value.

Wide Character: Wide character data type is also a character data type but this data
type has a size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long.

2. Derived Data Types: The data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely:

• Function
• Array
• Pointer
• Reference
1 | Computer Programming 1 23

3. Abstract or User-Defined Data Types: These data types are defined by the user
itself. Like, as defining a class in C++ or a structure. C++ provides the following user-
defined datatypes:

• Class
• Structure
• Union
• Enumeration
• Typedef defined Datatype

2.1.4 Operators in C++


Operators are the foundation of any programming language. We can define
operators as symbols that help us to perform specific mathematical and logical
computations on operands. In other words, we can say that an operator operates the
operands.
For example, ‘+’ is an operator used for addition, as shown below:

Operators in C++ can be classified into 6 types:

1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators

1. C++ Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables


and data.

For example,

Here, the + operator is used to add two variables a and b. Similarly, there are
various other arithmetic operators in C++.
1 | Computer Programming 1 24

Example 1: Arithmetic Operators

Output:

a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1

Here, the operators +, - and * compute addition,


subtraction, and multiplication respectively as
we might have expected.

Increment and Decrement Operators

C++ also provides increment and decrement operators: ++ and -- respectively.

• ++ increases the value of the operand by 1


• -- decreases it by 1
1 | Computer Programming 1 25

For Example,

Here, the code ++num; increases the value of num by 1.

Example 2: Increment and Decrement Operators

Output:

result_a = 11
result_b = 99

In the above program, we have used


the ++ and -- operators as prefixes
(++a and --b). However, we can also
use these operators as postfix (a++
and b--).

2. C++ Assignment Operators

In C++, assignment operators are used to assign values to variables.

For example,

Here, we have assigned a value of 5 to the variable a.


1 | Computer Programming 1 26

Example 3 : Assignment Operators

Output:

a = 2
b = 7

After a += b;
a = 9

3. C++ Relational Operators

A relational operator is used to check the relationship between two operands.


1 | Computer Programming 1 27

For example,

Here, > is a relational operator. It checks if a is greater than b or not.

If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

Example:

Output:

3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

Note: Relational operators


are used in decision-
making and loops.
1 | Computer Programming 1 28

4. C++ Logical Operators

Logical operators are used to check whether an expression is true or false. If


the expression is true, it returns 1 whereas if the expression is false, it returns
0.

In C++, logical operators are commonly used in decision making. To further


understand the logical operators, let's see the following examples,
1 | Computer Programming 1 29

Example:

Output:

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits.
They can only be used alongside char and int data types.
1 | Computer Programming 1 30

6. Other C++ Operators


Here's a list of some other common operators available in C++. We will learn
about them in later tutorials.
1 | Computer Programming 1 31

2.3 References
Malini Devi J. (2014). C++ Programming Language for Beginner.
Chapter 1 pp. 1-4

Hari Mohan Pandey (2015). Object-Oriented Programming C++ Simplified;


Computer Engineering Department NMIMS University Mumbai; An ISO 9001:2008
Certified Company; ISBN 978-93-81159-50-7

C++ Programming Language


https://www.tutorialspoint.com/cplusplus/index.htm
https://www.w3schools.com/cpp/
https://cplusplus.com/doc/tutorial/

2.4 Acknowledgment
The images, tables, figures, and information contained in this module were
taken from the references cited above.

You might also like