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

Computer Programming

The document outlines a course on Computer Programming at Arba Minch University, detailing the structure and content of the curriculum across multiple units. It covers fundamental concepts such as computer organization, data types, control statements, functions, arrays, strings, and pointers, with a focus on C++ programming. The document also includes a list of group members and submission details for the assignment.

Uploaded by

tyoseph00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views52 pages

Computer Programming

The document outlines a course on Computer Programming at Arba Minch University, detailing the structure and content of the curriculum across multiple units. It covers fundamental concepts such as computer organization, data types, control statements, functions, arrays, strings, and pointers, with a focus on C++ programming. The document also includes a list of group members and submission details for the assignment.

Uploaded by

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

ARBAMINCH UNIVERSITY

FACULTY OF COMPUTING AND SOFTWARE


ENGINEERING

“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

Submission Date: 29/09/2017E.C.


Table of Content
1.UNIT ONE................................................................................................................................. 2
INTRODUCTION.............................................................................................................................2
Overview of Computers and Computer Organization. ................................................................ 2
Numbering system........................................................................................................................2
Types of codes.............................................................................................................................. 4
BCD (Binary-Coded Decimal) code :.............................................................................................. 4
ASCII (American Standard Code Information Interchange) code :................................................ 4
EBCDIC (Extended Binary Coded Decimal Interchange Code) code ............................................. 5
Gray code ......................................................................................................................................5
Excess-3 code ............................................................................................................................... 5
2.UNIT 2 ........................................................................................................................................6
FUNDAMENTALS OF BASIC IN C++................................................................................................6
Data Types and Variables..............................................................................................................8
Operators, expressions and statements....................................................................................... 9
Fundamental Variable types. ..................................................................................................... 10
3.UNIT 3 ...................................................................................................................................... 11
CONTROL STATEMENTS............................................................................................................... 11
Sequential Statements.................................................................................................................12
Selection Statements ...................................................................................................................12
The if Statement...........................................................................................................................12
Types of Control Statements:.......................................................................................................12
Conditional Statements:...............................................................................................................12
Looping Statements:.................................................................................................................... 15
Jump Statements:........................................................................................................................17
4.UNIT 4 ...................................................................................................................................... 18
FUNCTIONS................................................................................................................................. 18
Declaring, defining and calling functions Declaring function......................................................18
Parameters or Arguments......................................................................................................... 20
Recursion................................................................................................................................... 21
Function Overloading................................................................................................................ 22
5. UNIT 5 .................................................................................................................................... 26
ARRAYS AND STRINGS............................................................................................................... 26
Initializing Arrays........................................................................................................................27
Strings of Characters................................................................................................................. 28
Converting strings to other types..............................................................................................29
Multidimensional Arrays...........................................................................................................31
6.UNIT-6 ......................................................................................................................................33
POINTERS..................................................................................................................................33
Declaring Pointers:................................................................................................................... 34
References and Pointers...........................................................................................................35
Array Name as
Pointers....................................................................................................................................36
Pointer Expressions and Pointer Arithmetic ...........................................................................37
Pointers to Pointers.................................................................................................................40
Void Pointers.......................................................................................................................... 41
Invalid Pointers.......................................................................................................................42
NULL Pointers........................................................................................................................ 43
Advantages of Pointers..........................................................................................................45
7.Unit -7 ………………………………………………………………………………………………………………………………..46

Structure………………………………………………………………………………………………………………………………46

Functions………………………………………………………………………………………………………………………………46

Arrays…………………………………………………………………………………………………………………………………..47

Pointers……………………………………………………………………………………………………………………………….48

typedef & union………………………………………………………………………………………………………………………..


………48

Comparison…………………………………………………………………………………………………………………………49

Pros & Cons………………………………………………………………………………………………………………………..51

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

divided into six logical units or sections:

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:

Decimal system (base 10) - uses 10 digits (0-9)

Binary system (base 2) - uses 2 digits (0 and 1)

Octal system (base 8) - uses 8 digits (0-7)

Hexadecimal system (base 16) - uses 16 digits (0-9 and A-F)

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

number systems in computers:

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

computer. Arithmetic operations:


Computers use the binary number system to perform arithmetic operations, such as addition,
subtraction, multiplication, and division. These operations are performed using circuits and logic gates
that manipulate

binary values. Memory addressing:

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

can address up to 4 GB of memory. Computer programming:

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

Types of number system in computer:

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

BCD (Binary-Coded Decimal) code :

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.

Extended ASCII series starts from 80h to FFh.

EBCDIC (Extended Binary Coded Decimal Interchange Code) code

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

