03 - CSC 201 - Lecture Note

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

C++ INTRODUCTION

Content
- Tokens
- Variables, Literals & Constants
- Data Types
- Basic I/O
- Type Conversion
- Operators
- Comments
C++ TOKENS
Tokens are the smallest individual units in a program. A C++ program is written using tokens. It has the
following tokens:

• Keywords: also known as reserved words in C++, which have predefined meanings to the
compiler. Examples are int, float, if, for, while etc.

• Identifiers: refer to the name of variables, functions, arrays, classes, or other user-defined
program elements created by the programmer.

• Literals: are data items that never change their value during the execution of the program.

• Punctuators: Punctuators are special symbols used for punctuation and syntactic purposes.
Examples are semicolon “;”, colon “:”, comma “,”, dot “.”, parentheses (), braces {}, square
brackets [], asterisk “*”,

• Operators: symbols that perform various operations on operands.

C++ VARIABLES
In C++, a variable is a named storage location in memory that holds a value of a particular data type. To
use a variable, the variable must be declared and initialised. A variable is a name which is associated with
a value, and the value can be changed.
Variable Declaration: To declare a variable, you need to specify its data type, followed by the variable
name. Syntax: data_type variable_name; Example: int age;

The variable name is “age”, and the data type is, which means it can hold integer values.
Variable Initialisation: Initialisation simply mean assigning a value to a variable. A variable can be
initialised at the time of declaration or assigned a new value using the assignment operator “=”.

Initialisation at the time of declaration: int age = 20;

Initialisation by assigning a new value: age = 20;

The variable name is “age”, which is associated with t h e value 20, and int is the data type.
Rules for Naming a Variable
1. A variable name can begin with only a letter or underscore “_”
2. A variable name can contain only letters, numbers and an underscore “_”, no special characters or
spaces.
3. A variable name cannot be a keyword.
Note: C++ identifiers are case-sensitive
Good Variable Naming Convention
• Meaning Names: Choose variable names that are meaningful and descriptive of their purpose or
the data they store. E.g. use “studentName” instate of “s” to store student’s name.
• Variable names should start with lowercase letters. Although a variable name can start with
underscore or uppercase letters, it is not encouraged.
• Camel or Snake Case: Use either Camel or Snake Case to separate words in variable names.
Example Camel case: “userName” or Snake case: “user_name”

• Consistency: Maintain consistent naming conventions throughout your codebase.

• Define constants in uppercase.

C++ LITERALS
Literals are data used for representing fixed values. They can be used directly in the code. For example, 1,
2.5, 'c' etc. Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these terms. The
following types of literals are available in C++.

• Integer Literals: whole numbers without any fractional or exponential part. C++ allows three types
of integer literals.
o Decimal (base 10): consists of a sequence of digits and should not begin with 0 (zero). For
example, 25, -179, +108.
o Octal (base 8): consists of a sequence of digits starting with 0 (zero). For example. 014, 012.
o Hexadecimal (base 16): consists of a sequence of digits preceded by 0x. For example, 0x7f,
0x5AD9.

• Floating-point Literals: A floating-point literal is a numeric literal that has either a fractional form
or an exponent form. For example, -5.0, 0.000024, 0.55E-5 (E-5 = 10-5).

• Character Literals: A character literal is created by enclosing a single character inside single
quotation marks. For example: 'a', 'm', 'F', '2', '}' etc.

• String Literals: A string literal is a sequence of characters enclosed in double-quote marks. For
example: “good”, “CSC 201”
C++ CONSTANTS
In C++, we can create variables whose value cannot be changed. For that, we use the const keyword.

Syntax: const double PI = 3.142


• It is a good programming style to use named constants in your program to explain the
meanings of numeric values. For example, compare the statements
float r = 25
double area = 3.142 * (r * r);
vs
double area = PI * (r * r);

• A programmer reading the first statement may not understand the significance of the number
3.142. The second statement, with a named constant, makes the computation much clearer.

C++ DATA TYPES


Data types define the type of data a variable can hold. For example, an integer variable can hold integer
data, and a character-type variable can hold character data. Data types in C++ are categorised into
three groups: Built-in, User-defined and Derived.

C++ Data Types

Built-in Derived User-Defined

- int - array - class


- float - function - struct
- double - pointer - union
- char - reference - enum
- bool
- void
C++ Built-in Data Types

