REVIEWER: AC1 COMPUTER PROGRAMMING Data Types
MODULE 1: INTRODUCTION TO COMPUTER
Variables
PROGRAMMING
Keywords
Logical and Arithmetical Operators
Computer programming is a systematic process of creating
If else conditions
computer programs to solve specific computing problems. It
Loops
involves analysis, coding, algorithm generation, and
Numbers, Characters and Arrays
verification. Selecting the right programming language can be
Functions
challenging, but it's essential for effective problem-solving.
Input and Output Operations
BASIC OF PROGRAMMING
COMPUTER PROGRAM
English is the most popular and well-known Human
A sequence of statements intended to
Language. The English language hasits own set of
accomplish/perform a certain task
grammar rules, which has to be followed to write in the
It is a set of instructions for a computer to follow
English languagecorrectly.
EXAMPLE of Computer Program:
Likewise, any other Human Languages (German,
A computer program that computes the numbers
Spanish, Russian, etc.) are made of several elements like
using a basic arithmetic operator
nouns, adjective, adverbs, propositions, and
A program that accepts input from the user then
conjunctions, etc. So, just like English, Spanish or other
print the summary of information
human languages, programming languages are also
made of different elements. PROGRAMMING – Process of planning and creating a
Just like human languages, programming languages program.
also follow grammar called syntax. There are certain
MACHINE LANGUAGE – The language that the computer
basic program code elements which are common for all
can directly understand.
the programming languages.
EXAMPLE of Machine Language
Most important basic elements for programming languages
are:
Programming Environment
In programming, programmer writes a series of
program statements which carry out task the program
has to perform.
ASSEMBLY LANGUAGE
The symbolic form of machine language that is easier
for people to read (for example ADD AX DX)
This makes use of instructions in mnemonic form
A program that translates assembly languages DIFFERENT PROGRAMMING LANGUAGES
instruction into language is called an assembler
HIGH-LEVEL LANGUAGES COMPILER – A program that translates a program written in
Most modern programming languages are designed to a high-level language into a low-level language (such as
be relatively easy. These are known as high-level machine language) before executing the statements.
languages.
INTERPRETER – Act as a compiler, but it translates one (1)
Each high-level language has its syntax, or rules of the
program statement at a time, this executes the statement as
languages (For example, the verb print or write is used
soon as it is translated.
to produce an output)
SYNTAX ERROR – In the process of translation, an invalid
program statement might be encountered known as a syntax
error. (for example, the mathematical expression 3+3 = 6 is
written incorrectly as 3#3=6.
DEBUGGING – The process/act of locating and repairing
the errors of the program is called debugging.
LOGICAL ERROR – Apart from a syntax error, a logical
ALGORITHM DESIGN
error might be encountered as well. Logical Error (Semantic
Error) occurs when the syntax of the program is correct but the
After analyzing the problem, the next step is to design an
expected output is not.
algorithm to solve it. If the problem is broken down into
subproblems, there should be an algorithm for each sub-
PROGRAMMING CYCLE
problem. You should check the algorithm for the correctness
ALGORITHM
and integrate the solution to sub-problems.
Step by step problem-solving process in which a
CODING
solution is arrived at in a finite amount of time.
The next step is to convert the algorithm into a programming
The problem-solving process in the programming
language, usually a high-level language. A text editor or IDE
environment involves the following steps:
(Integrated Development Environment) is used to write a
program to make sure that the program follows the language’s
1. Problem Analysis: Analyze the problem and outline
syntax. To ensure the syntax is correct, the code is run through
the problem and its solution requirements
a compiler. If error messages are encountered, the errors must
2. Analysis Algorithm: Design an algorithm to solve a
be identified and resolved (debugging). When the program is
problem
free from any syntax error, the compiler generates the machine
code.
3. Coding: implement the algorithm in a programming
language
Example of Algorithm
4. Execution: Verify that the algorithm works
The following algorithm is designed to know the firstname, Indentation is used to indicate branches and loops of
lastname, and middlename. It is supposed to concatenate the instructions.
value of the fields to display the fullname. The concatenation
Example:
of fields is : fullname = firstname + “ ” + middlename + “ ” +
lastname The following pseudocode is design to know the firstname,
lastname, and middlename. It is supposed to concatenate the
1. GET the firstname, lastname, and middlename
value of the fields to display the fullname. The concatenation
2. Concatenate fields: fullname = firstname + “ ” + of fields is : fullname = firstname + “ ” + middlename + “ ” +
middlename + “ ” + lastname lastname
3. Display fullname READ firstname
PSEUDOCODE READ lastname
Method of describing computer algorithms using a READ middlename
combination of natural language and programming language.
SET fullname to firstname + “ ” + middlename + “ ” +
Here are some rules that are frequently followed when writing lastname
pseudocode
Print fullname
Symbols are used for operations
FLOWCHART
Arithmetic Operations (+, - ,* ,/ )
Visual representation of an algorithm
Assignment (=)
It contains symbols/shapes describing how an
Comparison (=, <,>, <=,>=) algorithm or program operates.
Logical (and, or) Each command/instruction is placed in an appropriate
shape, and arrows are used to direct program flow.
Certain keywords can be used as a command, such as
PRINT, WRITE, READ, SET, etc.
from. In this tutorial, we will use an IDE.
VARIABLES – are containers for storing data values.
It is the basic unit of storage in a program.
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.
MODULE 2: INTRODUCTION TO C++
C++ – is a general-purpose programming language that was
developed as an enhancement of the C language to include
object-oriented paradigm.
C++ Environment
To start using C++, you need two things:
How Declare Variable?
A text editor, like Notepad, to write C++ code
Syntax: type variableName = value;
A compiler, like GCC, to translate the C++ code into a
Example:
language that the computer will understand
There are many text editors and compilers to choose
int – stores integers (whole numbers), without decimals, such
as 123 or -123
double – stores floating point numbers, with decimals, such as
19.99 or -19.99
DIFFERENCE BETWEEN VARIABLE DECLARATION
LOCAL VARIABLES
AND DEFINITION
A variable defined within a block or method or
The variable declaration refers to the part where a variable is
constructor is called a local variable.
first declared or introduced before its first use. A variable
definition is a part where the variable is assigned a memory These variables are created when entered into the block
location and a value. Most of the time, variable declaration and or the function is called and destroyed after exiting from
definition are done together. the block or when the call returns from the function.
TYPES OF VARIABLES The scope of these variables exists only within the block
in which the variable is declared. i.e. we can access this
There are three types of variables based on the scope of
variable only within that block.
variables in C++
Initialization of Local Variable is Mandatory.
Local Variables
INSTANCE VARIABLE
Instance Variables
1s are non-static variables and are declared in a class
Static Variables
outside any method, constructor, or block.
As instance variables are declared in a class, these message and it won’t halt the program. The compiler
variables are created when an object of the class is will replace the object name with the class name
created and destroyed when the object is destroyed. automatically.
Unlike local variables, we may use access specifiers for If we access the static variable without the class name,
instance variables. If we do not specify any access the Compiler will automatically append the class name.
specifier then the default access specifier will be used.
DATA TYPES – The data type specifies the size and type of
Initialization of Instance Variable is not Mandatory. information the variable will store
STATIC VARIABLE
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
NUMBER TYPES
any method constructor or block.
Unlike instance variables, we can only have one copy of
Use int when you need to store a whole number without
decimals, like 35 or 1000, and float or double when you need a
a static variable per class irrespective of how many
floating point number (with decimals), like 9.99 or 3.14515.
objects we create.
Static variables are created at the start of program
BOOLEAN TYPES
execution and destroyed automatically when execution
A boolean data type is declared with the bool keyword and can
ends.
only take the values true or false.
Initialization of Static Variable is not Mandatory. Its
CHARACTER TYPES
default value is 0
The char data type is used to store a single character. The
If we access the static variable like the Instance variable
character must be surrounded by single quotes, like 'A'
(through an object), the compiler will show the warning
or 'c'.
Alternatively, you can use ASCII values to display
certain characters.
STRING TYPES
The string type is used to store a sequence of characters BINARY OPERATORS – These operators operate or work
(text). This is not a built-in type, but it behaves like one with two operands.
in its most basic usage. String values must be
surrounded by double quotes:
To use strings, you must include an additional header
file in the source code, the <string> library
OPERATORS – is a symbol that operates on a value to
perform specific mathematical or logical computations. They
form the foundation of any programming language. In C++,
we have built-in operators to provide the required
functionality.
ARITHMETIC OPERATORS
RELATIONAL OPERATORS – These operators are used for
Arithmetic operators are used to perform common
the comparison of the values of two operands.
mathematical operations.
used to perform arithmetic or mathematical operations
on the operands.
Arithmetic Operators can be classified into 2 Types: Unary
Operators and Binary Operators.
UNARY OPERATORS – These operators operate or work
with a single operand.
LOGICAL OPERATORS – are used to combine two or more
conditions or constraints or to complement the evaluation of
the original condition in consideration.
BITWISE OPERATORS – These operators are used to
ASSIGNMENT OPERATORS – Used to assign value to a
perform bit-level operations on the operands. The operators
variable. The left side operand of the assignment operator is a
are first converted to bit-level and then the calculation is
variable and the right side operand of the assignment operator
performed on the operands. Mathematical operations such as
is a value. The value on the right side must be of the same data
addition, subtraction, multiplication, etc. can be performed at
type as the variable on the left side otherwise the compiler will
the bit level for faster processing.
raise an error.
PRE-PROCESSORS – are programs that process the source
code before compilation.
TERNARY OR CONDITIONAL OPERATORS (?:) –
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,
PRE-PROCESSING IN C++ – means to execute/process the
then Expression3 gets evaluated and is used as the answer for
program file before the execution of the main program.
the expression.
DIRECTIVES – provide preprocessor directives that tell the
compiler to preprocess the source code before compiling.
All the statements starting with the # (hash) symbol are known
as preprocessor directives in C++. Now, like a coach instructs
his/her students to perform certain tasks to improve/her
performance, the directives instruct the preprocessor to Conditional Compilation – a type of directives that
perform certain tasks to improve the program's helps to compile a specific portion of the program or to
performance/capabilities. skip the compilation of some specific part of the
program based on some conditions.
A # (hash) symbol (All the preprocessor directives in C++ start
with the # (hash) symbol). Other directives – Apart from the above directives,
there are two more directives that are not commonly
A pre-processor instruction after the # (hash) symbol. For
used. These are:
example, #include, #define, #ifdef, #elif, #error, #pragma etc.
#undef Directive – used to undefine an existing
Arguments are based on the type of the directive. For example,
Macro. This directive work as: #undef LIMIT.
<iostream> is argument for #include, PI 3.14 are arguments for
#define directive. #pragma Directive – this directive is a special
purpose directive and is used to turn on and off some
Example: #include<iostream>, #define PI 3.14, #ifdef PI etc.
features.
MODULE 3: INPUT AND OUTPUT AND FUNCTIONS
IN C++ PROGRAMMING
STREAMS IN C++
In C++, a stream is a sequence of characters that represents an
input or output source. Streams are used to perform input and
output operations in C++ programs. The two main types of
There are 4 Main Types of Preprocessor Directives: streams are:
Macros – In C/C++, Macros are pieces of code in a Input Stream (istream): This stream is used for reading
program that is given some name. data from a source, such as the keyboard or a file. The
primary input stream in C++ is associated with the cin
File Inclusion – This type of preprocessor directive tells
object.
the complier to include a file in the source code program.
Output Stream (ostream): This stream is used for writing
data to a destination, such as the console or a file. The operations.
primary output stream in C++ is associated with the
4. fstream (Combined Input/Output File Stream) Class:
cout object.
The fstream class combines both input and output
OTHER STREAMS
operations. It allows you to open a file for both reading
So far, we have been using the iostream standard library, which and writing.
provides cin and cout methods for reading from standard
OPENING FILES WITH SPECIFIC MODES (IOS::IN,
input and writing to standard output respectively.
IOS::OUT, IOS::APP, ETC.):
In C++, the fstream library provides facilities for file-based
When opening files, you can specify different modes using
input and output operations. The fstream library is an
flags like ios::in (input), ios::out (output), ios::app (append), and
extension of the iostream library and includes classes like
more.
ifstream (input file stream) and ofstream (output file stream) to
work with files.
1. fstream Class:
The fstream class is a combination of both ifstream and
ofstream. It allows you to perform both input and
output operations on files.
2. ifstream (Input File Stream) Class:
The ifstream class is used for reading data from a file.
You can use it to open a file for reading and perform
input operations.
3. ofstream (Output File Stream) Class:
The ofstream class is used for writing data to a file. You
can use it to open a file for writing and perform output
INPUT FUNCTIONS BASIC STRUCTURE OF A C++ PROGRAM
Input functions in C++ are used to receive data from the user A basic C++ program follows a structure that typically
during program execution. The most common input function includes:
is cin, which is associated with the standard input stream. It is
Header Files: These are included at the beginning of the
used to read data from the keyboard or another input source.
program and provide declarations and definitions
needed for the program. Commonly used header files
include <iostream> for input and output operations.
Main Function (main): Every C++ program must have
a main function. It serves as the entry point of the
program, and execution starts from here.
OUTPUT FUNCTIONS Statements and Expressions: These are the actual
instructions that the program will execute. They
Output functions in C++ are used to display information to
perform actions, make decisions, and control the flow of
the user during program execution. The primary output
the program.
function is cout, which is associated with the standard output
stream. It is used to print data to the console or another output Comments: These are used to add explanatory notes to
destination. the code. They are ignored by the compiler.
FUNCTIONS USE IN BASIC INPUT/OUTPUT Format String Example (using printf):
STATEMENT IN C++
#include <cstdio>
Functions in C++ are blocks of code that perform a specific
int main() {
task. In the context of basic input/output statements, functions
can be used to encapsulate repetitive or complex operations. int intValue = 42;
double doubleValue = 3.14159;
char charValue = 'A';
// Using printf with format string
printf("Integer: %d, Double: %.2f, Character: %c\n", intValue,
doubleValue,
charValue);
MODULE 4: Format Strings and Escape Sequence, Control return 0;
Structures, Function andArrays
}
FORMAT STRINGS AND ESCAPE SEQUENCES
In this example, the format string is "Integer: %d, Double: %.2f,
In C++, a format string is a string that contains placeholders Character: %c\n". Here:
that will be replaced by the values of variables during runtime.
%d is a placeholder for an integer.
Format strings are commonly used with functions like printf
from the C Standard Library or with stream manipulators in
%.2f is a placeholder for a floating-point number with two
the context of C++ I/O streams (cout, cin). Escape sequences,
decimal places.
on the other hand, are special characters in a string that
%c is a placeholder for a character.
represent non-printable or special characters.
\n is an escape sequence representing a newline character.
Escape Sequences Example: Many times in our code, we will need that a particular
piece of code should only execute if a specific condition
#include <iostream>
gets fulfilled. In C++, along with Conditional Control
int main() { Structures, we also have the Iteration or Loop Control
Structure.
// Using escape sequences in a string
TYPES OF CONTROL STRUCTURE IN C++
std::cout << "This is a line of text.\n";
There are three types of Control Structures in C++, And all the
std::cout << "This string contains a tab character\tand
program processes we write can only be implemented with
continues after the tab.\n";
these three control structures
return 0;
SEQUENCE STRUCTURE
}
This is the most simple and basic form of a control structure. It
In this example: is simply the plain logic we write; it only has simple linear
instructions, no decision making, and no loop. The programs
\n is an escape sequence representing a newline character.
we all wrote at the start of our programming journey were this
\t is an escape sequence representing a tab character. control structure only. It executes linearly line by line in a
straight line manner.
Both format strings and escape sequences are essential in string
manipulation and formatting in C++ applications. Format Let's understand the program flow and how it happened.
strings provide a way to control the layout and appearance of
Firstly, num1 and num2 were declared and initialized.
output, while escape sequences allow you to include special
characters in your strings, such as newline or tab characters. Then, the sum variable was declared and was assigned
the numerical sum of num1 and num2.
CONTROL STRUCTURE IN C++
We are then printing the sum.
The work of control structures is to give flow and logic
to a program. There are three types of basic control We can see that our program came one way, in a straight-line
structures in C++. manner, with no bending, no reverse, simply a straight flow.
This is simply what Sequence Control Structures are. Here,
SELECTION STRUCTURE We are first asking the user to enter their age and then
ask if they have a driving license
Sometimes in our program, we will need to write certain
condition checks that this part of code should only execute if a Then we are checking the condition using an if-else
particular condition meets or another part of code should run. control statement, and if it satisfies, then executing the
first block of code, else executing the other block of the
For example: The example we took at the start is that we have
code.
to write a program that will validate if a user is eligible to drive
or not based on two conditions: A block means a group of statements enclosed in curly
brackets {....}, and those specific statements are part of
if the age is equal to or above 18
that specific block.
if the user has their driving license
In C++, we have two types of Selection Control statements:
Let's understand it with the help of a program
If else statements
Switch case statements
We will be understanding in-depth about each of these in the
coming section.
LOOP STRUCTURE
Whenever in our program we see that a certain piece of code is
being repeated repeatedly, then we can enclose that in a loop
structure and provide the condition that this code should
execute these specific number of times. Loops in C++ are
essential for repetitive or iterative tasks, where you want to
execute a block of code multiple times without writing the
same code over and over.
We have three types of Loops in C++: The if –else structure / else statement
While Loop Use the else statement to specify a block of code to be executed
if the condition is false.
Do While Loop
For Loop
Now you know the different types of Control Structures, let us
know see the different ways on how to use this.
CONDITIONAL STRUCTURES
The If Structure
Use the if statement to specify a block of C++ code to be
Else –If Statement
executed if a condition is true
else the else if statement to specify a new condition if the first
condition is false.
Output: x is greater than y
In the example above we use two variables, x and y, to test
whether x is greater than y (using the > operator). As x is 20, and
y is 18, and we know that 20 is greater than 18, we print to the
screen that "x is greater than y".
Short Hand If...Else (Ternary Operator) specified condition is true:
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to
replace multiple lines of code with a single line. It is often used
to replace simple if else statements:
Do While Loop
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.
THE ITERATION STRUCTURE
Iteration statements cause statements (or compound
statements) to be executed zero or more times, subject to some
loop-termination criteria. When these statements are
compound statements, they are executed in order, except when
either the break statement or the continue statement is
encountered. C++ provides four iteration statements — while,
do, for, and range-based for. Each of these iterates until its
termination expression evaluates to zero (false), or until loop
termination is forced with a break statement. For Loop
The While Loop When you know exactly how many times you want to loop
through a block of code, use the for loop instead of a while loop:
The while loop loops through a block of code as long as a
Statement 1 is executed (one time) before the execution of the Continue Statement
code block.
The continue statement breaks one iteration (in the loop), if a
Statement 2 defines the condition for executing the code block. specified condition occurs, and continues with the next
iteration in the loop.
Statement 3 is executed (every time) after the code block has
been executed.
The example below will print the numbers 0 to 4:
Go to Statement
A goto statement provides an unconditional jump from the
goto to a labeled statement in the same function.
JUMP STATEMENTS
Use of goto statement is highly discouraged because it makes
Break Statement difficult to trace the control flow of a program, making the
program hard to understand and hard to modify. Any
The break statement can also be used to jump out of a loop.
program that uses a goto can be rewritten so that it doesn't need
Example:
the goto.
Switch Case Statements:
Use the switch statement to select one of many code blocks to
be executed.
This is how it works:
The switch expression is evaluated once FUNCTIONS:
The value of the expression is compared with the values A function is a block of code which only runs when it is called.
of each case
Functions are used to perform certain actions, and they are
If there is a match, the associated block of code is important for reusing code: Define the code once, and use it
executed many times.
The break and default keywords are optional, and will C++ provides some pre-defined functions, such as main(),
be described later in this chapter which is used to execute code. But you can also create your own
functions to perform certain actions.
To create (often referred to as declare) a function, specify the
name of the function, followed by parentheses ():
THE USE OF VOID
In C++, the void keyword is used in the context of functions to
indicate that the function does not return any value. When a
function's return type is specified as void, it means that the
function performs a task or action but does not produce a result
that can be used in an expression.
OVERLOADED FUNCTIONS: INITIALIZING ARRAYS:
Overloaded functions in C++ are multiple functions with the You can initialize an array at the time of declaration or later
same name but different parameter lists. The compiler during the program. Here are examples:
differentiates between these functions based on the number or
// Initializing at declaration
types of parameters. Function overloading allows you to use
int numbers[3] = {1, 2, 3};
the same function name for operations that conceptually do
the same thing but with different types or numbers of inputs. MULTIDIMENSIONAL ARRAYS:
C++ supports multidimensional arrays. A common example
RECURSIVITY:
is a 2D array:
Recursivity refers to the ability of a function to call itself.
// 2D array
Recursive functions can be a powerful and elegant way to solve
int matrix[3][3] = {
certain problems, especially those that exhibit a recursive
{1, 2, 3},
structure.
{4, 5, 6},
DECLARING FUNCTIONS:
{7, 8, 9}
Function declarations in C++ provide information to the
};
compiler about the function's name, return type, and
parameter types. A function declaration is necessary if you ARRAYS AS PARAMETERS:
define a function later in the code or if you want to use a Arrays can be passed to functions as parameters. When an
function before its actual definition. array is passed to a function, the function receives a pointer to
ARRAYS: the first element of the array. Here's an example:
In C++, an array is a collection of elements of the same data
type stored in contiguous memory locations. Arrays are
defined using a specific syntax:
// Example of an integer array
int myArray[5]; // Declare an integer array with a size of 5