KEMBAR78
Lecture-02-Basic Elements of C++ | PDF | Variable (Computer Science) | C++
100% found this document useful (1 vote)
41 views82 pages

Lecture-02-Basic Elements of C++

The document provides an overview of the C++ programming language, covering its structure, key elements, and fundamental concepts such as keywords, identifiers, operators, and data types. It discusses the advantages and disadvantages of C++, its applications, and includes examples of basic programming constructs like comments and the 'Hello World' program. Additionally, it explains the significance of various operators and the rules for naming identifiers in C++.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
41 views82 pages

Lecture-02-Basic Elements of C++

The document provides an overview of the C++ programming language, covering its structure, key elements, and fundamental concepts such as keywords, identifiers, operators, and data types. It discusses the advantages and disadvantages of C++, its applications, and includes examples of basic programming constructs like comments and the 'Hello World' program. Additionally, it explains the significance of various operators and the rules for naming identifiers in C++.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Computer Programming

Using

Course Code: CoSc 1012

March-2025
Chapter II
Basic Elements of C++

2
Chapter Contents

Topic One: C++ Program Structure

Topic Two: Keywords, identifiers, operators

Topic Three: Variables and Data types

Topic Four: Expressions

Topic Five: Statements

3
Introduction to C++
Programming Language
 C++ is a general-purpose programming language that was developed as an
enhancement of the C language to include object-oriented paradigm.
 It is an imperative and a compiled language.
 Here are some key points to keep in mind while working with C++:
 Object-Oriented Programming: C++ is an object-oriented programming
language, which means that it allows you to define classes and objects to
model real-world entities and their behavior.
 Strong Type System: C++ has a strong type system, which means that
variables have a specific type and that type must be respected in all
operations performed on that variable.
 Low-level Access: C++ provides low-level access to system resources,
which makes it a suitable choice for system programming and writing
efficient code.
 Standard Template Library (STL): The STL provides a large set of pre-
written algorithms and data structures that can be used to simplify your code
and make it more efficient.
4
Cont…
Cross-platform Compatibility: C++ can be compiled and run
on multiple platforms, including Windows, MacOS, and Linux,
making it a versatile language for developing cross-platform
applications.
Performance: C++ is a compiled language, which means that
code is transformed into machine code before it is executed.
This can result in faster execution times and improved
performance compared to interpreted languages like Python.
Memory Management: C++ requires manual memory
management, which can lead to errors if not done correctly.
However, this also provides more control over the program’s
memory usage and can result in more efficient memory usage.
Syntax: C++ has a complex syntax that can be difficult to
learn, especially for beginners. However, with practice and
experience, it becomes easier to understand and work with. 5
Applications of C++:
C++ finds varied usage in applications such as:
 Operating Systems & Systems Programming. e.g. Linux-based OS
(Ubuntu etc.)
 Browsers (Chrome & Firefox)

 Graphics & Game engines (Photoshop, Blender, Unreal-Engine)

 Database Engines (MySQL, MongoDB, Redis etc.)

 Cloud/Distributed Systems

6
Advantages of C++:
Performance: C++ is a compiled language, which means that
its code is compiled into machine-readable code, making it one
of the fastest programming languages.
Object-Oriented Programming: C++ supports object-
oriented programming, which makes it easier to write and
maintain large, complex applications.
Standard Template Library (STL): The STL provides a wide
range of algorithms and data structures for working with data,
making it easier to write efficient and effective code.
Machine Independent: C++ is not tied to any hardware or
processor. If the compiler compiles the program in the system,
it will be able to run no matter what the hardware is.
Large Community: C++ has a large, active community of
developers and users, providing a wealth of resources and
support for learning and using the language. 7
Disadvantages of C++:
Steep Learning Curve: C++ can be challenging to learn,
especially for beginners, due to its complexity and the number
of concepts that need to be understood.

Verbose Syntax: C++ has a verbose syntax, which can make


code longer and more difficult to read and maintain.