These data types are built-in or predefined data types and can be used directly by the user to declare
variables.
• int: Represents integers with a fixed size of 4 bytes within a range of -2,147,483,648 to
2,147,483,647. Example: int num = 80;
• float: Represents floating-point numbers (real numbers) with single precision. The size is 4 bytes,
and the range is 3.4E +/- 38 (7 digits). Example: float num = 123.78987;
• double: Represent floating-point number with double precision. The size is 8 bytes, and
the range is 1.7E +/- 308 (15 digits). Example: double num = 10098.98899;
• char: For characters. Size 1 byte. Example: char ch = 'A';
• bool: For Booleans, true or false. Example: bool b = true;
• void: Represents the absence of any type and is typically used as a return type for functions that
do not return a value.

C++ Derived Data Types


Derived data types that are derived from the primitive or built-in datatypes are referred to as Derived
Data Types. There are four types of derived data types in C++
• array: Represents a fixed-size sequence of elements of the same type.
• function: A block of code or program segment that is defined to perform a specific, well-defined
task.
• pointer: Represents a memory address pointing to a value of a specific type.
• reference: Represent an alias or alternative name for an existing variable.

C++ User-Defined Data Types


User-Defined data types are defined by the user itself. Like defining a class in C++ or a structure. C++
provides the following user-defined datatypes:
• class: User-defined types that encapsulate data and behaviour using the OOP principles.
• struct: User-defined types that can hold multiple variables of different types.
• enum: User-defined types consisting of a set of named values.
• union: A union is a user-defined type in which all members share the same memory location. This
definition means that at any given time, a union can contain no more than one object from its list of
members.
C++ Operators
Operators are symbols or special characters that perform specific operations on operands. They are used
to manipulate values, perform calculations, compare values, and more. Types of operators in C++:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators

Arithmetic Operators
They are:
• + Addition: Adds two operands together.
• - Subtraction: Subtracts the second operand from the first operand.
• * Multiplication: Multiplies two operands.
• / Division: Divides the first operand by the second operand.
• % Modulo: Computes the remainder of the division of the first operand by the second operand.
• ++ Increment: Increases the value of the operand by one.
• -- Decrement: Decreases the value of the operand by one.
Example of Arithmetic Operators
Output:

Assignment Operators
• = Assignment: Assigns the value on the right side to the variable on the left side.
• += Add and Assign: Adds the value on the right side to the variable on the left side and assigns the
result to the variable.
• -= Subtract and Assign: Subtracts the value on the right side from the variable on the left side and
assigns the result to the variable.
• *= Multiply and Assign: Multiplies the variable on the left side by the value on the right side and
assigns the result to the variable.
• /= Divide and Assign: Divides the variable on the left side by the value on the right side and assigns
the result to the variable.
• %= Modulo and Assign: Computes the modulo of the variable on the left side with the value on the
right side and assigns the result to the variable.
Example of Assignment Operators

Output:

Comparison Operators
• == Equal to: Checks if two operands are equal.
• != Not equal to: Checks if two operands are not equal.
• < Less than: Checks if the left operand is less than the right operand.
• > Greater than: Checks if the left operand is greater than the right operand.
• <= Less than or equal to: Checks if the left operand is less than or equal to the right operand.
• >= Greater than or equal to: Checks if the left operand is greater than or equal to the right operand.
Example of Comparison Operators

Output
Logical Operators

Logical operators perform logical operations and return Boolean results. They are mainly used in
conditional statements and loops for evaluating a condition.

• && Logical AND: Performs logical AND operation on two operands.

• || Logical OR: Performs logical OR operation on two operands.

• ! Logical NOT: Negates the logical value of the operand.

Example of Logical Operators

Output:

Ternary Operator
condition ? expression1 : expression2: Evaluates the condition, and if true, returns the value of
expression1; otherwise, returns the value of expression2.
Example of Ternary Operator

Output

Bitwise Operators
Bitwise operators perform logical operations bit-by-bit on the operands. There are six bitwise
Operators:

• & Bitwise AND: Performs bitwise AND operation on two operands - if we have num1 & num2,
compares corresponding bits of num1 and num2 and generates 1 if both bits are equal, else it
returns 0.

