0% found this document useful (0 votes)
4 views74 pages

Chapter 2

Chapter Two provides an introduction to programming with a focus on C++, including its environment setup, program structure, and essential components such as keywords, identifiers, data types, and variables. It explains the basic syntax and features of C++, emphasizing its object-oriented capabilities and various data types such as integers, floats, and characters. Additionally, the chapter covers the importance of comments and the role of literals in C++ programming.
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
0% found this document useful (0 votes)
4 views74 pages

Chapter 2

Chapter Two provides an introduction to programming with a focus on C++, including its environment setup, program structure, and essential components such as keywords, identifiers, data types, and variables. It explains the basic syntax and features of C++, emphasizing its object-oriented capabilities and various data types such as integers, floats, and characters. Additionally, the chapter covers the importance of comments and the role of literals in C++ programming.
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

CHAPTER TWO

BASICS OF PROGRAMMING
INTRODUCTION TO PROGRAMMING

Moyka Mosa
Outline

Introduction
C++ Environment Setup
C++ Program Structure
Parts of a program: Keywords, Identifiers, Inputs,
Outputs, Comments,
Data Types
Variables
Constants
2
Outline

 Operators
 Assignment Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Increment and Decrement Operators
 Bitwise Operators
 Conditional Operator
 Precedence of Operators

3
Introduction
C++ is one of the most popular and widely used
programming languages in the world.
It is a cross-platform language that can be used to
create high-performance applications.
It was developed by Bjarne Stroustrup at AT&T
Bell Laboratories in the 1979.
C++ is an extension of the C Programming
language.

4
Cont’d…
C++ builds upon the C language by introducing
object-oriented programming features.
In addition, C++ includes features like
namespaces, templates, and a comprehensive
standard library.
C++ is a case sensitive language.
It is used in the development of a wide range of
applications, including games, operating systems,
embedded systems, scientific computing, and
many others. 5
C++ Environment Setup
Environment Setup refers to installing and
configuring the software needed to code in C++.
To begin programming in C++, two essential tools
are required:
Text editor
Compiler
A text editor is a software used for writing code
in c++.
Example: Notepad, Notepad++, vim, etc.
6
Cont’d…
A C++ compiler is a tool that converts your source
code into machine-executable code.
One of the most commonly used and freely
available compilers is the GNU C/C++ compiler.
But an Integrated Development Environment is
used to make C++ programming easier and more
efficient.
An IDE is a software suite that combines multiple
development tools required to write and test
software. 7
Cont’d…
It presents them within a single, human-readable
graphical user interface (GUI).
It provides a single platform that includes:
A code editor
A compiler or interpreter
Debugging tools
Features like syntax highlighting, auto-
completion, and error detection
8
Cont’d…
Popular IDE's include Code::Blocks, Eclipse, and
Visual Studio, Dev-C++, and others.
Some of the most popular C++ compilers
include Microsoft Visual C++ (part of Visual Studio),
the GNU Compiler Collection (GCC) with g++, and
Clang/LLVM.

9
C++ Program Structure
The basic structure of a C++ program consists of
the following parts:
Header File Inclusion
Namespace Declaration
main() Function
Program Logic
Return Statement

10
Cont’d…
Header File Inclusion
Includes built-in libraries.
Example: <iostream> is used for input/output
(cin, cout).
You can include multiple headers: #include
<cmath>, #include <string> and others.

11
Cont’d…
Namespace Declaration (using namespace
std;)
std stands for standard.
Belongs to the Standard Library.
It contains all the features of the C++ Standard
Library
Avoids the need to write std::cout, std::cin, etc.

12
Cont’d…
main() Function
The main() function is the entry point of every C+
+ program.
It’s where the program starts execution.
Returns an integer to the operating system.
Program logic: Written inside main().
E.g.: cout << “Welcome to C++!”;
return 0;: Ends the program successfully.
13
Cont’d…

Example: A simple C++ program

14
C++ Tokens
A token is the smallest unit in a C++ program that
the compiler recognizes.
Tokens are the building blocks of C++ code.
Common types of tokens in C++ include:
Keywords, Identifiers, Constants, Operators,
Special Symbols.
A program is constructed using a combination of
these tokens.

