You are on page 1of 14

UNIT 2: C++ Basics

UNIT

2 C++
BASICS

This lesson covers an overview of C++ as a


programming language and the steps required to
process a program written in C++. CodeBlocks
will be introduced as an integrated development
environment that provides comprehensive
facilities to computer programmers for software
development.
This lesson discusses the basic elements of C++,
which are symbols, identifiers, reserved words,
data types, operators, and expressions. The
students will become familiar with the basic
structure of a C++ program and input/output
fundamentals which will enable them to begin
writing a simple program.

IT 103: COMPUTER PROGRAMMING 1 58


UNIT 2: C++ Basics

LESSON 2:
Basic Elements of a Program

OBJECTIVES:
At the end of the lesson, students will be able to:

▪ Recognize the basic elements of a C++ program


▪ Understand the different symbols in a C++ program
▪ Familiarize in different data types and reserved words in
constructing a C++ program

IT 103: COMPUTER PROGRAMMING 1 59


UNIT 2: C++ Basics

Symbols

The smallest individual unit of a program in any programming language is called a


“token”. C++ tokens are divided into special symbols, word symbols, and identifiers.

Following are some of the special symbols:

, Commas are used to dispersed items in a list.


; Semicolons are used to end statement
+ - * / Mathematical symbols
<= != == >= Relational operators

Comment symbol

The program that you write should be direct not only to you but also to the reader itself.
Part of good programming is the including of comments in the program. Generally,
comments can be used to explain the program’s purpose or explain the meaning of
key statements in the program. The compiler ignores these comments when it
translates the program into executable code.

Two types of comments symbols

1.) // single-line comment symbol


It can be put anywhere in the line. Everything runs into in that line after
// is ignored by the compiler.

For example:

// This is my first program


// C++ Language

2.) /* */ multiple-line comment symbol


The compiler ignores anything that appears between these two symbols.

For example:

/* This is my first program


C++ Language */

IT 103: COMPUTER PROGRAMMING 1 60


UNIT 2: C++ Basics

Reserved Word

The second category of tokens is a reserved word. Reserved words are also called
keywords that cannot be redefined within any program; that is, they can not be applied
for anything other than their expected use. Some of the essential reserved words are
given below:

C++ Reserved Words

The reserved words of C++ may be strategically located in some groups. In the first
group, were also present in the C programming language and have been continued
over into C++. There are 32 such reserved words:

auto const double float int short struct unsigned


break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

There are other 30 reserved words that were not in C, are therefore new to C++:

asm dynamic_cast namespace reinterpret_cast try


bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t

The following 11 C++ reserved words are not vital when the standard ASCII character
set is being used. Still, they have been added to give more readable alternatives for
some of the C++ operators, and also to encourage programming with character sets
that lack characters needed by C++.

xor_eq bitand compl not_eq or_eq and


and_eq bitor not or xor

A specific compiler may not be completely modern, which implies that some (and possibly many) of the
reserved words in the lead up to two groups may not yet be actualized.

Reserved words, "keywords," and predefined identifiers...

There is a differentiation between reserved words and predefined identifiers, which are once in a while
collectively referred to as keywords. Nonetheless, be aware that the terminology is nonstandard. As an
illustration, some authors use keywords in the same sense that others use the reserved word.

IT 103: COMPUTER PROGRAMMING 1 61


UNIT 2: C++ Basics

Identifier

The third category of tokens is the identifier. Identifier refers to the names of variables,
constants, functions, and other objects defined in a C++ program. It allows us to name
data and other objects in the program. Each identified object in the computer is stored
at a unique address. If we did not have identifiers that we could use to represent data
locations symbolically, we would have to know and use the object's addresses.
Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located. Different programming languages use different syntactical rules
to form identifiers.

In C++, the rules for identifiers are very simple.

▪ The only valid name symbols are the capital letters A through Z, the lowercase
letters a through z, digits 0 – 9, and underscore.
▪ The first character cannot be a digit or an underscore.
▪ An identifier cannot contain punctuation marks, math symbols, or other special
symbols.
▪ ANSI guarantees only the first 32 characters to be significant.
▪ C++ identifier is case-sensitive,
▪ The last rule is that the name we create cannot be keywords. Keywords are
also known as reserved words.

Examples of Valid and invalid identifiers

 Valid Identifiers  Invalid Identifiers


grade grade+3
area1 1area
area_of_triangle area of triangle

Example:

Identify if each identifier is valid or invalid.

Identifiers Valid or Invalid


abd
123score
rate+1
salary
item_2

IT 103: COMPUTER PROGRAMMING 1 62


UNIT 2: C++ Basics

Data Types

A data type of a variable in the operating system assigns memory and decides what
can be stored in the reserved memory.

Primitive Built-in Data Types


C++ offers both built-in and user-defined data types. The following table lists seven
basic C++ data types:

