Computer Programming
Computer Programming
“Computer Programming”
Section 1
Group 1
Department of Pre-engineering
GROUP NAME ID No.
1. Ananiya Gezahegn NSR/195/17
2.Abidnasir Yasin NSR/3023/17
3.Bisrat Kasu NSR/427/17
4.Bethlehem Getu NSR/353/17
5.Bitania Sintayehu NSR/432/17
6.Mikiyas Shewalewu NSR/1194/17
7.Fireweyni Biruk NSR/727/17
8.Mubarek Gudeta NSR/1237/17
9.Abdirisak Abdikaadir NSR/3022/17
10.Firewu Fillipos NSR/726/17
11.Hana Baye NSR/825/17
Submitted to: Instructor Ayele
Structure………………………………………………………………………………………………………………………………46
Functions………………………………………………………………………………………………………………………………46
Arrays…………………………………………………………………………………………………………………………………..47
Pointers……………………………………………………………………………………………………………………………….48
Comparison…………………………………………………………………………………………………………………………49
8. References.........................................................................................................................52
UNIT ONE
INTRODUCTION
An electronic device operating under the control of instructions stored in its own memory unit. An
electronic device that stores and process data, in doing so:
➔Receive data (input) ,Processes data arithmetically and logically ,Produce information (output)
from the processing and Store information (output) for future use
The four operations are referred to as the information processing cycle: Input, process, output, and
storage. Computers transform raw data into information. Overview of Computers and Computer
Organization. Regardless of differences in physical appearance, virtually every computer may be
envisioned as being
Input Unit : it obtains information from various input devices and places this information at the disposal
of the other units so that the information may be processed or stored. Output Unit : it takes information
that has been processed by the computer and places it on various
output devices to make the information available for use outside the computer. Memory unit : it retains
information that has been entered through the input unit, so the information
may be made immediately available for processing when it is needed. The memory unit also retains
processed information until that information can be placed on output devices by the output unit
. Central Processing Unit (CPU) : it is the computer’s coordinator and is responsible for supervising
the operations of the other sections. CPU tells the input unit when information should be read into
memory, tells ALU when information from the memory should be used in calculation and tells output
unit when to send information from the memory to certain output devices. Arithmetic and Logic unit : is
a part found inside the Central Processing Unit and is responsible for
performing calculations such as addition, subtraction, multiplication and division. It also performs
comparisons. Secondary Storage device : Programs or data used by other units normally are placed on
secondary
storage devices (such as disks) until they are needed, possibly hours, days, months, or even years later.
Numbering system
is a way of representing numerical values using a set of symbols or digits. The most commonly used
number systems in computers are the decimal system, the binary system, and the hexadecimal system.
What is the base of number system in computer?
The base, or radix, of a number system in computer science refers to the number of digits or symbols
used
to represent numerical values. In other words, the base determines how many unique values can be
represented with a single digit in the number system. The most commonly used number systems in
computer science are:
In general, a number system with a higher base can represent more unique values with a smaller
number
of digits. For example, the binary system (base 2) can only represent 2 unique values with a single digit
(0
and 1), while the decimal system (base 10) can represent 10 unique values (0-9) with a single digit.The
hexadecimal system (base 16) can represent 16 unique values (0-9 and A-F) with a single digit. What is
the use of number system in computer?
Number systems are a fundamental part of how computers represent and manipulate data. Computers
use
binary (base-2) number system to represent data and perform calculations. Here are some specific uses
of
Representing data:
Computers use the binary number system to represent all kinds of data, such as text, images, audio, and
video. Each piece of data is converted into a series of 0s and 1s, which can be stored and processed by
the
Memory in a computer is organized into a series of addressable locations. The number of locations is
determined by the number of bits used to represent each memory address. For example, a 32-bit
computer
Computer programming involves working with numbers and mathematical operations. Programmers
use
number systems such as binary, decimal, and hexadecimal to represent and manipulate data in their
programs.Overall, the use of number systems is essential to the functioning of computers and
computer- based technologies
There are several types of number systems used in computer science, including:
Binary: The binary number system uses two digits, 0 and 1, to represent all numbers. It is the foundation
of all digital systems, including computers. Decimal: The decimal number system uses ten digits, 0
through 9, to represent all numbers. It is the
number system most commonly used by humans. Octal: The octal number system uses eight digits, 0
through 7, to represent all numbers. It is commonly
used in computer programming and digital electronics. Hexadecimal: The hexadecimal number system
uses 16 digits, 0 through 9 and A through F, to represent
all numbers. It is often used in computer programming and digital electronics because it is more
compact
and easier to read than binary. In computer science, binary is the most commonly used number system,
as it is the foundation of all
digital systems. However, decimal, octal, and hexadecimal are also used in various applications.
Computers and digital circuits processes information in the binary format. Each character is assigned 7
or
8 bit binary code to indicate its character which may be numeric, alphabet or special symbol. Example -
Binary number 1000001 represents 65(decimal) in straight binary code, alphabet A in ASCII code and
41(decimal) in BCD code. Types of codes
Four-bit code that represents one of the ten decimal digits from 0 to 9. Example - (37)10 is represented
as 0011 0111 using BCD code, rather than (100101)2 in straight binary
code. Thus BCD code requires more bits than straight binary code. Still it is suitable for input and output
operations in digital systems. Note: 1010, 1011, 1100, 1101, 1110, and 1111 are INVALID CODE in BCD
code. ASCII (American Standard Code Information Interchange) code :
It is 7-bit or 8-bit alphanumeric code. 7-bit code is standard ASCII supports 127 characters. Standard
ASCII series starts from 00h to 7Fh, where 00h-1Fh are used as control characters and 20h-7Fh
as graphics symbols. 8-bit code is extended ASCII supports 256 symbols where special graphics and
math's symbols are added.
8-bit alphanumeric code developed by IBM, supports 256 symbols. It was mainly used in IBM mainframe
computers. Gray code
Differs from leading and following number by a single bit. Gray code for 2 is 0011 and for 3 is 0010. No
weights are assigned to the bit positions. Extensively used in shaft encoders.
Excess-3 code
4-bit code is obtained by adding binary 0011 to the natural BCD code of the digit. Example - decimal 2 is
coded as 0010 + 0011 = 0101 as Excess-3 code.
It not weighted code. Its self-complimenting code, means 1's complement of the coded number yields
9's complement of the
number itself. Used in digital system for performing substraction operations. UNIT 2
A programming basics course teaches fundamental programming concepts that are common across
many programming languages. It typically covers topics like variables, data types, operators, control flow
(if/else statements, loops), functions, and debugging. The goal is to build a strong foundation in
programming, allowing learners to understand how programs are structured and how they execute. Key
Concepts:
Variables: Memory locations that store data, which can be numbers, text, or other values. Data Types:
Categories of data, such as integers, floating-point numbers, strings, and booleans. Operators: Symbols
that perform operations on data, like addition, subtraction, or comparison. Control Flow: Mechanisms
for controlling the order in which code is executed, such as if/else statements, loops, and break
statements. Functions: Reusable blocks of code that perform specific tasks. Debugging: The process of
finding and fixing errors in code. C++ is one of the oldest programming languages. Bjarne Stroustrup
invented it in 1979 in New Jersey at
Bell laboratories. Earlier, C++ was known as C with classes, because they designed it as an extension of
the C language. In 1982 the creators renamed it C++, and they added some new features like operator
overloading, virtual functions, comments, and so on. In 1985 C++ was released for commercial
implementation, and in the year 1989, its second edition was released. Basics_Example. C++ is one of
the most popular programming languages; it is an object-oriented, pre-compiled, and
intermediate-level language. C++ has a wide variety of applications, and you use it for making games,
developing software applications, operating systems, and whatnot. This tutorial on C++ Basics will help
Example
#include <iostream>
int main() {
return 0;
Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such
as cout (used in line 5). Header files add functionality to C++ programs. Line 2: using namespace std
means that we can use names for objects and variables from the standard
library. Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable. Line
4: Another thing that always appear in a C++ program is int main(). This is called a function. Any
code inside its curly brackets {} will be executed. Line 5: cout (pronounced "see-out") is an object used
together with the insertion operator (<<) to
output/print text. In our example, it will output "Hello World!". Note: C++ is case-sensitive: "cout" and
"Cout" has different meaning. Note: Every C++ statement ends with a semicolon ;. Note: The body of int
main() could also been written as:
The compiler ignores white spaces. However, multiple lines makes the code morereadable. Line 6:
return 0; ends the main function. Line 7: Do not forget to add the closing curly bracket } to actually end
the main function
Example
#include <iostream.h>
int main()
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return 0;
C++ Statements
The cout object, together with the << operator, is used to output values and print text. Input (cin)
Is done by applying the overloaded operator of extraction (>>) on the cin stream. This must
be followed by the variable that will store the data that is going to be read. Example: int age;
cin >> age; Declares the variable age as an int and then waits for an input from cin (keyborad). Data
Types and Variables
Data types: They are used along with the variables; they instruct the variables on what kind of data they
can store. Data types in C++ are of three types:
Primitive data types: These data types are built-in and are used to declare variables. For example,
boolean, integer, character, float, etc. Derived data types: These are called derived data types because it
derives them from primitive data types. It includes function, array, pointer, etc. User-defined data type:
These are those data types that the user defines. Variables: Variables are used to store values. To
declare a variable, you must write the variable name
problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the
flowchart is drawn, it becomes easy to write the program in any high level language.
Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct
to say that a flowchart is a must for the better documentation of a complex program.
An operator is a symbol that makes the machine to take an action. Different Operators act on one or
more
operands and can also have different kinds of operators. C++ provides several categories of operators,
including the following:
Assignment operator (=). Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
Arithmetic operators (+, -, *, /, %). Relational operator (==, !=, > , <, >=, <=). Logical Operators (!, &&, ||):
#include <iostream.h>
int main()
return 0;
Special Printing characters. In C++, there are some special characters used for formatting. These are: \n
new line \t tab \b backspace \” double quote \’ single quote \? Question mark \\ backsla
Fundamental Variable types. Several other variable types are built into C++. They can be conveniently
classified as integer, floating- point or character variables. Floating-point variable types can be expressed
as fraction i.e. they are “real
numbers”. Character variables hold a single byte. They are used to hold 256 different characters and
symbols of the ASCII and extended ASCII character sets. The type of variables used in C++ program are
described in the next table, which lists the variable type, how much room
scope of Variables. Scope of a variable is the boundary or block in a program where a variable can be
accessed. The boundary
or block is identified by the left and right French brackets. In C++, we can declare variables any where in
the source code. But we should declare a variable before
using it no matter where it is written. Global variables: are variables that can be referred/accessed any
where in the code, within any function, as long as it is declared first. A variable declared before any
function immediately after the include
statements are global variables. Local Variables: the scope of the local variable is limited to the code
level or block within which they
are declared.
UNIT 3
CONTROL STATEMENTS
A running program spends all of its time executing instructions or statements in that program. The order
in which statements in a program are executed is called flow of that program. Programmers can control
which instruction to be executed in a program, which is called flow control. This term reflects the fact
that the currently executing statement has the control of the CPU, which when completed will be
handed
over (flow) to another statement. Flow control in a program is typically sequential, from one statement
to the next. But we cal also have execution that might be divided to other paths by branching
statements. Or perform a block of statement repeatedly until a condition fails by Repetition or looping.
Flow control
is an important concept in programming because it will give all the power to the programmer to decide
what to do to execute during a run and what is not, therefore, affecting the overall outcome of the
program.
Sequential Statements
Such kind of statements are instruction in a program which will executed one after the other in the
order
scripted in the program. In sequential statements, the order will be determined during program
Selection statements are statements in a program where there are points at which the program will
decide
at runtime whether some part of the code should or should not be executed. There are two types of
selection statements in C++, which are the “if statement” and the “switch statement” The if Statement
It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied. The different forms of the ‘If” statement will be used to decide whether to execute part of the
program
based on a condition which will be tested either for TRUE or FALSE result.
These execute code blocks based on whether a condition is true or false. if: Executes a block if a
condition is true. i ntx ;
cin>>x;
if(x)
13
if-else: Executes one block if a condition is true and another if it's false. #include <iostream.h>
int main()
{ int n;
cin >> n;
if ( n % 2 == 0)
else
return 0;
int main()
int year;
if (year % 100 == 0)
if (year % 400 == 0)
else
else
else
return 0;
switch: Selects a code block to execute based on the value of a variable. #include <iostream.h>
int main()
{ int year;
if (year % 4 == 0)
if (year % 100 == 0)
{
if (year % 400 == 0)
else
15
else
else
return 0;
Looping Statements:
These repeat a block of code until a condition is met. for: Repeats a block a specific number of times.
#include <iostream.h>
int main()
int n, sum = 0;
cin >> n;
sum += i;
}
cout << "Sum = " << sum;
return 0;
int main()
while(n1 != n2)
n1 -= n2;
else
n2 -= n1;
return 0;
do-while: Repeats a block at least once and then continues as long as a condition is true. range-based
for: Iterates over a range of values. #include <iostream.h>
int main(){
age=-1;
cin>>age; }
Jump Statements:
These transfer control to another part of the program. break: Terminates a loop or switch statement.
#include <iostream.h>
int main(){
for(n=10;n>0;n--) {
cout<<n<< “,”;
if(n = = 3) {
break; }
return 0;
continue: Skips the remaining code in the current loop iteration and starts the next iteration. #include
<iostream.h>
int main()
for(int n=10;n>0;n--) {
if(n==5)
cout<<n<< “,”; }
int n=20;
loop:
n--; if (n>0)
goto loop;
return 0; }
UNIT 4
FUNCTIONS
What is a function?
A function provides a convenient way of packaging a computational recipe, so that it can be used as
often as required. Therefore, a function is a block of code designed to tackle a specific problem.
. Function Basics
One of the best ways to tackle a problem is to start with the overall goal, then divide this goal into
several smaller tasks. You should never lose sight of the overall goal, but think also of how individual
pieces can fit together to accomplish such a goal. If your program does a lot, break it into several
functions. Each function should do only one primary task. Summarized function basics. C++ functions
generally adhere to the following rules. 1. Every function must have a name. 2. Function names are
made up and assigned by the programmer following the same rules that apply to
naming variables. They can contain up to 32 characters, they must begin with a letter, and they can
consist of letters, numbers, and the underscore (_) character. 3. All function names have one set of
parenthesis immediately following them. This helps you (and C++
compiler) differentiate them from variables. 4.The body of each function, starting immediately after
parenthesis of the function name, must be
enclosed by braces. Declaring, defining and calling functions Declaring function :The interface of a
function (also called its prototype) specifies how it may be used. It consists of three entities:
o The function return type. This specifies the type of value the function returns. A function which
returns nothing should have a return type void. o The function name. this is simply a unique identifier
o The function parameters (also called its signature). This is a set of zero or more typed identifiers used
o A function definition consists of two parts: interface (prototype) & body. The brace of a function
contains the computational steps (statements) that computerize the function. The definition consists of
a
line called the decelerator. o If function definition is done before the main function, then there is no
need to put the prototype, otherwise the prototype should be scripted before the main function starts.
Calling the function:
o Using a function involves ‘calling’ it. o Calling a function means making the instruction of the function
to be executed. o A function call consists of the function name followed by the call operator brackets ‘()’,
inside which
zero or more comma-separated arguments appear. The number and type of arguments should match
the
number of function parameters. Each argument is an expression whose type should match the type of
the
corresponding parameter in the function interface. o When a function call is executed, the arguments
are
first evaluated and their resulting values are assigned to the corresponding parameters. The function
body is then executed. Finally the return value (if any) is passed to the caller. Example:C++
return a + b;
In this example:
add is the function name. int a, int b are the parameters, both of type int. int is the return type. return a
+ b; is the function body, which calculates and returns the sum of a and b.
Parameters or Arguments
A function can also take some input data to process. These values are called function arguments and are
supplied to the function at the function call. To receive these values, we define placeholder variables
called parameter inside parenthesis in function definition. They should be specified with their types and
names. return_type name(type1 name1, type2 name2...) {
// Function body
return val;
name1, name2 and so on are the parameter names using which they will be accessed in the function.
Example:
#include <bits/stdc++.h>
int main() {
printNum(num1);
printNum(num2);
return 0;
In the above program, printNum() function is defined with one integer parameter n that it prints. It
means
that it will take one value of integer type while calling and print it. We called printNum() two times, one
with num1 and one with num2, and in each call, it prints the given number. Note that we refer to the
passed argument using the name n not num1 or num2 in the function. It is due to the concept called
scope
of variables in the main and printNum() function. Heretofore, there can be one question. Why didn't we
call the function with both numbers at once? The
answer lies in the printNum() definition. We have defined the function that only takes one value of
integer
type as parameter, so we cannot pass two values. In other words, A function can only take as many
arguments as specified in the function definition and it is compulsory to
pass them while calling it. Also, they should be of same type as in the function definition. main is also
the function. In C++, the main function is a special function that every C++ program must
contain. It serves as the entry point for the program. The computer will start running the code from the
beginning of the main function. The return value of the main function indicates the successful or
When function is called within the same function, it is known as recursion. The function which calls itself
is known as recursive function and such calls are called recursive calls. Recursion is an important concept
in programming that simplifies a lot of problems are complex to handle using normal programming
means. Example
#include <iostream.h>
int main()
string str;
getline(cin, str);
reverse(str);
return 0;
if(numOfChars == 1)
else
Function Overloading
Up until now, we know that an identifier can only be used only once in the program. The name of the
function is also an identifier, so it should be unique as well. Image a scenario where you have a function
that performs the multiplication of two integers, but you also
need to a function that multiplies two integers that are in the form of strings. Normally, you may have to
use two functions with different names for this purpose. In large codebase, there can be many such
cases
and creating and remembering the names of these functions can be hectic. This problem can be solved
though function overloading. Function overloading refers to the feature in
C++ where two or more functions can have the same name but different parameters. It allows us to use
the same function name for different arguments but same purpose. This helps in clean semantically
understandable code. In C++, data can be sent to functions when they are called in order to perform
operations. This data is
called parameters or arguments and there are various parameter passing methods available in C++. In
this
article, we will discuss various parameter-passing techniques in C++. Before you see the techniques, first
understand the difference between the following terms:
Formal Parameters: Variables used in parameter list of a function as placeholders. Also called only
parameters. Actual Parameters: The expressions or values passed in during a function call. Also called
arguments. There are 3 different methods using which we can pass parameters to a function in C++.
These are:
1. Pass by Value
In pass by value method, a variable's value is copied and then passed to the function. As the result, any
changes to the parameter inside the function will not affect the variable's original value in the caller.
This
method is simple, easy to understand and implement but it is not preferred for large size of data
structures
C++
#include <iostream>
void change(int a) {
// Modifying arguments
a = 22;
int main() {
int x = 5;
change(x);
cout << x;
return 0;
2. Pass by Reference
In pass-by-reference method, instead of passing the value of the argument, we pass the reference of an
argument to the function. This allows the function to change the value of the original argument. This is
#include <iostream.h>
int main()
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "a = " << a << ", b = " << b << endl;
return 0;
Example
C++
#include <iostream>
void change(int& a) {
// Modifying arguments
a = 22;
}
int main() {
int x = 5;
change(x);
cout << x;
return 0;
Output; 22
3. Pass by Pointer
The pass-by-pointer is very similar to the pass-by-reference method. The only difference is that we pass
the raw address of the argument as the parameter to the function instead of reference. Example
C++
#include <iostream>
void change(int* a) {
// Modifying arguments
*a = 22;
int main() {
int x = 5;
change(&x);
cout << x;
return 0;
}
UNIT 5
What is An Array?
A collection of identical data objects, which are stored in consecutive memory locations under a
common heading or a variable name. In other words, an array is a group or a table of values referred to
by the same name. The individual values in array are called elements. Array elements are also variables.
Set of values of the same type, which have a single name followed by an index. In C++, square brackets
A block of memory representing a collection of many simple data variables stored in a separate array
element, and the computer stores all the elements of an array consecutively in memory. Properties of
arrays:
Arrays in C++ are zero-bounded; that is the index of the first element in the array is 0 and the last
element is N-1, where N is the size of the array. It is illegal to refer to an element outside of the array
bounds, and your program will crash or have
unexpected results, depending on the compiler. Array can only hold values of one type
Array declaration
Declaring the name and type of an array and setting the number of elements in an array is called
dimensioning the array. The array must be declared before one uses in like other variables. In the array
1. The type of the array (i.e. integer, floating point, char etc.)
2. Name of the array, 3. The total number of memory locations to be allocated or the maximum value of
each subscript. i.e. the
number of elements in the array. So the general syntax for the declaration is:
#include <iostream>
return 0;
Initializing Arrays
When declaring an array of local scope (within a function), if we do not specify the array variable will
not be initialized, so its content is undetermined until we store some values in it. If we declare a global
array (outside any function) its content will be initialized with all its elements
#include <iostream>
int main() {
double sum = 0;
sum += numbers[i];
}
double average = sum / size;
return 0;
Strings of Characters
In all programs and concepts we have seen so far, we have used only numerical variables, used to
express
numbers exclusively. But in addition to numerical variables there also exist strings of characters that
allow us to represent successive characters, like words, sentences, names, texts, etc. Until now we have
only used them as constants, but we have never considered variables able to contain them. In C++ there
is no specific elementary variable type to store string of characters. In order to fulfill this
feature we can use arrays of type char, which are successions of char elements. Remember that this
data
type (char) is the one used to store a single character, for that reason arrays of them are generally used
to
int main()
int sec=6;
return 0;
Due to that a string may contain representations of other data types like numbers it might be useful to
translate that content to a variable of a numeric type. For example, a string may contain "1977" , but
this
is a sequence of 5 chars not so easily convertible to a single integer data type. The cstdlib ( stdlib.h )
library provides three useful functions for this purpose: • atoi: converts string to int type. • atol:
converts string to long type. • atof: converts string to float type. Functions to manipulate strings
The cstring library ( string.h ) defines many functions to perform some manipulation operations with
C-like strings (like already explained strcpy). Here you have a brief with the most usual:
a) String length Returns the length of a string, not including the null character (\0). strlen (const char*
string );
b) String Concatenation: Appends src string at the end of dest string. Returns dest. The string
concatenation can have two forms, where the first one is to append the whole content of the source to
the
destination the other will append only part of the source to the destination. o Appending the whole
content of the source strcat (char* dest , const char* src );
o Appending part of the source strncat (char* dest , const char* src, int size ); Where size is the
#include <iostream>
int main() {
30
cin.getline(str1, 100);
cin.getline(str2, 50);
int i, j;
str1[i] = str2[j];
str1[i] = '\0';
return 0;
c) String Copy: Overwrites the content of the dest string by the src string. Returns dest. The string
copy can have two forms, where the first one is to copying the whole content of the source to the
destination and the other will copy only part of the source to the destination. o Copy the whole content
of the source strcpy (char* dest , const char* src );
o Appending part of the source strncpy (char* dest , const char* src, int size ); Where size is the
#include <iostream>
int main() {
cin.getline(str1, 100);
strcpy(str2, str1);
return 0;
d) String Compare: Compares the two string string1 and string2. The string compare can have two forms,
where the first one is to compare the whole content of the two
strings and the other will compare only part of the two strings. o Copy the whole content of the source
strcmp (const char* string1 , const char* string2 );
o Appending part of the source strncmp (const char* string1 , const char* string2, int size ); Where
o Returns negative value if the first is less than the second string
o Returns positive value if the first is greater than the second string
Multidimensional Arrays
In C++, we can create an array of an array, known as a multidimensional array. For example: int x[3][4];
Here, x is a two-dimensional array. It can hold a maximum of 12 elements.We can think of this array as a
table with 3 rows and each row has 4 columns as shown below. C++ two dimensional array
float x[2][4][3];
This array x can hold a maximum of 24 elements. We can find out the total number of elements in the
array simply by multiplying its dimensions:
2 x 4 x 3 = 24
Like a normal array, we can initialize a multidimensional array in more than one way. 1. Initialization of
two-dimensional array
The above method is not preferred. A better way to initialize this array with the same array elements is
given below:
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements
each. // C++ Program to display all elements
#include <iostream>
int main() {
int test[3][2] = {{2, -5}, {4, 0}, {9, 1}}; // use of nested for loop
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
} return 0;
}
UNIT-6
POINTERS
Introduction
We have already seen how variables are memory cells that we can access by an identifier. But these
variables are stored in concrete places of the computer memory. For our programs, the computer
memory
is only a succession of 1 byte cells (the minimum size for a datum), each one with a unique address. A
pointer is a variable which stores the address of another variable. The only difference between pointer
variable and regular variable is the data they hold. There are two pointer operators in C++:
Whenever you see the & used with pointers, think of the words “address of.” The & operator always
produces the memory address of whatever it precedes. The * operator, when used with pointers, either
declares a pointer or dereferences the pointer’s value. The dereference operator can be literally
translated
to "value pointed by" . A pointer is simply the address of an object in memory. Generally, objects can be
accessed in two ways:
directly by their symbolic name, or indirectly through a pointer. The act of getting to an object via a
pointer to it, is called dereferencing the pointer. Pointer variables are defined to point to objects of a
specific type so that when the pointer is dereferenced, a typed object is obtained. At the moment in
which we declare a variable this one must be stored in a concrete location in this succession of cells (the
memory). We generally do not decide where the variable is to be placed - fortunately that is something
automatically done by the compiler and the operating system on runtime, but once the operating
system
has assigned an address there are some cases in which we may be interested in knowing where the
variable is stored. This can be done by preceding the variable identifier by an ampersand sign (&), which
literally means, "address of”. For example: ptr= &var;
This would assign to variable ptr the address of variable var , since when preceding the name of the
variable var with the ampersand ( & ) character we are no longer talking about the content of the
variable, but about its address in memory. We are going to suppose that var has been placed in the
memory address 1776 and that we write the
following:
var=25;
x=var;
ptr = &var;
Declaring Pointers:
Is reserving a memory location for a pointer variable in the heap. Syntax: type * pointer_name ;
Pointers allow programs to create and modify dynamic data structures, while enabling them to simulate
call-by-reference. One key use of pointers is iterating over elements in arrays or other data structures.
Here is the general form of declaring a pointer variable:
type *var-name;
In this syntax, type refers to the base type of the pointer, and it must be valid. var-name refers to the
name
of the pointer variable. The asterisk used for pointer declaration is the same used for multiplication.
However, here, we use an asterisk to designate a variable as a pointer. Here are valid pointer
declarations:
The data type of the value of pointers, including integer, character, float, or double, is the same, a
hexadecimal number representing a memory address. However, pointers of different data types differ in
terms of the data type of the variable or constant that a pointer is pointing to. Syntax of a Pointer in C++
datatype *var_name;
The memory address of a variable refers to the location of every declared variable in the memory.
Suppose you have the variable var in the program, so use &var to return the memory address. C++
Pointer Example:
#include <iostream>
int main() {
int a = 10;
cout << "Pointer ptr stores address: " << ptr << endl;
cout << "Value at address stored in ptr (*ptr): " << *ptr << endl;
cout << "New value of a after modifying through pointer: " << a << endl;
return 0;
Define a pointer variable. Use the unary operator (&) to assign the address of a variable, which returns
the variable’s address. Use the unary operator (*) to access the value stored in the address, and it will
return the variable value, which is located at the address given by its operand.
We can pass C++ arguments to function using the following three ways:
Call-By-Value
#include <iostream>
// Function that accepts a pointer but does NOT modify the actual pointer
ptr = nullptr; // This does NOT affect the original pointer in main()
int main() {
cout << "Before function call: " << num << endl;
cout << "After function call: " << num << endl;
cout << "Pointer in main after function call: " << ptr << endl; // Still holds original address
return 0;
An array name consists of the address of the first element of an array, acting like a constant pointer.
Hence, we can’t change the address stored in the array name. Example:
#include <iostream>
int main() {
cout << "Element " << i << " (Value: " << *(ptr + i) << ", Address: " << (ptr + i) << ")\n";
cout << "First element (arr[0]): " << *arr << endl;
cout << "Second element (arr[1]): " << *(arr + 1) << endl;
*(arr + 2) = 99;
cout << "\nAfter modifying arr[2] using pointer: " << arr[2] << endl;
return 0;
We can perform a few arithmetic operations on pointers, which we have discussed below:
Example:
#include <iostream>
int main() {
cout << "p1 points to: " << *p1 << " at address " << p1 << endl;
cout << "p2 points to: " << *p2 << " at address " << p2 << endl;
// Incrementing pointer
p1++;
cout << "p1 now points to: " << *p1 << " at address " << p1 << endl;
// Decrementing pointer
p2--;
cout << "p2 now points to: " << *p2 << " at address " << p2 << endl;
p1 += 2;
cout << "p1 now points to: " << *p1 << " at address " << p1 << endl;
p2 -= 1;
cout << "p2 now points to: " << *p2 << " at address " << p2 << endl;
// Pointer difference
cout << "\nPointer difference (p2 - p1): " << diff << endl;
return 0;
}
Advanced Pointer Notation
Now, let’s understand pointer notation for the two-dimensional numeric arrays. Example:
#include <iostream>
39
int main() {
int arr[3][3] = {
};
cout << "arr[" << i << "][" << j << "] = " << *(*(arr + i) + j) << " ";
cout << "Base address of arr: " << arr << endl;
cout << "Address of first row (arr[0]): " << arr[0] << " == " << *(arr) << endl;
cout << "Address of second row (arr[1]): " << arr[1] << " == " << *(arr + 1) << endl;
return 0;
String literals are arrays, i.e., a null-terminated sequence of characters. They are arrays of type character
plus a terminating null character, where every element is of the type const char (considering that string
characters can’t be modified). Example:
40
#include <iostream>
int main() {
const char *str = "Hello, World!"; // String literal stored in read-only memory
cout << "String Literal Address: " << (void*)str << endl; // Print base address of string
cout << "First character: " << *str << endl; // Access first character
return 0;
Pointers to Pointers
C++ allows us to create a pointer to a pointer that, in turn, can point to data or another pointer. While
declaring the pointer for every level of indirection, the syntax includes a unary operator (*) for every
level
of indirection. char x;
char *y;
char ** z;
x = ’m’;
y = &x;
41
z = &y;
Here, y points to the char x that stores ‘m’, and z points to the pointer y. Example:
#include <iostream>
int main() {
cout << "\nValue of y (Pointer to x): " << (void*)y << endl;
cout << "\nValue of z (Pointer to pointer y): " << (void*)z << endl;
cout << "Dereferencing z (*z) gives y's address: " << (void*)*z << endl;
cout << "Double dereferencing **z gives x's value: " << **z << endl;
**z = 'A';
cout << "\nAfter modifying **z, value of x: " << x << endl;
return 0;
Void Pointers
C++ Void pointers are special pointers that represent the absence of type. They point to a value with no
type, so there are undetermined length and undetermined dereferencing properties. Therefore, void
pointers in C++ are highly flexible as they can point to any data type. Void pointers can’t be
dereferenced
indirectly and must be first transformed into another pointer type pointing to a concrete data type
before
#include <iostream>
int main() {
int a = 42;
double b = 3.14;
ptr = &a;
cout << "Value of a through void pointer: " << *(static_cast<int*>(ptr)) << endl; // Storing a double's
address
ptr = &b;
cout << "Value of b through void pointer: " << *(static_cast<double*>(ptr)) << endl; // Storing a
char's address
ptr = &c;
cout << "Value of c through void pointer: " << *(static_cast<char*>(ptr)) << endl;
return 0;
Invalid Pointers
A pointer must point to a valid address but not necessarily to a valid element. Such a pointer is known as
an invalid pointer. An uninitialized pointer is also an invalid pointer. int *ptr1;
int arr[9];
As you can see, ptr1 is uninitialized, making it an invalid pointer. Also, as ptr2 is out of bounds of arr, it
is an invalid pointer, too. You must know that an invalid pointer may not necessarily raise a compile
error.
NULL Pointers
In C++, null pointers don’t indicate an invalid address but may point nowhere. We can assign a pointer as
int *ptr1 = 0;
We can create a pointer variable not only for built-in types, such as float, int, double, etc. but also for
user-defined types like structure. Example: Using a Structure Pointer with Static Memory Allocation
#include <iostream>
// Define a structure
struct Employee {
int id;
char name[50];
float salary;
};
int main() {
ptr = &emp;
return 0;
In C++, we can use the arrow operator to access member functions and member variables of a structure
#include <iostream>
// Define a structure
struct Employee {
int id;
char name[50];
float salary;
void display() {
};
int main() {
ptr->id = 101;
ptr->salary = 85000.50;
delete ptr;
return 0;
Advantages of Pointers
They allow us to return multiple values from functions. They reduce the code while enhancing
performance. They can be used to retrieve strings, arrays, trees, functions, and structures. They enable
us to access a memory location in the memory of the computer.
Chapter 7
1. Structure (struct)
A structure is a user-defined data type used to group variables of different types under one name.
Syntax:
cpp
CopyEdit
struct TypeName {
// members
};
Example:
cpp
CopyEdit
struct Person {
string name;
int age;
float salary;
};
cpp
CopyEdit
Person x;
x.age = 25;
3. Structures and Functions
• Passed by value
• Passed by reference
Example:
cpp
CopyEdit
void display(Person p) {
Initialization:
cpp
CopyEdit
Assignment:
cpp
CopyEdit
Person p2;
5. Nested Structures
Example:
cpp
CopyEdit
struct Person {
string name;
int age;
};
struct Employee {
Person p;
string dept;
};
cpp
CopyEdit
Employee e;
6. Array of Structures
Example:
cpp
CopyEdit
Person persons[5];
persons[0].age = 25;
7. Pointers to Structures
You can use pointers to access structure members with the arrow operator (->).
Example:
cpp
CopyEdit
Important Operator:
8. typedef Used to define new type names (aliases) for existing data types.
Syntax:
cpp
CopyEdit
Example:
cpp
CopyEdit
9. union
A union allows different members to share the same memory location. Only one member can store a
value at a time.
Syntax:
cpp
CopyEdit
union Data {
int i;
float f;
char c;
};
Advanced Example:
cpp
CopyEdit
union Mix {
long l;
char c[4];
};
Advantages of Structures:
Disadvantages of Structures:
Advantages of Unions:
• Useful when different representations are needed for the same data.
• Allows multiple ways to access the same memory (e.g., byte-wise, word-wise).
Disadvantages of Unions:
https://www.wscubetech.com/resources/cpp/pointers
https://www.simplilearn.com/tutorials/cpp-tutorial/pointers-in-
https://www.w3schools.com/cpp/cpp_pointers.
https://www.programiz.com/cpp-programming/pointers