15
Keywords (Reserved words)
Keywords are predefined words that have special
meanings to the compiler.
It is always written in lower cases.
Keywords are reserved terms in the C++
programming language that have preset
meanings.
For example, int money;
int is a keyword that indicates money is a variable
of type integer.
16
Cont’d…

17
C++ Identifier
C++ identifiers are unique names assigned to
identify variables, functions, classes, arrays, and
other user-defined items in a program.
Identifiers can be short names (like x and y) or
more descriptive names (age, sum, totalVolume).
It is recommended to use descriptive names in
order to create understandable and maintainable
code.
Example: int minutesPerHour = 60; //Good
int m = 60; //Not easy to understand
18
Cont’d…

Rules for Naming Identifiers


It must begin with a letter uppercase
or lowercase or an underscore (_) but cannot
start with a digit.
After the first character, use letters, digits digits (0-
9), or underscores.
It cannot contain whitespace or special characters
such as !, #, %, etc.
Identifiers are case-sensitive (Myvar ≠ myvar). 19
Cont’d…

Rules for Naming Identifiers…


It has no limit on name length (int x or int
thisIsAVeryLongVariableNameThatStillWorksInCpp
).
It cannot be a keyword (reserved word), such as
int, bool, return, while, etc.
Use meaningful names that reflect the purpose of
the identifier (e.g, totalCount, calculateArea).
Use camelCase or snake_case for readability. 20
Cont’d…
CamelCase: Words are joined together without
spaces.
Each new word starts with a capital letter (except
the first one).
Example: calculateAverageScore, firstName
Snake_case: Words are written in lowercase and
separated by underscores.
Example: calculate_average_score, first_name
21
Variable
In C++, variable is a name given to a memory
location.
A variable is a named storage location in
memory.
It is the basic unit of storage in a program.
Creating and naming a variable is called variable
definition or declaration.
The syntax of variable definition is: type name;
Where, type is the type of data that a variable can
22
Cont’d…
name is the name assigned to the variable.
Example: int num;
int is the keyword used to tell the compiler that
the variable with name num will store integer
values.
Multiple variables of the same type can be defined
as: type name1, name2, name3 ...;
To declare multiple variables of the same type,
separate them with commas.
23
Cont’d…
A variable must be declared before use in C++.
A variable that is just defined or declared might
not contain a valid value.
So, we need to initialize it with a valid initial value.
Variable initialization assigns an initial value to a
variable at the time of declaration.
It is performed using an assignment operator(=).
type name;
name = value; 24
Cont’d…
Example: int num;
num=100;
Variable 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;
25
Cont’d…
In C++, a variable is like a container that holds
data.
As the program runs, the value stored in that
variable can be updated or changed.
Example:
int number = 5; // Initially, number is 5
number = 10; // Now, number is changed to
10

26
Literals
Literals are the actual values that are directly
written in the code to represent specific data.
They are data used for representing fixed values.
In C++, literals are often used to assign initial
values to variables.
Example: int x = 10; //10 is literal
A literal can be used as an operand in an
expression.
Example: int result = 5 + 3; // 3 and 5 are literals
27
Cont’d…
Literals can also be passed as arguments to
functions.
Example: printValue(25); // The literal 25 is
passed as an argument to the function
C++ supports several types of literals based on the
kind of data they represent.
Types of Literals in C++:
1. Integer Literals: represent whole numbers and
can be expressed in decimal, octal, hexadecimal, or
binary.
28
Cont’d…
Example: 10, 012, 0xA, 0b1010
2. Floating-Point Literals: represent numbers with
decimal points or in exponential (scientific)
notation.
Example: 3.14, 6.022e23
3. Character Literals: represent individual
characters and are enclosed in single quotes.
Certain special characters can be represented
using escape sequences.
Examples: 'A', '\n', '\t' 29
Cont’d…
4. String Literals: represent sequence of characters
enclosed in double quotes.
Examples: "Hello, World!", "This is a string".
5. Boolean Literals: Used to represent truth values:
true and false.
Examples: True, False.