Data Type Keyword


Boolean bool
Character char
Integer int
Floating Point float
Double Floating Point double
Valueless value
Wide Character wchar_t

Some of the basic types can be modified using one or more of these type modifiers:
▪ signed
▪ unsigned
▪ short
▪ long

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

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,647 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

IT 103: COMPUTER PROGRAMMING 1 63


UNIT 2: C++ Basics

▪ Each data type associated with a different set of values


▪ The siSize of the number represented determines the data type
▪ Data type limits the amount of memory used
▪ Other compilers may have a diverse range of values for each data type.

The String Type

The data type string is a computer programmer-defined type of data. Unlike primitive
data type, a string cannot be directly available for use in a program. To use this type,
you need to access program components from the C++ library.

A string is an arrangement of zero or more characters. Strings in C++ are bounded in


double quotation marks. A string containing no characters is called an empty string or
null. The following are examples of strings:

“Hello” “Programming” “Mary”

Data Type Example


bool true, false
char ‘A’ , ‘a’ , ‘+’
int 10 , 250 , 1002
float / double 1.50 , 10.56 , 212.245
string “Hi” , “Hello” , “bye”

Variable

A variable is used to hold data. The data stored in a variable is called its value.

In programming languages, variables are implemented as memory locations.

▪ The compiler assigns a memory location to each variable name (identifier) in


the program.
▪ Each variable in a computer program must be declared.
▪ When you declare a variable, you are telling the compiler what kind of data you
will be stored in the variable.

How to declare a variable?

Variable Declaration. A syntax rule to declare a variable is:

datatype identifier;

For example, consider the following statements:

int x;
float rate;
char answer;
IT 103: COMPUTER PROGRAMMING 1 64
UNIT 2: C++ Basics

Note:

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

Operators

An operator is used to perform specific arithmetic or logical manipulations. C++ is rich


in built-in operators and provides the following types of operators:

▪ Assignment Operator
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators

Assignment Operator

The assignment operator (=) is used in the assignment statement, which takes the
following form:

variable = expression;

To evaluate assignment statement, the expression on the right-hand side of the equal
sign is assessed first, and then the variable on the left-hand side is set to this value.

A variable needs to be initialized the first time a value is placed in the variable,

A C++ statement such as:

y = 5; means five will be stored in y.


x= y + 2; means add 2 to the value of y, and assign the new
value to the variable x. Hence, x will yield a value of
7.
Examples of Variable Initializations

int x =10;
double pi = 3.14;
char ans = ‘y’;

IT 103: COMPUTER PROGRAMMING 1 65


UNIT 2: C++ Basics

The following arithmetical operations supported by C++ are:

Arithmetic Operator
Symbol Name Example Definition
It is taking two or more numbers
and adding them together. The
+ Addition x+y
result of an addition is called
sum.
represents the operation of
removing objects from a
- Subtraction x–y
collection. The result of
subtraction is called a difference.
one of the four basic operations
of arithmetic gives the result of
* Multiplication x* y combining groups of equal sizes.
The result of a multiplication is
called a product.
It is a method of distributing a
/ Division x/y
group of things into equal parts.
It is placed between
two expressions that have the
= Equal x=y same value, or for which one
studies the conditions under
which they have the same value
Modulus or It is the remainder after dividing
% x%y
Modulo one number by another.
++ Increment x ++ or ++ x Increases the value of x by 1
-- Decrement y ++ or -- y Decreases the value of x by 1
+ (unary) Positive +x The value of x
- (unary Negative -x The arithmetic negation of x

Arithmetic operations such as addition, subtraction, multiplication, and division


correspond literally to their respective mathematical operators.

The modulo operator, represented by a percentage sign (%), gives the remainder of a
division process.

For example:
x = 10 % 3;

The resulting value of x is 1 , since dividing 10 by 3 results in 3, with a remainder of 1.

IT 103: COMPUTER PROGRAMMING 1 66


UNIT 2: C++ Basics

Order of precedence

It is likely to build mathematical expressions with several operators. When more than
one arithmetic operator is used in an expression, C++ uses the operator precedence
rules to assess the expression. In line with the order of precedence rules for arithmetic
operators,

* , / ,% are at higher level of precedence than + , -

However, when operators have the same level, the operations are performed from
left to right.

Consider the following statement:


x = 12 + 6 / 3

What value will be stored in x? The answer is 14 because the order of operations
dictates that the division operator works before the addition operator does.

Expression Value
5 + 2 *4 13
10 / 2 – 3 2
8 + 12 * 2 – 4 28
6–3*2+7–1 6
(5 + 2) * 4 28
10 / (5 – 3) 5
8 + 12 * (6 – 2) 56
(6 – 3) * (2 + 7) / 3 9

Converting Algebraic Expression to Programming Expression

You probably remember from algebra class that the expression 2xy is understood to
mean 2 times x times y. in math, you do not always use an operator for multiplication.
Programming languages, however, require an operator for any mathematical
operation.

Programming
Algebraic Expression
Expression
6B 6*B
(3)(12) 3 * 12
4xy 4*x*y
𝑥
y = 32 y=x/2*3
z = 3bc + 4 z = 3 * b *c + 4
𝑥+2
a = 𝑎−1 a = (x + 2) / (a – 1)

IT 103: COMPUTER PROGRAMMING 1 67


UNIT 2: C++ Basics

Increment and Decrement Operators

Increment (++) and Decrement (--) operators are placed either in front or after the
operand. The statements

++x; or ++x;
- -y; or y- -;

Means x is incremented by 1, and y is decremented by 1, respectively.

When used in assignment statements, however, placing the operators after the
variable takes a different meaning.

Consider the following statements:


x =5;
y =x++;
z = y- -*2;

In the assignment statement for the variables y and z, the increment and decrement
operators are placed after the variable operands. As such, the operators are called
post-increment and post-decrement operators, respectively. This means that the
variable operands will be incremented/decremented after the expressions have been
thoroughly evaluated. In the statement

y=x++;

The value of the variable x is assigned first to the variable y before it is incremented.
Thus, after the statement is executed, x=6, and y=5. In the statement

z=y- -*2;

When the increment/decrement operator is placed ahead of the variable operand, it is


considered a pre-increment/pre-decrement operator, and the increment/decrement is
executed before anything else is done with the variable.

With three different ways of writing an increment/decrement operation, the concern


now would be which of the three methods is best. As a general rule, using the ++ / - -
operators would execute faster than the standard =/- and shorthand operators.

Example 1 Example 2
x=4;
y=++x; // x contains x=5;
5, y contains y=x++;// x contains
5 6, y contains 5

IT 103: COMPUTER PROGRAMMING 1 68


UNIT 2: C++ Basics

Compound Operators (Compound Assignments)

Corresponding to the five arithmetic operators *, /, %, + and -, there is a shorthand


notation that combines the assignment operator(=) and an arithmetic operator so that
the given variable can have its value changed by adding, subtracting, multiplying by,
or dividing by a specified value.

Shorthand Notation Equivalent to:

x += 2; x = x + 2;
y - = 5; y = y - 5;
a /= 2; a = a / 2;
b * = c; b = b * c;
z %=10 z = z % 10;

Relational Operators

Two expressions can be collate using relational operators. For example, to know if
two values are equal or if one is less than the other.
The result of such an operation is either true or false (i.e., a Boolean Value)

The relational operators in C++ are:

Relational Operator
Symbol Name Example Definition
Compares if the value of the
< Less than x<y left operand is less than the
value of the right operand.
Compares if the value of the
left operand is greater than
> Greater than x>y
the value of the right
operand.
Compares if the value of the
left operand is less than or
<= Less than or equal to x <= y
equal to the value of the
right operand.
Compares if the value of the
Greater than or equal left operand is greater than
>= x>=y
to or equal to the value of the
right operand.
Compares if the values of
== Equal to x == y two operands are equal or
not.
Compares if the values of
!= Not Equal x != y two operands are equal or
not.

IT 103: COMPUTER PROGRAMMING 1 69


UNIT 2: C++ Basics

Boolean Expressions

A Boolean expression is an expression that is either true or false.

Here there are some examples:

(7 == 5) // false
(5 > 4) // true
(3 != 2) // true
(6 >= 6) // true
(5 < 5) // false

Of course, it is not only numeric constants that can be linked but only any value,
including variables.

Suppose that a=2, b=3 and c=6, then:

// false,
(a = = 4)
since a is not equal to 4
// true,
(a * b >= c)
since (2*3 >= 6) is true
// false,
( b+4 > a)
since (3+4 > 2*6) is false

Logical Operator
Symbol Name Example Definition
((a == 5) && (b> 6)) Logical AND operator. If
// evaluates to false both the operands are non-
&& And
zero, then the condition
( true && false )
becomes true.
((a == 5) || (c>8))
Logical OR Operator. If
any of the two operands is
|| Or // evaluates to true
( true || false ) non-zero, then condition
becomes true.
!(a == 5)
// evaluates to false Logical NOT Operator.
because the Use to reverses the logical
state of its operand. If a
! Not expression at its
condition is true, then
right (a == 5) is
Logical NOT operator will
true make false.

IT 103: COMPUTER PROGRAMMING 1 70


UNIT 2: C++ Basics

Suppose that a= 5; b=3 and c=6, then:

((a == 5) && (b> 6)) // evaluates to false


( true && false )

((a == 5) || (c>8)) // evaluates to true


( true || false )

!(a == 5) // evaluates to false because the


expression at its right (a == 5)
is true

IT 103: COMPUTER PROGRAMMING 1 71

You might also like