• | Bitwise OR: Performs bitwise OR operation on two operands- num1 | num2 compares
corresponding bits of num1 and num2 and generates 1 if either bit is 1, else it returns 0.
• ^ Bitwise XOR: Performs bitwise exclusive OR (XOR) operation on two operands. num1 ^ num2
compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it
returns 0.
• ~ Bitwise Complement: Flips the bits of the operand. num1 is a complement operator that just
changes the bit from 0 to 1 and 1 to 0.
• << Bitwise Shift Left: Shifts the bits of the left operand to the left by the number of positions
specified by the right operand. num1 << 2, moves the bits to the left, discards the far left bit,
and assigns the rightmost bit a value of 0.
• >> Bitwise Shift Right: Shifts the bits of the left operand to the right by the number of positions
specified by the right operand. num1 >> 2 moves the bits to the right, discards the far right bit,
and assigns the leftmost bit a value of 0.

Example of Bitwise Operators

Output:

Miscellaneous Operators
There are a few other operators in C++, such as the comma operator and sizeof operator.

Comma Operator
The comma operator “,” is used to separate two or more expressions that are included where only
one expression is expected.
• When the set of expressions has to be evaluated for a value, only the rightmost expression is
considered. For example, the following code:
a = (b=3, b+2);
o Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end,
variable a would contain the value 5 while variable b would contain the value 3.
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and returns
the size in bytes of that type or object: a = sizeof(char);
• This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof
is a constant, so it is always determined before program execution.

Explicit type casting operator


• Type-casting operators allow you to convert a datum of a given type to another. There are
several ways to do this in C++. The simplest one, which has been inherited from the C
language, is to precede the expression to be converted by the new type enclosed between
parentheses (()):
int i;
float f = 3.14;
i = (int) f;
• The above code converts the float number 3.14 to an integer value (3), the remainder is lost.
Here, the typecasting operator was (int).
• Another way to do the same thing in C++ is using the functional notation: preceding the
expression to be converted by the type and enclosing the expression between parentheses:
i = int (f);
Both ways of typecasting are valid in C++.

Operator Precedence in C++


This determines which operator needs to be evaluated first if an expression has more than one operator.
Operators with higher precedence at the top and lower precedence at the bottom.

o Parentheses: ()

o Unary Operators: ++, --, !, ~


o Multiplicative: *, /, %
o Additive: +, –
o Shift: <<, >>
o Relational: <, >, >=, <, <=
o Equality: ==, !=
o Bitwise AND &, Bitwise XOR ^, Bitwise OR |
o Logical AND &&, Logical OR ||
o Ternary: ? :
o Assignment: = += -= *= /= %= > >= < <= &= ^= |=

Integer division and remainder


• Division works as you would expect as long as at least one of the numbers involved is a
floating-point number. That is, 7.0 / 4.0, 7 / 4.0, and 7.0 / 4 all yield 1.75.
• However, if both numbers are integers, then the result of the division is always an integer,
with the remainder discarded.
• That is, 7 / 4 evaluates to 1 because 7 divided by 4 is 1 with a remainder of 3 (which is
discarded). This can be a source of subtle programming errors.
• If you are interested in the remainder only, use the % operator: 7 % 4
• the % operator computes the remainder of an integer division.

Rounding to the nearest Integer


• When a floating-point value is assigned to an integer variable, the fractional part is
discarded:
double price = 2.23;

int naira = price; // Sets naira to 2

• Discarding the fractional part is not always what you want. Often, you want to round to the
nearest integer. To round a positive floating-point value to the nearest integer, add
0.5 and then convert to an integer:

#include <iostream>
using namespace std;

int main ()

{
double price = 2.23;

int naira = price + .5;


cout << "the price is" << naira;
return 0;
}
Powers and roots
• In C++, there are no symbols for powers and roots. To compute them, you must call
functions.
• To take the square root of a number, you use the sqrt function.
• For example, √x is written as sqrt(x). To compute xn, you write pow(x, n).

+
• The expression 𝑏 × $1 + '
())
* becomes b * pow(1 + r/100, n)

Arithmetic Expressions

Mathematical Expression C++ Expression Comments

,-. (x + y) / 2 The parentheses are required; x + y / 2


/

,. Parentheses are not required; operators with the same precedence


/ x*y/2 are evaluated from left to right.
+
1
𝑏 × 01 + 233
4 b * pow(1 + r/100, n) Remember to add #include <cmath> to the top of your program.

5𝑎/ + 𝑏/ sqrt(a * a + b * b) a * a is simpler than pow(a, 2).

7-8-9 If i, j, and k are integers, using a denominator of 3.0 forces floating-


:.3 (i + j + k) / 3.0 point division.

You might also like