Error-Prone: C++ provides low-level access to system


resources, which can lead to subtle errors that are difficult to
detect and fix.

8
Some Interesting Facts about
C++:
The name of C++ signifies the evolutionary nature of the
changes from C. “++” is the C increment operator.
C++ is one of the predominant languages for the development
of all kind of technical and commercial software.
C++ introduces Object-Oriented Programming, not present in
C. Like other things, C++ supports the four primary features of
OOP: encapsulation, polymorphism, abstraction, and
inheritance.
C++ got the OOP features from Simula67 Programming
language.

A function is a minimum requirement for a C++ program to


run.(at least main() function) 9
Writing First C++ Program
The “Hello World” program is the first step towards learning
any programming language and is also one of the most straight
forward program and displays the message “Hello World” on the
output screen.
C++ Hello World Program on the console screen.

10
Cont…
Let us understand every line and terminologies of the above
program.
1. // C++ program to display “Hello World”
This line is a comment line. A comment is used to display
additional information about the program. A comment does
not contain any programming logic. When a comment is
encountered by a compiler, the compiler simply skips that line
of code.
2. #include <iostream>
The #include is a preprocessor directive tells the compiler to
include the content of a file in the source code. For
example, #include<iostream> tells the compiler to include
the input-output library which contains all C++’s input/output
library functions.
11
Cont…
3. using namespace std
This is used to import the entity of the std namespace into the
current namespace of the program. It is basically the space
where all the inbuilt features of C++ are declared. For example,
std::cout.
4. int main() { }
The main() function is the entry point of every C++ program,
no matter where the function is located in the program. The
opening braces ‘{‘ indicates the beginning of the main function
and the closing braces ‘}’ indicates the ending of the main
function. 12
Cont…
5. cout<<“Hello World”;
The cout is a tool (object) that is used to display output on the
console screen. Everything followed by the character << in
double quotes ” ” is displayed on the output screen. The semi-
colon character at the end of the statement is used to
indicate that the statement is ending there.
6. return 0
This statement is used to return a value from a function and
indicates the finishing of a function. Here, it is used to sent the
signal of successful execution of the main function.
13
In C++ there are two types
of comments
Single Line Comment

In C++, single line comments are represented as // double


forward slash. It applies comments to a single line only. The
compiler ignores any text after // and it will not be executed.

Multi-Line Comment

A multi-line comment can occupy many lines of code, it starts


with /* and ends with */, but it cannot be nested. Any text
between /* and */ will be ignored by the compiler.

14
Example

15
Why are Comments used in
C++?
Comments in C++ are used to summarize an algorithm,
identify a variable’s purpose, or clarify a code segment that
appears unclear. Comments are also used for:

Comments are used for easier debugging.

make a program more readable and gives an overall description


of the code.

Comments are helpful in skipping the execution of some parts of


the code.
Every time a program or code is reused after long periods of
time, the comment recaps all the information of the code
quickly. 16
C++ Program Structure
The basic elements and concepts of the C++ programming
language to create C++ programs.

17
Cont…
When you compile and execute this program, the following
four lines are displayed on the screen.
My first C++ program.
The sum of 2 and 3 = 5
7 + 8 = 15
Num = 6
These lines are displayed by the execution of the following four
statements.
cout << "My first C++ program." << endl;
cout << "The sum of 2 and 3 = " << 5 << endl;
cout << "7 + 8 = " << 7 + 8 << endl;
cout << "Num = " << num << endl; 18
Cont…
Let us consider the following statements:

cout << "My first C++ program." << endl;

C++ output statement and it causes the computer to evaluate


the expression after the pair of symbols << and display the
result on the screen

Anything in double quotes is a string.

For example, "My first C++ program." and "7 + 8 = " are
strings.

