Computer Programming
Computer Programming
CHAPTER TWO bytes. For example, sizeof(int) will give you the
size of an integer on your specific system.
SIZE OF A VARIABLE
The size of a variable depends on its data type. PRIMITIVE AND REFERENCE DATA
Here is a list of common data types in C++ along TYPES
with their corresponding memory sizes :-
8. long: Typically occupies 4 bytes of • int is a primitive data type used to store
memory (may vary on different systems). whole numbers.
9. unsigned long: Typically occupies 4 bytes • float is a primitive data type used to store
of memory (may vary on different decimal numbers.
systems). • char is a primitive data type used to store
10.float: Typically occupies 4 bytes of single characters.
memory. • bool is a primitive data type used to store
11.double: Typically occupies 8 bytes of boolean values (true or false).
memory.
Primitive data types have fixed sizes and
12.long double: Typically occupies 8 or more
predefined operations that can be performed on
bytes of memory (may vary on different
them. They are directly supported by the
systems).
programming language and have straightforward
It's important to note that the memory size of a memory representations.
data type can vary depending on the compiler
and system architecture. The sizes mentioned Reference Data Type:
above are typical sizes for common platforms, but A reference data type, also known as a reference
they are not guaranteed to be the same in all type, is a data type that refers to an object's
environments. Additionally, the size of some memory address rather than directly storing its
types, such as long and long double, may vary value. In simpler terms, a reference data type
between different systems. stores a reference or a "pointer" to an object
Keep in mind that the actual memory usage can rather than the object itself. This allows multiple
be influenced by factors like alignment and variables to refer to the same object, enabling
padding requirements imposed by the compiler sharing and manipulation of complex data
and system architecture. To get the precise size structures.
of a specific data type on your system, you can Reference data types are typically used to work
use the sizeof operator, which returns the size in with complex data structures such as arrays,
strings, and objects. They provide flexibility and
dynamic memory management. Examples of 2. Identifiers should not begin with a
reference data types include arrays, strings, and digit.
classes.
• Valid: num1, _value
For example:
• Invalid: 1var, 3_sum
• An array is a reference data type that can 3. Keywords (reserved words) in C++
store multiple values of the same type. cannot be used as identifiers.
• A string is a reference data type used to
represent a sequence of characters. • Valid: total, value
• A class is a user-defined reference data • Invalid: int, return
type that encapsulates data and behaviors. 4. C++ is case-sensitive, meaning that
lowercase and uppercase letters are
Reference data types allow for more complex data
considered different.
structures and support operations like copying,
modifying, and sharing data. They have a more • Valid: age, Age
dynamic nature compared to primitive data types • Invalid: var1, VAR1
and require special handling, such as memory
5. Identifiers cannot match any of the
allocation and deallocation.
reserved keywords in the C++
In summary, primitive data types represent basic language or specific keywords of your
values like numbers and characters, while compiler.
reference data types refer to objects by their
memory addresses. Primitive data types are • Reserved keywords include
simple and directly supported by the words like if, while, for, class,
programming language, while reference data void, and many others. You
types enable more complex data structures and cannot use these as identifiers.
require special handling.
VARIABLES IN C++
3. Value: A variable holds a value, which 2. Local Variables: Local variables are
can be changed during the execution of a declared within a specific block of code,
program. Initially, a variable may be such as within a function or a loop.
assigned an initial value, and later it can These variables have a local scope,
be updated by assigning a new value to meaning they are only accessible within
it. the block where they are declared. Local
variables exist only during the execution
To use a variable in C++, we need to declare it
of the block in which they are declared.
first. Declaring a variable means specifying its
Once the block is exited, the local
data type and giving it a name. The syntax for
variables are destroyed and their values
declaring a variable is: data_type variable_name;
are no longer accessible.
For example, to declare an integer variable
Example :-
named z, we write: int z; This statement reserves
a space in the computer's memory called z,
which can hold only integer values.
Program Explanation:
2. Condition: This step is a condition that is In simpler terms, think of the while loop as a
checked before each iteration. If the "do this while that is true" statement. It
condition is true, the loop continues continues executing a set of instructions as long
executing the code block. If the condition as a certain condition remains true. It's like a
is false, the loop terminates, and the repeated action that keeps going until a particular
program continues with the next requirement is fulfilled.
statement after the loop.
The while loop consists of a condition and a code
3. Update: This step is executed after each block. The condition is checked before each
iteration. It typically updates the loop iteration, and if it evaluates to true, the code
variable or performs any necessary block is executed. After each iteration, the
modifications for the next iteration. condition is checked again, and the loop
continues as long as the condition remains true.
Here's an example of a "for" loop in C++ that
Once the condition becomes false, the loop
prints numbers from 1 to 5:
terminates, and the program proceeds to the next
statement after the loop.
In this example:
• After each iteration, the update i++ 5. If it is true, the code block inside the loop is
increments the value of i by 1. executed. It prints the current value of count and
then increments it by 1 using count++. This
The loop will execute the code block inside the process continues until count reaches 5. Once
curly braces {} for each value of i from 1 to 5. count becomes 5, the condition count < 5
In this case, it will print the numbers 1 2 3 4 5 evaluates to false, and the loop terminates.
to the console.
The output of this example will be:
The "for" loop is commonly used when you know
the number of iterations in advance or when you
want to perform a specific action a fixed number
of times. It provides a concise way to express
repetitive behavior and is widely used in various
programming scenarios.
The while loop allows for flexible repetition, as
WHILE LOOP the number of iterations is determined by the
condition. You can think of it as a continuous
The while loop is a flow control construct in loop that keeps going until a specific condition
programming that repeatedly executes a block of becomes false. Just make sure to include code
within the loop that eventually alters the
condition, ensuring the loop will eventually end Notice that even if the condition count < 5
to avoid an infinite loop. becomes false after the first iteration, the code
block is still executed at least once because the
DO WHILE LOOP condition is checked after the execution of the
block.
In Java, the do-while loop is a flow control The do-while loop is useful when you want to
construct that repeatedly executes a block of code ensure that a block of code is executed at least
at least once, and then continues to execute the once, regardless of the condition. It provides
code as long as a specified condition remains flexibility in scenarios where you need to perform
true. It is a variation of the while loop, but with an action first and then check if it should be
the condition checked after the execution of the repeated.
code block.
THE CONTINUE AND BREAK STATEMENT
In simpler terms, think of the do-while loop as a
"do this, and then keep doing it while that is In C++, the "continue" and "break" statements
true" statement. It ensures that the code block is are flow control statements that allow you to
executed at least once, and then it checks if the modify the behavior of loops.
condition is true to decide whether to continue or
The "continue" statement is used to skip the
stop the loop.
remaining code inside a loop iteration and move
The syntax for the do-while loop in Java is as to the next iteration. When encountered, it
follows: terminates the current iteration and jumps to the
beginning of the next iteration.
In this example, the variable count is initialized In this example, the loop iterates from 1 to 10.
to 0. The do-while loop executes the code block When the condition i % 2 != 0 is true (indicating
inside the do statement, which prints the current an odd number), the "continue" statement is
value of count, and then increments count by 1 encountered, and the code block following it is
using count++. After each iteration, the condition skipped. As a result, only even numbers are
count < 5 is checked. If it evaluates to true, the printed: 2 4 6 8 10.
loop continues and executes the code block again.
The "break" statement, on the other hand, is
If the condition is false, the loop terminates.
used to immediately exit the loop when
The output of this example will be: encountered, regardless of the loop condition. It
provides a way to prematurely terminate the
loop.
In this example, the loop continues until i Please note that this is just a simple example to
reaches 10. However, when i becomes equal to illustrate the usage of goto. In general, it's
the target value (5 in this case), the "break" recommended to use other control flow structures
statement is encountered. The loop is immediately like if-else or loops to achieve the desired
terminated, and the program continues with the behavior, as they usually make the code more
statements following the loop. As a result, only readable and maintainable.
the numbers 1 2 3 4 are printed. PRE-INCREMENT (++K) AND POST-
Both the "continue" and "break" statements INCREMENT (K++)
provide control over loop execution. The
In C++, both k++ and ++k are increment
"continue" statement allows you to skip specific
operators used to increase the value of a variable.
iterations, while the "break" statement allows you
The main difference between them lies in their
to exit the loop prematurely. These statements
behavior regarding the value used in expressions
are helpful when you need to customize the
and the timing of the increment.
behavior of your loops based on certain
conditions or when you want to optimize the Let's break it down with a simpler explanation
execution flow. and a simple example:
• ++k (Pre-increment):
Here's an example of how it can be done: Think of an array as a set of labeled boxes,
where each box can hold one piece of data. Each
box is numbered or indexed, starting from 0, to
indicate its position in the array. The index is
like the address of the box that holds a particular
element.
WHAT’S AN ARRAY
ONE DIMENSIONAL ARRAY
structured and ordered way to store and work
with collections of data in a program.
DECLARATION OF ARRAYS
It's important to note that the size of the array This shorthand form is equivalent to count[i] =
must be known at compile time. The compiler count[i] + 5.
needs to allocate the appropriate amount of • Using array elements in conditional
memory based on the size specified. If you were statements:
to use a regular variable for the size, it would
if (annual_temp[j] < 10.0)
not work because the compiler needs to know the
cout << "It was cold this year" << endl;
size in advance to allocate the necessary memory.
By declaring and defining an array, you create a Using a loop to access every element in an array:
fixed-size container that can hold multiple values
for (i = 0; i < NE; i++)
of the same type. Each element in the array has
cin >> annual_temp[i];
its own unique index, starting from 0, which
allows you to access and manipulate individual
elements using their index. Arrays provide a
Here, NE is the number of elements in the
annual_temp array. In this case, the array does not have a specified
You can also calculate various statistics using size, and the compiler will automatically allocate
array elements. For example, to find the average enough space to hold the number of elements in
temperature of the first ten elements in the array: the initialization list. In this example, the primes
array will have seven elements.
sum = 0.0;
for (i = 0; i < 10; i++) If you want to specify the size of the array
sum += annual_temp[i]; explicitly, you can do so. The size must be
av1 = sum / 10; greater than or equal to the number of elements
in the initialization list. For example:
It is good practice to use named constants instead
of literal numbers in your code. By defining a int primes[10] = {1, 2, 3, 5, 7};
constant, such as const int NUM_ELEMENTS =
10, you can easily modify the size or range of In this case, the array primes has a size of ten,
but only the first five elements are initialized
the array without having to change multiple
with the provided values. The remaining elements
occurrences of the number in the code. will be set to their default values (0 in the case
It's important to note that C++ does not check of int).
whether the subscript used to access an array
element is within the valid range. It is the
programmer's responsibility to ensure that the
subscript falls within the range of 0 to n-1.
Accessing elements outside this range can lead to
unpredictable behavior, such as accessing invalid
memory locations or overwriting other variables
or program code. Subscript overflow, which
occurs when you use an index out of range, can
cause errors and unexpected results in your
program.
INITIALIZING ARRAYS
When initializing an array, you can provide
initial values to the array elements at the time of
declaration. This is done by enclosing the values
in curly brackets {}. For example, to initialize an
array primes with the first few prime numbers,
you can write :- COPYING ARRAYS
int primes[] = {1, 2, 3, 5, 7, 11, 13};
When it comes to copying arrays in C++, you In C++, if we have a class named "Square" to
cannot use the assignment operator (=) directly to represent each square on the chessboard, we can
assign one array to another. Instead, you need to declare a two-dimensional array named "board"
as follows:
copy the elements one by one using a loop.
const int SIZE = 10; This declaration creates an array with 8 rows and
int x[SIZE]; 8 columns, representing the 64 squares on the
int y[SIZE];
chessboard. Each element in the array can hold
an object of the "Square" class.
To copy the elements from array y to array x,
you need to iterate over the elements using a Alternatively, we could represent the same
loop and assign each element individually: chessboard using a one-dimensional array with 64
elements:
for (int i = 0; i < SIZE; i++) {
x[i] = y[i]; Square board[64];
}
However, using a one-dimensional array in this
In this loop, the index variable i is used to access case may not correspond as closely to the real-
each element of x and y. The value of y[i] is world chessboard, as the relationship between
assigned to x[i], effectively copying the value rows and columns is not explicitly defined.
from y to x. This process is repeated for each
When accessing elements in a multidimensional
element of the arrays until all elements are
array, each dimension is represented by its
copied.
corresponding subscript. For example, if we want
It's worth noting that using a constant, such as to access the fourth position in the first row of
SIZE, to store the array size is a good practice. the chessboard (assuming the first subscript
This allows you to easily change the size of the represents the row and the second subscript
arrays by modifying the constant value in one represents the column), we would use the
place, rather than having to update all the notation board[0][3]. In this case, the first
occurrences of the size throughout the code. This subscript value is 0 to indicate the first row, and
improves code maintainability and reduces the the second subscript value is 3 to indicate the
risk of missing any updates. fourth column.
strcpy(destination, source);
strcat(destination, source);
COMPARING STRINGS
Here's a simplified explanation of comparing
strings using strcmp() and strncmp() in C++:
De-referencing Operator (*) :- The first two lines (42) indicate that v1 and *p1
(the value pointed to by p1) both hold the value
Now, let's talk about the de-referencing operator 42 after the assignment. The next two lines
(*). Once you have a pointer that points to a (0x7ffc78b09a74) show the memory address of
variable, you can use the dereferencing operator v1 and the value stored in p1, respectively.
to access the value stored in that variable
indirectly. EXAMPLE :-
Here's an example :-
FUNCTION IN C++
Syntax: The syntax of a function definition void Return Type: If the function does not return
follows this pattern: a value, the return type should be explicitly
declared as void. A void return type indicates
return_type function_name([type that the function does not produce any result.
parameterName1, type parameterName2, ...])
{
// Statements and logic Example :-
}
RETURN VALUES
Pass by Reference: In C++, passing arguments by Here are some key points about returning a value
reference allows you to pass the actual original from a function:
object into the function rather than creating a
local copy. Changes made to the object within Return Type: Functions are declared with a
specific return type, which indicates the data type
of the value that the function will return. For program jumps to the instructions of that
example, a function declared with a return type function and then returns to the calling code
of int is expected to return an integer value. once the function is executed. However, for very
small functions that consist of just a few lines of
Using the return Keyword: To return a value code, this jumping process can introduce some
from a function, the return keyword is used. It is performance overhead.
followed by the value that is being returned. This
To optimize the performance in such cases, the
value can be a literal value, a variable, or an
inline keyword can be used when declaring a
expression that evaluates to a value.
function. When a function is declared as inline,
Returning a Value vs. Returning void: Functions the compiler includes the code of that function
can either return a value or have a return type of directly into the calling code instead of creating a
void. If a function has a return type of void, it separate function. It's as if the statements of the
means that the function does not return any function were written directly in the calling
value. In such cases, the return statement is used function.
without any value after it, simply indicating the
Here are a few key points about inline functions:
end of the function.
It's important to note that the return value can code. For larger functions, the benefits of
be captured and utilized by the caller, allowing inlining may be outweighed by the
computations or operations within the program. It's important to note that the decision to use the
inline keyword should be based on careful
INLINE FUNCTION AND RECURSIVE FUNCTION consideration. While it can provide performance
improvements for small functions, it may not
INLINE FUNCTIONS :- In programming, functions always be beneficial for larger functions or in
are typically defined separately from where they cases where the increased program size is a
are called. When a function is called, the concern.
So this skipping of the separate instructions is Another interesting type of function is called a
what we call "inline" functions. It helps speed recursive function. A recursive function is defined
things up because the computer doesn't need to in terms of itself. It usually has a base case,
jump to a different set of instructions and then which is a simple case that can be solved without
come back again. The instructions are right there, recursion, and a recursive case, which refers back
where they are needed, and it saves time. to the function itself to make progress towards
the base case.
But there is a catch. If the instructions are too
long, copying them everywhere can make the Let's take an example of a recursive function
program bigger and slower. So, we only use called "f" defined on non-negative integers:
inline functions for very short sets of instructions.
• f(0) is the base case, where the value is
To sum it up, an inline function is like copying a directly known.
short set of instructions directly into the place • For any value x greater than 0, f(x) is
where they are needed, instead of going to a defined as 2 * f(x - 1) + x^2.
different place to follow those instructions. It can
To evaluate the value of f(3), we need to
make things faster for short instructions, but we
evaluate f(2) first, then f(1), and finally f(0). By
need to be careful not to use it for long
substituting the values according to the
instructions that would make the program bigger
definition, we can compute the value of f(3) as
and slower.
21.
In programming, we often need to work with Once we have defined a structure, we can create
groups of related values. For example, if we want variables of that structure type just like any other
to store a date consisting of a day, month, and variable. These variables are called structure
year, it would be inconvenient to create separate variables. When we create a structure variable, it
will have all the member variables defined in the and year. The only difference is the name we
structure definition. give to each structure variable.
For example, if we create two structure variables To access the member variables of a structure
based on the date structure, both variables will variable, we use the dot (.) operator. We combine
have the same member variables: day, month, the structure variable's name with the member
and year. The only difference is the name we variable's name to refer to a specific member
give to each structure variable. variable. For example, if we have a structure
variable called myDate, we can access its day
To access the member variables of a structure
member variable as myDate.day.
variable, we use the dot (.) operator. We combine
the structure variable's name with the member It's important to note that member variables are
variable's name to refer to a specific member distinguished by the structure variable they
variable. For example, if we have a structure belong to. This means that we can have multiple
variable called myDate, we can access its day structure variables with the same member
member variable as myDate.day. variable names, but they are independent and
separate from each other.
It's important to note that member variables are
distinguished by the structure variable they
belong to. This means that we can have multiple DEFINING STRUCTURES
structure variables with the same member
variable names, but they are independent and
When defining a structure in C++, you are
separate from each other.
essentially creating a blueprint or template for a
STRUCTURE :- user-defined type. The structure specifies the
layout and types of its member variables.
In C++, a structure is a way to create a user-
To define a structure, you use the struct keyword
defined type that groups together multiple
followed by the structure name, which serves as
variables. It allows us to define a blueprint or
the type identifier. Inside the structure, you
template for a data structure that consists of
enclose the member variables within curly braces
several variables, which are called member
{}. Each member variable is declared just like
variables.
any other variable, specifying its type and name.
To define a structure, we use the struct keyword
For example, let's consider a structure called
followed by the name of the structure. Inside the
student. It has two member variables: an int
structure, we list the member variables along
variable named id and a character array of size
with their types and names. For example, we can
15 named name.
define a structure called date that contains three
member variables of type int: day, month, and
year.
In this code, the intention is to initialize the day, In the first line, we declare a variable i of type
month, and year member variables of the date int. This is a built-in type provided by the
structure to specific values (24, 10, and 2001, programming language.
respectively). In the second line, we declare a variable std1 of
However, this syntax is not valid in C++. type student. Here, student is a user-defined type
Member variables of a structure must be defined using a structure. The student structure
initialized when you create a structure variable, has characteristics or attributes that represent the
not within the structure definition itself. id and name of a student.
To properly initialize the member variables, you In the third line, we declare a variable birthday
can do it after creating a structure variable using of type date. Similarly, date is a user-defined
the assignment operator (=) or through a type defined using a structure. The date structure
constructor if you define one for your structure. has member variables such as day, month, and
year to represent a date.
Here's an example of initializing the member
variables after creating a structure variable When a structure variable is created, a block of
memory is reserved to hold all of its member
variables. Each member variable occupies a You can use any expressions that result in values
portion of that memory block. The member to initialize the member variables. For example,
variables are stored at specific offsets within the you can use variables and arithmetic operations.
memory block. For example, in the date However, once a structure variable has been
structure, the day member variable may be declared, you cannot assign values to multiple
located at offset 0, and the month member members using an initialization block. You need
variable may be located at offset 4 (assuming to access each member individually for
each member variable occupies 4 bytes). assignment.
So, by creating structure variables, we can store It's important to note that you can assign fewer
and access multiple related pieces of data in a values than the number of member variables in
single variable, making it easier to work with the structure, but you cannot assign more values.
complex data structures. If you omit a value in the initialization, no value
will be assigned to the corresponding member
variable.
INITIALIZING STRUCTURE VARIABLES
ACCESSING MEMBERS OF A STRUCTURE VARIABLE
When you define a structure, you cannot directly
To access the members of a structure variable,
initialize its member variables in the structure
you use the structure member operator, which is
definition. However, you can initialize the
the period (dot) symbol. You specify the structure
member variables of a structure variable when
variable's name, followed by the period, and then
you create it.
the name of the member variable you want to
To initialize the member variables of a structure access.
variable, you use an initialization block. After the
For example, if you have a structure variable
variable declaration, you use the assignment
called s1 with member variables id and name,
operator (=) and provide a list of initializers
you can access them using s1.id and s1.name.
enclosed in curly braces. The values are assigned
This allows you to read and assign values to the
to the member variables in the order they are
member variables, as well as display their
declared in the structure definition.
contents.
For example, consider the following code:
In the provided example, a program creates a
structure called student, which has member
variables id and name. The program creates two
student variables, s1 and s2, and prompts the
user to enter their IDs and names. The
In the first line, a variable called nco_birthday of
information is stored in the respective variables,
type date is created and initialized with the
and then the program displays the students'
values {19, 8, 1979}. The values are assigned to
information by accessing their member variables
the member variables day, month, and year in
using the structure member operator.
the same order they are declared in the structure
definition. By using the structure member operator, you can
access and manipulate the individual member
Similarly, in the second line, a variable called
variables of a structure variable, allowing you to
std1 of type student is created and initialized
work with the data stored in the structure.
with the values {"Ababe", "Scr/2222/22"}. The
values are assigned to the member variables
name and id in the same order they are declared
in the structure definition.
This can be useful when you want to group
variables together in one place without affecting
other parts of the program.
Example :-
By including a structure definition as a member By using nested structures, you can achieve better
variable within another structure definition, you code organization, improve readability, and
can create a hierarchical structure that organizes enhance the maintainability of your programs. It
and encapsulates related data together. helps in avoiding naming conflicts and provides a
clear and structured representation of the data
For example, consider a scenario where you have
relationships.
a Person structure that represents an individual,
and within the Person structure, you want to
include an Address structure to store the person's
address details. This allows you to associate
FILE MANAGEMENT
address information with each person.
File management is an important aspect of
By nesting structures in this way, you can access programming where we work with files, such as
and manipulate the member variables of the saving data to the computer's storage and reading
nested structure using the dot operator (.) to data from it. The files stored on the computer's
access the specific members within the structure storage are called physical files. In order to work
hierarchy. with files in a program, we create a logical file
in the computer's memory (RAM). This logical file
When you declare a structure type as part of
is represented as an object with a specific file
another structure, you create a hierarchical
type. To keep track of this logical file, we use a
relationship between the structures. This
variable called a file variable or file handler.
hierarchy allows you to organize related data and
access it in a structured manner.
Example :-
Example :-
Example :-
The code starts by including the necessary Finally, we close all the opened files using the
libraries and declaring the using namespace std; close function of each file object. Closing the files
statement to avoid writing std:: before each is important to ensure that all the data is written
standard library function or object. and the resources are properly released.
Inside the main function, we create five ofstream The return 0; statement signifies the end of the
objects: outFile1, outFile2, outFile3, outFile4, and main function and indicates that the program
outFile5. These objects represent output file executed successfully.
streams, allowing us to write data to files.
We then open the files using the open function of In this code, we are using the C++ standard
each file object. The files "ethio1.txt", libraries iostream and fstream for input/output
"ethio2.txt", "ethio3.txt", and "ethio5.txt" are operations.
opened in append mode (ios::app) to append data The code starts by including the necessary
to the existing content of the files. The file libraries and declaring the using namespace std;
"ethio4.txt" is opened without any specific mode, statement to avoid writing std:: before each
so it will be opened for writing and overwrite standard library function or object.
any existing content.
Inside the main function, we declare string
Next, we use the << operator to write messages variables x and z to store read words and lines,
to the files. For example, outFile1 << "Hello respectively. We also declare character variables y
World"; writes the message "Hello World" to the and a to store read characters.
file associated with outFile1.
We then create five ifstream objects: inFile3,
inFile4, inFile5, inFile6, and inFile7. These
objects represent input file streams, allowing us
to read data from files.