30
C++ Comments
Comments are non-executable lines in the code.
They serve as notes or explanations to make the
code more readable for developers.
They are used to explain the code, improve
readability, and help with debugging.
The compiler ignores comments.
C++ supports two types of comments:
1. Single-line comments
2. Multi-line comments 31
Cont’d…
1. Single-line comments
In C++, a single line comment starts with a double
forward slash (//) symbol.
It applies comments to a single line only.
Anything written after // until the end of the first
line is a single-line comment.
The compiler ignores any text after // and it will
not be executed.
Example: int a; // declaring a variable 32
Cont’d…
2. Multi-line comments
Start with /* and end with */.
Any text in between these symbols is treated as a
comment only.
Any text between /* and */ will be ignored by the
compiler.
A multi-line comment can occupy many lines of
code
33
Cont’d…
Example:
/* The code below will print the words Hello
World!
to the screen, and it is amazing */
cout << "Hello World!";
Single-line comments are generally used for short
lines of comments.
Multi-line comments are generally used for longer
lines of comments. 34
C++ Data Types
Data types define the type of data a variable can
hold.
C++ is a strongly typed language — every
variable must have a type.
In C++, data types are generally categorized into
the following main categories:
1. Primitive (Fundamental) Data Types
2. Derived Data Types
3. User-Defined Data Types
35
Cont’d…
.
C++ Data Types

Primitive/ Derived Data User Defined


Built-in Type Data Type

36
Cont’d…
1. Primitive (Fundamental) Data Types
Are the most basic types of data built into a
programming language.
They are directly supported by the compiler and
represent basic values.
They serve as the foundation for all other data
types.
Common primitive data types are: integer types,
floating-point types, character types, and 37
Cont’d…
A. Integer Data Type (int)
The keyword used to define integers is int.
Used to store whole numbers, which can be
positive, negative, or zero. For example: -3, 0,
100, 2456.
It is commonly used for counting, indexing, or any
situation where whole numbers are required.
It does not store decimal or fractional values.
Its size is usually 4 bytes (32 bits).
It can store values from -2,147,483,648 to 38
Cont’d…
B. Floating Point Data Type (float)
The keyword used to define floating-point
numbers is float.
Used to store floating-point numbers (decimals
and exponentials).
It is typically used when storing values that
require fractions, such as measurements or
scientific data.
Its size is 4 bytes (32 bits).
39
Cont’d…
C. Double Data Type (double)
The keyword used to define double-precision
floating-point numbers is double.
It is used to store decimal numbers with higher
precision.
The size of double is 8 bytes (64 bits).
It has a precision of 15 to 17 decimal digits.
Hence, double has two times the precision
of float. 40
Cont’d…
D. Character Data Type (char)
The keyword used to define a character is char.
It is used to store a single character.
Its size is 1 byte.
It stores characters enclosed in single quotes (‘ ‘).
char can also be signed or unsigned, affecting
the range of values:
Signed: -128 to 127
Unsigned: 0 to 255 41
Cont’d…
D. Boolean Data Type (bool)
The keyword used to define a boolean variable
is bool.
The bool data type has one of two possible
values: true or false.
Its size is 1 byte.

42
Cont’d…
Type modifiers
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.
C++ allows the char, int, and double data types to
have modifiers preceding them.
There are four type modifiers in C++: signed,
43
Cont’d…
I. signed Modifier
Signed variables can hold both positive and
negative integers including zero.
It can be used only with int and char data types.
Example: signed int x; signed char my_char = 'A’;
The range of signed char is usually -128 to 127 (on
systems where a byte is 8 bits).
By default, integers are signed.
Hence instead of signed int, we can directly 44
Cont’d…
II. unsigned Modifier
The unsigned variables can hold only non-
negative integer values.
It makes the data type non-negative, meaning it
can only store zero or positive values.
It can only be used with int and char data types.
unsigned int can store a range of values
from 0 to 4,294,967,295.
45
Cont’d…
unsigned char can store values from 0 to 255
(instead of -128 to 127 for a signed char).
In C++, the unsigned modifier can be combined
with other type modifiers to alter the size and
range of integer types.
These type modifiers include short, long, and long
long.

46
Cont’d…
III. short Modifier
short is a modifier used with the integer (int)
type.
It reduces the storage size compared to a normal
int.
Mainly used when memory saving is important
and large numbers are not needed.
It stores whole numbers but occupies 2 bytes (16
bits). 47
Cont’d…
IV. long Modifier
long is a type modifier used to increase the
storage size of an integer type.
It allows storing larger whole numbers than the
regular int.
The long int is typically 4 bytes (32 bits) on most
systems.
However, it can be 8 bytes (64 bits) on some
systems, especially 64-bit ones.
It can be used with integer and double data types.48
Cont’d…
long is equivalent to long int.
It can also be used twice on integers. long long
int.
long long guarantees 8 bytes (64 bits) and is used
for larger integer values.
The long double type is used for floating-point
numbers and provides extended precision.
long double usually occupies 16 bytes.
The modifiers signed and unsigned can also be
used as prefix to long or short modifiers. 49
Cont’d…
Type Typical size Range
int 4 bytes -2,147,483,648 to
+2,147,483,647
char 1 byte -128 to 127
float 4 bytes 1.17549e-38 to 3.40282e+38
double 8 bytes ±1.7E-308 to ±1.7E+308.
signed int 4 bytes -2,147,483,648 to
+2,147,483,647
short int 2 bytes -32,768 to 32,767
unsigned int 4bytes 0 to 4,294,967,295 50
Cont’d…
signed short int 2 bytes -32,768 to 32,767
long int 4bytes -2,147,483,648 to
2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4byte 0 to 4,294,967,295
long long int 8 bytes -(2^63) to (2^63)-1
unsigned long 8 bytes 0 to
long int 18,446,744,073,709,551,61
5 51
Cont’d…
A C++ program that checks and displays the size
of fundamental data types:

52
Cont’d…
2. Derived Data Types
Derived data types are data types that are created
by combining primitive or built-in data types.
For example: arrays, pointers, function, and
references.
3. User Defined Data Types
Types created by programmers to model specific
problems.
C++ supports 5 user-defined data types: Class,
Structure, Union, Enumeration and Typedef. 53
Cont’d…
Types affect several key aspects of program
behavior and system resources.
I. Memory Usage: Different data types require
different amounts of memory. For instance, int: 4
bytes, char: 1 byte.
II. Performance: Operations on certain data types
are faster. For example, Integer arithmetic is faster
than floating-point.
III. Valid Operations: Each data type supports
specific operations. For example, booleans can’t 54
Constants
Constants are variables whose values cannot be
changed once initialized.
There are two methods to define constants in C+
+:
1. #define preprocessor directive method
2. 'const' keyword method
1. 'const' Keyword Method:
It ensures that the value remains immutable
throughout the program's execution.
Example: const int MAX_VALUE = 100;
55
Cont’d…
2. #define Preprocessor Directive Method
It is used to define constants before the
compilation of the code starts.
It tells the preprocessor to replace a name with a
value or text before compilation.
It acts as a simple text substitution tool.
Syntax: #define CONSTANT_NAME constant_value
Example: #define PI 3.14159
56
Cont’d…
Example: Same output with different methods

57
C++ Operators
Symbols that take one or more arguments
(operands) and operate on them to produce a
result.
Operators are symbols that perform operations
on variables and values.
Types of operators in C++ are:
Arithmetic Operators
Relational (Comparison) Operators
Logical Operators
Assignment Operators
Increment/Decrement Operators 58
Arithmetic Operators
Used to perform arithmetic operations on the
operands. Example: int a=5, b=2;
Operato Name Description Operation Result
r s
+ Addition Adds two values a+b 7
- Subtraction Subtracts second from first a - b 3
Multiplicatio
* Multiplies two numbers a*b 10
n
/ Division Divides first by second a/b 2
% Modulus Returns remainder a%b 1
59
Cont’d…
All arithmetic operators except modulo (%) allow
mixed integer/real operands.
For example: 9/2 // gives 4, not 4.5
-9/2 // gives -4, not -4.5
4/6 // evaluates to 0
10.5%3 // Compiler error
5+3.14 // converted to double +
double
If both operands are integers, then the result will
be an integer.
If one or both operands are real then the result 60
Relational Operators
Relational operators compare two values or
expressions and return a true or false result.
All C++ relational operators are binary operators.
They require two operands to perform a
comparison.
Relational operators enable:
Decision-making (through conditional statements
like if-else)
Loop control (determining when loops should
continue or terminate)
Conditional checks (evaluating expressions to guide61
Cont’d…
Example: int a=5, b=2;
Operator Description Example Result
== Equal to a == b false
!= Not equal to a != b true
> Greater than a>b true
< Less than a<b false
>= Greater than or a >= b true
equal
<= Less than or equal a <= b false 62
Logical Operators
Logical operators combine multiple conditions
and return a true or false result.
They are used in decision-making and looping
statements to evaluate multiple conditions.
These operators are essential for controlling the
flow of a program based on conditions.
It returns either 0 or 1 depending upon whether
the expression results in true or false.
If the result is true, it returns 1 else returns 0.
There are three primary logical operators in C++.
63
Cont’d…
Operato Name Description Example Result
r
&& Logical AND Returns true if (a > 4 && b > 1) true
both statements
are true
|| Logical OR Returns true if (a>2||b<2) True
one of the
statements is
true
! Logical NOT Reverse the !(a > b) false
64
Cont’d…
Additionally, C++ provides alternative keywords:
No Operator Keyword
1. && and
2. || or
3. ! not
The logical NOT operator ( ! ) is a unary operator
that is used to negate the value of a condition.
In C++, the logical AND (&&) and logical OR (||)
operators are binary operators. 65
Assignment Operators
Are used to assign values to variables.
Operator Meaning Example Equivalen
t
= Assign value a = 10
+= Add and assign a+= 5 a=a+5
-= Subtract and assign a-= 3 a=a-3
*= Multiply and assign a*= 2 a= a * 2
/= Divide and assign a/= 2 a= a / 2
%= Modulus and assign a%= 2 a= a % 266
Increment/Decrement Operators
The increment operator (++) adds 1 to its
operand.
The decrement operator (--) subtracts 1 from its
operand.
x = x+1; is the same as x++;
x = x-1; is the same as x--;
Both the increment and decrement operators can
either precede (prefix) or follow (postfix) the
operand.
67
Cont’d…
The postfix operator says that first use the value
and then increment it.
This means the value is first used up for the
operation then the value is updated by 1.
Post-increment (x++) means "use then
increment".
Example: int x = 5;
int temp = x++;
x becomes 6 (after increment)
temp gets 5 (original value before increment)
68
Cont’d…
The prefix operator says that first increment the
value then use it.
This means the value is increased by 1 for the
operation then the value is used by the variable.
Example: int x = 5;
int temp = ++x;
x becomes 6 (after increment)
temp gets 6 (the new value after increment)
The -- operator works in a similar way to the +
+ operator except -- decreases the value by 1.
69
Bitwise Operators
Bitwise operators perform operations on
the binary representations of integers.
These operations include testing, setting, or
shifting the actual bits.
They are used for low-level manipulation of data,
memory optimization, and certain algorithms.

70
Cont’d…
Operator Name Description Example (a = 5, b = 3)

a & b → 1 (0101 & 0011 =


& AND Sets bit to 1 if both bits are 1
0001)

a | b → 7 (0101 | 0011 =
| OR Sets bit to 1 if at least one bit is 1
0111)

a ^ b → 6 (0101 ^ 0011 =
^ XOR Sets bit to 1 if bits are different
0110)

NOT (Compl ~a → -6 (in 4-bit: ~0101 =


~ Flips all bits (unary operator)
ement) 1010)

a << 1 → 10 (0101 << 1 =


<< Left Shift Shifts bits left, filling with 0
1010)

Shifts bits right (signed/unsigned behavior a >> 1 → 2 (0101 >> 1 =


>> Right Shift
varies) 0010) 71
Conditional Operator (?:)
It is also called the ternary operator because it
works with three operands.
It takes 3 operands (condition, expression1 and
expression2).
Syntax: condition ? expression1 : expression2;
Here, condition is evaluated and
if condition is true, expression1 is executed.
if condition is false, expression2 is executed.
It is a short and concise way to write an if-else
statement.
72
Cont’d…
Example: C++ Ternary Operator
#include <iostream>
using namespace std;
int main()
{
double marks;
cout<<"Enter Grade from (0=100)";
cin>>marks;
string result = (marks>=50)? "PASS":"FAIL";
cout << "You " << result << " the exam.";
return 0;
} 73
Cont’d…
Reading Assignment: Operator precedence in C+
+

74

You might also like