19
Cont…
Let us consider the following statement.
cout << "The sum of 2 and 3 = " << 5 << endl;
This output statement consists of two expressions.
The first expression (after the first <<) is “The sum of 2 and 3 =
” and the second expression (after the second <<) consists of
the number 5.
The expression "The sum of 2 and 3 = " is a string and evaluates
to itself.
The second expression, which consists of the number 5
evaluates to 5. Thus, the output of the preceding statement is:
The sum of 2 and 3 = 5
20
Keywords, Identifiers &
Operators

21
Keywords
Keywords are the reserved words that have special
meanings in the C++ language. They are the words that the
language uses for a specifying the components of the language,
such as void, int, public, etc. They can’t be used for a variable
name or function name or any other identifiers.

Let’s take a look available keywords at the hello world code:

using, namespace, and return are the keywords that are


used to implement some functionality of the language. Their
meaning is predefined in C++ and will always remain same.

22
C++ Keywords
alignas
alignof and and_eq asm

auto bitand bitor bool break

case catch char char8_t char16_t

char32_t class compl concept const

consteval constexpr constinit const_cast continue

co_await co_return co_yield decltype default

delete do double dynamic_cast else

enum explicit export extern FALSE

final float for friend goto


23
C++ Keywords
if inline int long mutable

namespace new noexcept not not_eq

nullptr operator or or_eq private

protected public register reinterpret_cast requires

return short signed sizeof static

static_assert static_cast struct switch template

this thread_local throw TRUE try

typedef typeid typename union unsigned

using virtual void volatile wchar_t

while xor xor_eq


24
C++ Identifiers
In C++ programming language, identifiers are the unique
names assigned to variables, functions, classes, structs, or
other entities within the program. Let’s take a look at an
example:
// Creating a variable
int val = 10;
int num = 0;
// Creating a function
void func() {} In the above code, the words val and num are
identifiers. Basically, everything named by a programmer is an
identifier and is used to refer to the entity later in the program.25
Rules to Name of an Identifier
We can use any word as an identifier as long as it follows the
following rules:
1. An identifier can consist of letters (A-Z or a-z), digits (0-9),
and underscores (_). Special characters and spaces are not
allowed.
2. An identifier can only begin with a letter or an underscore
only.
3. C++ has reserved keywords that cannot be used as
identifiers since they have predefined meanings in the
language. For example, int cannot be used as an identifier as
it already has some predefined meaning in C++. Attempting
to use these as identifiers will result in a compilation error.
26
Example of Valid/Invalid
Identifiers

27
Cont….

Output
The sum is: 12

28
Identifier Naming Conventions
Naming Conventions are not the rules enforced by C++
language but are suggestions for naming variables by the
programming community for easier understanding. Some of the
naming conventions are as follows:

For Variables:

Use camelCase (for constants, you can use


UPPER_SNAKE_CASE)

Start with lowercase alphabet.

Use descriptive, meaningful names.

For example, frequencyCount, personName 29


Cont….
For Functions:

Use camelCase.

Use Verb or verb phrases for naming.

For example, getName(), countFrequency(), etc.

For Classes:

Use PascalCase

Use Nouns or noun phrases for naming.

For example, Car, Person, etc

30
Keywords vs Identifiers
Keywords Identifiers
Identifiers are the values used to
define different programming items
Keywords are predefined/reserved like a variable, integers, structures,
words and unions.
It defines the type of entity. It classifies the name of the entity.
an identifier can consist of
A keyword contains only alphabetical alphabetical characters, digits, and
characters, underscores.
It should be lowercase. It can be both upper and lowercase.
No special symbols or punctuations
are used in keywords and
No special symbols or punctuations identifiers. The only underscore can
are used in keywords and identifiers. be used in an identifier.
Example: Geeks_for_Geeks, GFG,
Example: int, char, while, do. Gfg1. 31
Operators in C++
In C++, an operator is a symbol that operates on a value to
perform specific mathematical or logical computations on given
values. They are the foundation of any programming language.
Table of Content
 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Ternary or Conditional Operators


32
1. Arithmetic Operators

Name Symbol Description