FUNDAMENTALS OF BASIC IN C++

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

you understand all the basic concepts of C++. C++ Syntax

Let's break up the following code to understand it better:

Example

#include <iostream>

using namespace std;

int main() {

cout << "Hello World!";

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:

int main () { cout << "Hello World! "; return 0; }

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>

using namespace std;

int main()

int firstNumber, secondNumber, sumOfTwoNumbers;

cout << "Enter two integers: ";

cin >> firstNumber >> secondNumber;

sumOfTwoNumbers = firstNumber + secondNumber;

cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;

return 0;

C++ Statements

A computer program is a list of "instructions" to be "executed" by a computer. In a programming


language, these programming instructions are called statements. C++ Output (Print Text)

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

with its data type. The syntax for a variable

flowchart is a graphical representation of an algorithm. Play a vital role in the programming of a

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.

Operators, expressions and statements

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 (!, &&, ||):

Increment/Decrement Operators: (++) and (--)

Conditional Operator (?:)

Comma Operator (,). Example:

#include <iostream.h>

using namespace std;

int main()

int divisor, dividend, quotient, remainder;

cout << "Enter dividend: ";

cin >> dividend;


cout << "Enter divisor: ";

cin >> divisor;

quotient = dividend / divisor;

remainder = dividend % divisor;

cout << "Quotient = " << quotient << endl;

cout << "Remainder = " << remainder;

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

development and can not be changed. Selection Statements

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.

Types of Control Statements:


Conditional Statements:

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)

cout<<”you are an adult”;

13

if-else: Executes one block if a condition is true and another if it's false. #include <iostream.h>

using namespace std;

int main()