Addition + Adds two operands.
Subtracts second operand from the
Subtraction – first.
Multiplication * Multiplies two operands.
Divides first operand by the second
Division / operand.
Returns the remainder an integer
Modulo Operation % division.

Increment ++ Increase the value of operand by 1.

Decrement — Decrease the value of operand by 1.


33
Example

Output
a + b = 11
a - b = 5
a * b = 24
a / b = 2
a % b = 2
++a = 9
--b = 2

34
Important Points: on
Arithmetic Operators
The Modulo operator (%) operator should only be used with
integers. Other operators can also be used with floating point
values.
++a and a++, both are increment operators, however, both
are slightly different. In ++a, the value of the variable is
incremented first and then It is used in the program. In a++,
the value of the variable is assigned first and then It is
incremented. Similarly happens for the decrement operator.
You may have noticed that some operator works on two
operands while other work on one. On the basis of this
operators are also classified as:
 Unary: Works on single operand.
 Binary: Works on two operands.
 Ternary: Works on three operands.
35
2. Relational Operators
Relational operators are used for the comparison of the
values of two operands. For example, ‘>’ check right operand
is greater.
Name Symbol Description
Is Equal To == Checks both operands are equal
Checks first operand is greater than
Greater Than > the second operand
Greater Than Checks first operand is greater than
or Equal To >= equal to the second operand
Checks first operand is lesser than the
Less Than < second operand
Less Than or Checks first operand is lesser than
Equal To <= equal to the second operand
Not Equal To != Checks both operands are not equal 36
Example: Relational Operators
Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
Note: 0 denotes false
and 1 denotes true.

37
3. Logical Operators
Logical operators are used to combine two or more conditions
or constraints or to complement the evaluation of the original
condition in consideration. The result returns a Boolean value,
i.e., true or false.

Name Symbol Description


Returns true only if all the
operands are true or non-
Logical AND && zero.

Returns true if either of the


Logical OR || operands is true or non-zero.
Returns true if the operand is
Logical NOT ! false or zero. 38
Cont…
Output
a && b is 1
a || b is 1
!b is 0

39
4. Bitwise Operators
Bitwise Operations: are works on bit-level. So, compiler first
converted to bit-level and then the calculation is performed on
the operands.
Name Symbol Description
Copies a bit to the evaluated result if it
Binary AND & exists in both operands
Copies a bit to the evaluated result if it
Binary OR | exists in any of the operand
Copies the bit to the evaluated result if
it is present in either of the operands
Binary XOR ^ but not both
Shifts the value to left by the number
Left Shift << of bits specified by the right operand.
Shifts the value to right by the number
Right Shift >> of bits specified by the right operand.
40
One’s Complement ~ Changes binary digits 1 to 0 and 0 to 1
Example:
Note: Only char and int data types can be used with Bitwise
Operators.
Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7

41
5. Assignment Operators
 Assignment Operators: are used to assign value to a variable.
We assign the value of right operand into left operand
according to which assignment operator we use.

42
Cont…
Name Symbol Description
Assigns the value on the right to the
Assignment = variable on the left.
First add right operand value into left
operand then assign that value into left
Add and Assignment += operand.
First subtract right operand value into
Subtract and left operand then assign that value into
Assignment -= left operand.
First multiply right operand value into
Multiply and left operand then assign that value into
Assignment *= left operand.
First divide right operand value into left
Divide and operand then assign that value into left
43
Assignment /= operand.
Example
Output
a = 6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6

44
6. Ternary or Conditional
Operators
Ternary or conditional operator returns the value, based
on the condition.
Expression1 ? Expression2 : Expression3
The ternary operator ? determines the answer on the basis of
the evaluation of Expression1. If it is true,
then Expression2 gets evaluated and is used as the answer
for the expression. If Expression1 is false,
then Expression3 gets evaluated and is used as the answer
for the expression.

This operator takes three operands, therefore it is known as


a Ternary Operator. 45
Example
Output
The greatest
number is 4

46
Miscellaneous Operators
1. sizeof Operator
sizeof operator is a unary operator used to compute the size
of its operand or variable in bytes. For example,
sizeof (char);
sizeof (var_name);
2. Comma Operator (,)
Comma operator is a binary operator that is used for
multiple purposes. It is used as a separator or used to evaluate
its first operand and discards the result; it then evaluates the
second operand and returns this value (and type).
int n = (m+1, m-2, m+5);
int a, b, c; 47
Cont…
3. Arrow Operator
Arrow operator is used to access the variables of classes or
structures through its pointer.
sptr -> member;

4. Casting Operators
Casting operators are used to convert the value of one data
type to another data type. For example, for an integer value x:

(float)x
static_cast<float>(x)
48
Cont…
5. Dot Operator(.)
Dot operator is used to access members of structure
variables or class objects using their object names.
obj . member;

6. Addressof Operator (&)


Addressof operator is used to find the memory address in
which a particular variable is stored. In C++, it is also used to
create a reference.
&var_name;
49
Variables and Data Types

50
C++ Variables
In C++, 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 accessed or changed during program execution.
Creating a Variable
Giving it a name is called variable definition (sometimes
called variable declaration). The syntax of variable
definition is: type name;
where, type is the type of data that a variable can store,
and name is the name assigned to the variable. Multiple
variables of the same type can be defined as:
type name1, name2, name3 ....; The data type of a variable is
selected from the list of data types supported by C++. 51
Cont…
Example:
• To store number without decimal point, we use integer data
type.
int num;
• Here, int is the keyword used to tell the compiler that the
variable with name num will store integer values. The C++
Course covers the types of variables in C++ and how to use
them effectively in your programs.

52
Initializing a Variable
A variable that is just defined may not contain some valid
value. We have to initialize it to some valid initial value. It is
done by using an assignment operator = as shown: type
name;

name = value;
Definition and initialization can also be done in a single step as
shown: type name = value;
where the value should be of the same type as variable.
Example:

int num = 100; The integer variable num is initialized with the
value 100. Values are generally the literals of the same type. 53
Accessing a Variable

The main objective of a variable is to store the data so that it


can be retrieved later. It can be done by simply using its
assigned name. Example

Output
a

54
Updating a Variable

The value stored in the variables can be changed any number


of times by simply assigning a new value using = assignment
operator. Example Output
24
888

55
Rules For Naming Variable
The names given to a variable are called identifiers. There are
some rules for creating these identifiers (names):

A name can only contain letters (A-Z or a-z), digits (0-9),


and underscores (_).

It should start with a letter or an underscore only.

It is case sensitive.

The name of the variable should not contain any whitespace