{ int n;

cout << "Enter an integer: ";

cin >> n;

if ( n % 2 == 0)

cout << n << " is even.";

else

cout << n << " is odd.";

return 0;

if-else if-else: Allows checking multiple conditions in sequence. #include <iostream.h>

using namespace std;

int main()

int year;

cout << "Enter a year: ";

cin >> year;


if (year % 4 == 0)

if (year % 100 == 0)

if (year % 400 == 0)

cout << year << " is a leap year.";

else

cout << year << " is not a leap year.";

else

cout << year << " is a leap year.";

else

cout << year << " is not a leap year.";

return 0;

switch: Selects a code block to execute based on the value of a variable. #include <iostream.h>

using namespace std;

int main()

{ int year;

cout << "Enter a year: ";

cin >> year;

if (year % 4 == 0)

if (year % 100 == 0)
{

if (year % 400 == 0)

cout << year << " is a leap year.";

else

15

cout << year << " is not a leap year.";

else

cout << year << " is a leap year.";

else

cout << year << " is not a leap year.";

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>

using namespace std;

int main()

int n, sum = 0;

cout << "Enter a positive integer: ";

cin >> n;

for (int i = 1; i <= n; ++i) {

sum += i;

}
cout << "Sum = " << sum;

return 0;

while: Repeats a block as long as a condition is true. #include <iostream.h>

using namespace std;

int main()

{ int n1, n2;

cout << "Enter two numbers: ";

cin >> n1 >> n2;

while(n1 != n2)

{ if(n1 > n2)

n1 -= n2;

else

n2 -= n1;

cout << "HCF = " << 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>

using namespace std;

int main(){

age=-1;

do { cout<<“\n enter your valid age [between 0 and 130]:”;

cin>>age; }

while(age < 0 || age > 130)


}

Jump Statements:

These transfer control to another part of the program. break: Terminates a loop or switch statement.
#include <iostream.h>

using namespace std;

int main(){

for(n=10;n>0;n--) {

cout<<n<< “,”;

if(n = = 3) {

cout<< “count down aborted!!”;

break; }

return 0;

continue: Skips the remaining code in the current loop iteration and starts the next iteration. #include
<iostream.h>

using namespace std;

int main()

for(int n=10;n>0;n--) {

if(n==5)

continue; //causes a jump to n—

cout<<n<< “,”; }

goto: Transfers control to a labeled statement (generally discouraged). #include <iostream>

using namespace std;

int main (){

int n=20;
loop:

cout << n << ", ";

n--; if (n>0)

goto loop;

cout << "End!";

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

for passing values to and from the function. Defining a function:

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++

int add(int a, int b) {

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>

using namespace std;

// Defining function that prints given number

void printNum(int n){

cout << n << endl;

int main() {

int num1 = 10;

int num2 = 99;

// Calling printNum and passing both

// num1 and num2 to it one by one

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

unsuccessful execution of the program. Recursion

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>

using namespace std;

void reverse(const string& a);

int main()

string str;

cout << " Please enter a string " << endl;

getline(cin, str);

reverse(str);

return 0;

void reverse(const string& str)


{

size_t numOfChars = str.size();

if(numOfChars == 1)

cout << str << endl;

else

cout << str[numOfChars - 1];

reverse(str.substr(0, numOfChars - 1));

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

at it involves copying the value. Example:

C++

#include <iostream>

using namespace std;

// Arguments are pass by value

void change(int a) {

// Modifying arguments

a = 22;

int main() {

int x = 5;

// Passing x by value to change()

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

useful when you have to pass large size data. Example

#include <iostream.h>

using namespace std;

int main()

int a = 5, b = 10, temp;

cout << "Before swapping." << endl;

cout << "a = " << a << ", b = " << b << endl;

temp = a;

a = b;

b = temp;

cout << "\nAfter swapping." << endl;

cout << "a = " << a << ", b = " << b << endl;

return 0;

Example

C++

#include <iostream>

using namespace std;

// Arguments are pass by value

void change(int& a) {

// Modifying arguments

a = 22;

}
int main() {

int x = 5;

// Passing x by reference to change()

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>

using namespace std;

// Arguments are pass by value

void change(int* a) {

// Modifying arguments

*a = 22;

int main() {

int x = 5;

// Passing address of x to change()

change(&x);

cout << x;

return 0;
}

UNIT 5

ARRAYS AND STRINGS

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

appear around the index right after the name

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

declaration one must define:

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:

DataTypename arrayname [array size];

#include <iostream>

using namespace std;


int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

for (int n : numbers) {

cout << n << " ";

cout << "\nThe numbers are: ";

for (int i = 0; i < 5; ++i) {

cout << numbers[i] << " ";

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

filled with zeros. Thus, if in the global scope we declare:

int day [5];

#include <iostream>

int main() {

double numbers[] = {1.2, 2.3, 3.4, 4.5, 5.6};

double sum = 0;

int size = sizeof(numbers) / sizeof(numbers[0]);

for (int i = 0; i < size; i++) {

sum += numbers[i];

}
double average = sum / size;

std::cout << "Sum: " << sum << std::endl;

std::cout << "Average: " << average << std::endl;

return 0;

Strings of Characters

What are Strings?

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

make strings of single characters. #include<iostream>

using namespace std;

int main()

string name ="GIZACHEW GIGA";

int sec=6;

string date="22/08/2017 EC";

cout << "programming exam. " << endl;

cout <<"computer programming. " <<endl;

cout <<"My name is: "<<name<<endl;


cout <<"section: " <<sec<<endl;

cout <<"Date: " << date<<endl;

return 0;

Converting strings to other types

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

number characters to be appended

#include <iostream>

using namespace std;

int main() {

30

char str1[100], str2[50];


cout << "Enter first string: ";

cin.getline(str1, 100);

cout << "Enter second string: ";

cin.getline(str2, 50);

int i, j;

// Finding length of str1

for (i = 0; str1[i] != '\0'; i++);

// Appending str2 to str1

for (j = 0; str2[j] != '\0'; j++, i++) {

str1[i] = str2[j];

str1[i] = '\0';

cout << "Concatenated String: " << str1 << endl;

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

number characters to be copied

#include <iostream>

#include <cstring> // Required for strcpy()

using namespace std;

int main() {

char str1[100], str2[100];


// Taking input from the user

cout << "Enter a string: ";

cin.getline(str1, 100);

// Copying using strcpy()

strcpy(str2, str1);

cout << "Copied String: " << str2 << endl;

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

size is the number characters to be compaired

Both string compare functions returns three different values:

o Returns 0 is the strings are equal

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

Elements in two-dimensional array in C++ Programming

Three-dimensional arrays also work in a similar way. For example:

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

Multidimensional Array Initialization

Like a normal array, we can initialize a multidimensional array in more than one way. 1. Initialization of
two-dimensional array

int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same array elements is

given below:

int test[2][3] = { {2, 4, 5}, {9, 0, 19}};

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

// of an initialised two dimensional array

#include <iostream>

using namespace std;

int main() {

int test[3][2] = {{2, -5}, {4, 0}, {9, 1}}; // use of nested for loop

// access rows of the array

for (int i = 0; i < 3; ++i) {

// access columns of the array

for (int j = 0; j < 2; ++j) {

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++:

& the address of operator

* the dereference operator

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:

int *ip; // pointer to an integer

char *ch // pointer to character

float *fp; // pointer to a float

double *dp; // pointer to a double

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;

int *ptr; // pointer to an address holding int data


Address in C++

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>

using namespace std;

int main() {

int a = 10;

int *ptr = &a; // Pointer stores the address of variable 'a'

cout << "Value of a: " << a << endl;

cout << "Address of a: " << &a << endl;

cout << "Pointer ptr stores address: " << ptr << endl;

cout << "Value at address stored in ptr (*ptr): " << *ptr << endl;

*ptr = 20; // Changing the value of 'a' through pointer

cout << "New value of a after modifying through pointer: " << a << endl;

return 0;

How to Use a Pointer in C++?

Below, we have explained how to use a C++ pointer:

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.

References and Pointers

We can pass C++ arguments to function using the following three ways:

Call-By-Value

Call-By-Reference with a Pointer Argument

Call-By-Reference with a Reference Argument


Example: Call by Value with a Pointer

#include <iostream>

using namespace std;

// Function that accepts a pointer but does NOT modify the actual pointer

void modifyValue(int *ptr) {

*ptr = 50; // Modifies the value at the address

ptr = nullptr; // This does NOT affect the original pointer in main()

int main() {

int num = 10;

int *ptr = &num; // Pointer storing the address of num

cout << "Before function call: " << num << endl;

modifyValue(ptr); // Call by value (pointer is passed by value)

cout << "After function call: " << num << endl;

cout << "Pointer in main after function call: " << ptr << endl; // Still holds original address

return 0;

Array Name as Pointers

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>

using namespace std;

int main() {

int arr[] = {10, 20, 30, 40, 50};

// Array name as a pointer

int *ptr = arr;


cout << "Using pointer arithmetic on array:\n";

for (int i = 0; i < 5; i++) {

cout << "Element " << i << " (Value: " << *(ptr + i) << ", Address: " << (ptr + i) << ")\n";

// Accessing array using array name as pointer

cout << "\nUsing array name directly:\n";

cout << "First element (arr[0]): " << *arr << endl;

cout << "Second element (arr[1]): " << *(arr + 1) << endl;

// Modifying array values using pointer arithmetic

*(arr + 2) = 99;

cout << "\nAfter modifying arr[2] using pointer: " << arr[2] << endl;

return 0;

Pointer Expressions and Pointer Arithmetic

We can perform a few arithmetic operations on pointers, which we have discussed below:

incremented ( ++ ) and decremented ( — )

Adding an integer to a pointer ( + or += )

Subtracting an integer from a pointer ( – or -= )

Difference between two pointers (p1-p2)

Example:

#include <iostream>

using namespace std;

int main() {

int arr[] = {10, 20, 30, 40, 50};

int *p1 = arr; // Points to the first element (arr[0])


int *p2 = arr + 3; // Points to the fourth element (arr[3])

cout << "Initial pointer values:\n";

cout << "p1 points to: " << *p1 << " at address " << p1 << endl;

cout << "p2 points to: " << *p2 << " at address " << p2 << endl;

// Incrementing pointer

p1++;

cout << "\nAfter p1++ (increment):\n";

cout << "p1 now points to: " << *p1 << " at address " << p1 << endl;

// Decrementing pointer

p2--;

cout << "\nAfter p2-- (decrement):\n";

cout << "p2 now points to: " << *p2 << " at address " << p2 << endl;

// Adding an integer to a pointer

p1 += 2;

cout << "\nAfter p1 += 2:\n";

cout << "p1 now points to: " << *p1 << " at address " << p1 << endl;

// Subtracting an integer from a pointer

p2 -= 1;

cout << "\nAfter p2 -= 1:\n";

cout << "p2 now points to: " << *p2 << " at address " << p2 << endl;

// Pointer difference

int diff = p2 - p1;

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

using namespace std;

int main() {

int arr[3][3] = {

{1, 2, 3}, {4, 5, 6}, {7, 8, 9}

};

cout << "Accessing 2D array using pointer notation:\n";

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

cout << "arr[" << i << "][" << j << "] = " << *(*(arr + i) + j) << " ";

cout << endl;

cout << "\nAddress demonstration:\n";

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;

Pointers and String Literals

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>

using namespace std;

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

// Pointer Arithmetic to print the string character by character

cout << "\nTraversing string using pointer arithmetic:\n";

while (*str) { // Loop until null terminator is reached

cout << *str << " ";

str++; // Move to the next character

// Reset pointer to original position

str = "Hello, World!";

// Attempting to modify string literal (Undefined behavior!)

// str[0] = 'h'; // ❌ ERROR: Modifying string literal is not allowed

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>

using namespace std;

int main() {

char x = 'm'; // Character variable

char *y = &x; // Pointer to character

char **z = &y; // Pointer to pointer

cout << "Value of x: " << x << endl;

cout << "Address of x (&x): " << (void*)&x << endl;

cout << "\nValue of y (Pointer to x): " << (void*)y << endl;

cout << "Dereferencing y (*y): " << *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;

// Modifying value of x using pointer to pointer

**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

they are dereferenced. Example:

#include <iostream>

using namespace std;

int main() {

int a = 42;

double b = 3.14;

char c = 'X'; // Void pointer declaration

void* ptr; // Storing an integer's address

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];

int *ptr2 = arr+10;

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

NULL using the following two methods:

int *ptr1 = 0;

int *ptr2 = NULL;

C++ Pointers to Structure

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>

using namespace std;

// Define a structure

struct Employee {

int id;

char name[50];

float salary;

};

int main() {

// Declare a structure variable with Indian names

Employee emp = {101, "Rajesh Kumar", 75000.75};

// Declare a pointer to structure


Employee *ptr;

// Assign the address of structure variable to pointer

ptr = &emp;

// Access structure members using pointer

cout << "Employee Details using Structure Pointer:\n";

cout << "ID: " << ptr->id << endl;

cout << "Name: " << ptr->name << endl;

cout << "Salary: ₹" << ptr->salary << endl;

return 0;

Arrow (->) Operator

In C++, we can use the arrow operator to access member functions and member variables of a structure

variable through a pointer. Example:

#include <iostream>

using namespace std;

// Define a structure

struct Employee {

int id;

char name[50];

float salary;

// Function inside structure

void display() {

cout << "ID: " << id << endl;

cout << "Name: " << name << endl;

cout << "Salary: ₹" << salary << endl;


}

};

int main() {

// Dynamically allocate memory for structure

Employee *ptr = new Employee;

// Assign values using the pointer and arrow operator

ptr->id = 101;

strcpy(ptr->name, "Amit Verma");

ptr->salary = 85000.50;

// Access structure members using arrow operator

cout << "Employee Details:\n";

ptr->display(); // Calling function using arrow operator

// Free allocated memory

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

User Defined Data Types in C++

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;

};

2. Accessing Structure Members

Use the dot operator (.) to access structure members:

cpp

CopyEdit

Person x;

x.age = 25;
3. Structures and Functions

Structure variables can be:

• Passed by value

• Passed by reference

• Returned from functions

Example:

cpp

CopyEdit

void display(Person p) {

cout << p.name;

4. Structure Initialization and Assignment

Initialization:

cpp

CopyEdit

Person p1 = {"John", 30, 4000.5};

Assignment:

cpp

CopyEdit

Person p2;

p2 = p1; // Only works if types match

5. Nested Structures

Structures can contain other structures as members.

Example:
cpp

CopyEdit

struct Person {

string name;

int age;

};

struct Employee {

Person p;

string dept;

};

Accessing Nested Members:

cpp

CopyEdit

Employee e;

cout << e.p.name;

6. Array of Structures

Used to handle multiple records efficiently.

Example:

cpp

CopyEdit

Person persons[5];

persons[0].age = 25;

Used in loops to store and display multiple structure records.

7. Pointers to Structures
You can use pointers to access structure members with the arrow operator (->).

Example:

cpp

CopyEdit

Person x = {"Alice", 28, 3200.0};

Person *ptr = &x;

cout << ptr->name; // or (*ptr).name

Important Operator:

• ptr->member is equivalent to (*ptr).member

8. typedef Used to define new type names (aliases) for existing data types.

Syntax:

cpp

CopyEdit

typedef existing_type new_type_name;

Example:

cpp

CopyEdit

typedef unsigned int WORD;

typedef char* strt;

typedef char field[50];

Useful for simplifying long type names and improving readability.

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;

struct { short hi, lo; } s;

char c[4];

};

Advantages and Disadvantages

Advantages of Structures:

• Groups related data under one name.

• Can hold different data types.

• Easy to pass to functions.

• Improves code readability and maintenance.

• Supports nesting and arrays.

Disadvantages of Structures:

• Cannot contain member functions (unless using classes).

• No data hiding or encapsulation.

• Cannot inherit like classes.


• Memory is allocated separately for each member (less efficient than unions in some cases).

Advantages of Unions:

• Saves memory by sharing space among members.

• 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:

• Only one member can store a value at a time.

• Risk of data corruption if accessed incorrectly.

• Harder to debug due to shared memory.

• No type safety; programmer must manage which member is valid.


References

General students module(power point)

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

You might also like