and special characters (i.e. #, $, %, *, etc).

We cannot used C++ keyword (e.g. float, double, class) as a


variable name. 56
How are variables used?
Variables are the names given to the memory location which
stores some value. These names can be used in any place
where the value it stores can be used.

For example, we assign values of the same type to variables.


But instead of these values, we can also use variables that store
these values. Output
10
10

57
Cont…
Addition of two integers can be done in C++ using +
operator as shown:
Output
30

We can do the above operation using the variables that store
these two values.

Output
30

58
Constant Variables
In C++, a constant variable is one whose value cannot be
changed after it is initialized. This is done using
the const keyword.

59
Scope of Variables
Scope of Variable is the region inside the program where the
variable can be referred to by using its name. Basically, it is the
part of the program where the variable exists. Proper
understanding of this concept requires the understanding of
other concepts such as functions, blocks, etc.

Memory Management of Variables: When we create or


declare a variable, a fixed-size memory block is assigned to the
variable, and its initial value is a garbage value. Initialization
assigns a meaningful value using the assignment operator.
Variables essentially manipulate specific memory locations, and
60
their stored data is accessed via their names.
Summary

61
C++ Data Types
Data types specify the type of data that a variable 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 as 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. For example,

62
Cont…
Output
10

Explanation: In the above code, we needed to store the value 10 in our program,
so we created a variable var. But before var, we have used the keyword ‘int‘. This
keyword is used to define the data types of integers.
63
Cont…
In C++, data types are classified into the following types:
S. No. Type Description Data Types

Built-in or primitive data int, float,


types that are used to store double, char,
1 Basic Data Types simple values. bool, void
array, pointer,
Data types derived from reference,
2 Derived Data Types basic types. function

Custom data types created class, struct,


User Defined Data by the programmer union, typedef,
3 Types according to their need. using 64
Primitive Data Types in C++
Program
1. Character Data Type (char)
 The character data type is used to store a single
character. The keyword used to define a character is char.
Its size is 1 byte and it stores characters enclosed in single
quotes (‘ ‘). It can generally store upto 256 characters
according to their ASCII codes.

Syntax:

char name;
where name is the identifier assigned to the variable.
65
Cont…
Example

Output
A

66
Cont…
2. Integer Data Type (int)
Integer data type denotes that the given variable can store
the integer numbers. The keyword used to define integers
is int. Its size is 4-bytes (for 64-bit) systems and can store
numbers for binary, octal, decimal and hexadecimal base
systems in the range from -2,147,483,648 to
2,147,483,647.

Syntax
int name;
where, name is the identifier assigned to the variable.
67
Cont…
Example Output
25
21

68
Cont…
3. Boolean Data Type (bool)
The boolean data type is used to store logical
values: true(1) or false(0). The keyword used to define a
boolean variable is bool. Its size is 1 byte.

Syntax
bool name;
where name is the identifier assigned to the variable.

69
Cont…
Example
Output
1

70
Cont…
4. Floating Point Data Type (float)
Floating-point data type is used to store numbers with
decimal points. The keyword used to define floating-point
numbers is float. Its size is 4 bytes (on 64-bit systems) and
can store values in the range from 1.2E-38 to 3.4e+38.

Syntax
float name;
where, name is the identifier assigned to the variable.

71
Cont…
Example Output
36.5

72
Cont…
5. Double Data Type (double)
The double data type is used to store decimal numbers with
higher precision. The keyword used to define double-precision
floating-point numbers is double. Its size is 8 bytes (on 64-bit
systems) and can store the values in the range from 1.7e-308
to 1.7e+308
Syntax
double name;
where, name is the identifier assigned to the variable.

73
Cont…
Example
Output
3.14159

74
Cont…
6. Void Data Type (void)
The void data type represents the absence of value. We
cannot create a variable of void type. It is used for pointer and
functions that do not return any value using the keyword void.

Syntax

void functionName();

75
Cont…
Example
Output
Hello, World!

76
Size of Data Types in C++

Earlier, we mentioned that the size of the data types is


according to the 64-bit systems. Does it mean that the size of
C++ data types is different for different computers?

Actually, it is partially true. The size of C++ data types can


vary across different systems, depending on the architecture of
the computer (e.g., 32-bit vs. 64-bit systems) and the compiler
being used. But if the architecture of the computer is same,
then the size across different computers remains same.

We can find the size of the data type using sizeof operator.
77
Cont…
Example Output
Size of int: 4 bytes
Size of char: 1 byte
Size of float: 4 bytes
Size of double: 8 bytes

78
Data Type Modifiers

Data type modifiers are the keywords used to change or


give extra meaning to already existing data types. It is added
to primitive data types as a prefix to modify their size or range
of data they can store. There are 4 type modifiers in
C++: short, long, signed and unsigned.
For Example,
Defining an int with long type modifier will change its size to 8
bytes:
int => 4 bytes
long int => 8 bytes
79
Expressions and Statements
in C++

80
Cont…
Statements: In C++, a statement controls the sequence of
execution, evaluates an expression, or does nothing (the null
statement). All C++ statements end with a semicolon.

Expressions: an expression is a computation which yields a


value. It can also be viewed as any statement that evaluates to
a value (returns a value).
 E.g. The statement 3+2; returns the value 5 and thus is an
expression

81
82

You might also like