0% found this document useful (0 votes)
5 views

Computer Programming

The document provides an overview of data types in C++, detailing primitive and reference data types along with their memory sizes. It explains the concept of variables, identifiers, and the differences between global and local variables, including how to access them using the scope resolution operator. Additionally, it covers constants, operators, and flow control in programming, emphasizing their roles in data manipulation and program structure.

Uploaded by

Ephrem Alene
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Computer Programming

The document provides an overview of data types in C++, detailing primitive and reference data types along with their memory sizes. It explains the concept of variables, identifiers, and the differences between global and local variables, including how to access them using the scope resolution operator. Additionally, it covers constants, operators, and flow control in programming, emphasizing their roles in data manipulation and program structure.

Uploaded by

Ephrem Alene
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

COMPUTER PROGRAMMING

CHAPTER TWO bytes. For example, sizeof(int) will give you the
size of an integer on your specific system.
SIZE OF A VARIABLE

The size of a variable depends on its data type. PRIMITIVE AND REFERENCE DATA
Here is a list of common data types in C++ along TYPES
with their corresponding memory sizes :-

1. bool: Occupies 1 byte of memory.


Primitive Data Type:
2. char: Occupies 1 byte of memory. Primitive data types in programming represent
3. unsigned char: Occupies 1 byte of the basic building blocks for storing and
memory. manipulating data. These data types are
4. Short int : Occupies 2 bytes of memory. predefined by the programming language and are
5. unsigned short: Occupies 2 bytes of typically used to represent simple values.
memory. Examples of primitive data types include integers,
6. int: Typically occupies 4 bytes of memory. floating-point numbers, characters, and booleans.
7. unsigned int: Typically occupies 4 bytes of
memory. For example :-

8. long: Typically occupies 4 bytes of • int is a primitive data type used to store
memory (may vary on different systems). whole numbers.
9. unsigned long: Typically occupies 4 bytes • float is a primitive data type used to store
of memory (may vary on different decimal numbers.
systems). • char is a primitive data type used to store
10.float: Typically occupies 4 bytes of single characters.
memory. • bool is a primitive data type used to store
11.double: Typically occupies 8 bytes of boolean values (true or false).
memory.
Primitive data types have fixed sizes and
12.long double: Typically occupies 8 or more
predefined operations that can be performed on
bytes of memory (may vary on different
them. They are directly supported by the
systems).
programming language and have straightforward
It's important to note that the memory size of a memory representations.
data type can vary depending on the compiler
and system architecture. The sizes mentioned Reference Data Type:
above are typical sizes for common platforms, but A reference data type, also known as a reference
they are not guaranteed to be the same in all type, is a data type that refers to an object's
environments. Additionally, the size of some memory address rather than directly storing its
types, such as long and long double, may vary value. In simpler terms, a reference data type
between different systems. stores a reference or a "pointer" to an object
Keep in mind that the actual memory usage can rather than the object itself. This allows multiple
be influenced by factors like alignment and variables to refer to the same object, enabling
padding requirements imposed by the compiler sharing and manipulation of complex data
and system architecture. To get the precise size structures.
of a specific data type on your system, you can Reference data types are typically used to work
use the sizeof operator, which returns the size in with complex data structures such as arrays,
strings, and objects. They provide flexibility and
dynamic memory management. Examples of 2. Identifiers should not begin with a
reference data types include arrays, strings, and digit.
classes.
• Valid: num1, _value
For example:
• Invalid: 1var, 3_sum
• An array is a reference data type that can 3. Keywords (reserved words) in C++
store multiple values of the same type. cannot be used as identifiers.
• A string is a reference data type used to
represent a sequence of characters. • Valid: total, value
• A class is a user-defined reference data • Invalid: int, return
type that encapsulates data and behaviors. 4. C++ is case-sensitive, meaning that
lowercase and uppercase letters are
Reference data types allow for more complex data
considered different.
structures and support operations like copying,
modifying, and sharing data. They have a more • Valid: age, Age
dynamic nature compared to primitive data types • Invalid: var1, VAR1
and require special handling, such as memory
5. Identifiers cannot match any of the
allocation and deallocation.
reserved keywords in the C++
In summary, primitive data types represent basic language or specific keywords of your
values like numbers and characters, while compiler.
reference data types refer to objects by their
memory addresses. Primitive data types are • Reserved keywords include
simple and directly supported by the words like if, while, for, class,
programming language, while reference data void, and many others. You
types enable more complex data structures and cannot use these as identifiers.
require special handling.
VARIABLES IN C++

IDENTIFIERS IN C++ A variable in programming is like a reserved


space in the computer's memory that can hold
An identifier is a name given to a program information. It is used to store data values that
element such as a variable, function, array, can be used in computations and operations
structure, or class. It is like a natural name within a program. Variables have three important
given by the programmer, such as "Ahmed" properties:
or "Elias". 1. Data Type: A variable has a data type,
For example, consider the statement: int d; In which determines the type of data it can
this case, d is the identifier for a variable. hold. For example, integer, floating-point
number, or character. The data type also
To create valid identifiers, you need to follow certain determines the size of memory reserved
rules :- for the variable. Different data types have
1. Variable identifiers should always different properties and memory
begin with a letter or an underscore requirements.

(_). 2. Name: Each variable has a name that acts


as a unique identifier for that particular
• Valid: myVar, _count
reserved memory location. The name is
• Invalid: 5g, @value
used to refer to the value stored in the
variable. It is like a label or tag given to can be used and modified anywhere in
the memory location. the program.

3. Value: A variable holds a value, which 2. Local Variables: Local variables are
can be changed during the execution of a declared within a specific block of code,
program. Initially, a variable may be such as within a function or a loop.
assigned an initial value, and later it can These variables have a local scope,
be updated by assigning a new value to meaning they are only accessible within
it. the block where they are declared. Local
variables exist only during the execution
To use a variable in C++, we need to declare it
of the block in which they are declared.
first. Declaring a variable means specifying its
Once the block is exited, the local
data type and giving it a name. The syntax for
variables are destroyed and their values
declaring a variable is: data_type variable_name;
are no longer accessible.
For example, to declare an integer variable
Example :-
named z, we write: int z; This statement reserves
a space in the computer's memory called z,
which can hold only integer values.

Similarly, to declare a floating-point variable


named g, we write: float g; This statement
reserves a space in the memory called g, which
can hold floating-point numbers.

Multiple variables can be declared at the same


time by separating their names with commas: For
example, int a, v, s; This is the same as
declaring three separate variables: int a;, int v;,
int s;

GLOBAL AND LOCAL VARIABLES


In this code, num1 is a global variable because it
The scope of a variable refers to the area or
is declared outside of any function. It can be
block of code in a program where the variable
accessed from both the add function and the
can be accessed and used. The scope is defined
main function.
by the opening and closing braces ({ }) in C++.
Inside the add function, num2 is a local variable
In C++, variables can be declared anywhere in
because it is declared within the function's block.
the source code, but they should be declared
It is only accessible within the add function.
before they are used. The scope determines where
a variable is visible and accessible within the Similarly, z is a local variable within the add
program. function. It is only accessible within the block
where it is declared. This means that trying to
There are two main types of variable scopes:
access z outside the add function, such as in the
1. Global Variables: Global variables are main function, would result in an error.
declared outside of any function, typically
LOCAL VARIABLE AND GLOBAL VARIABLE WITH
at the beginning of the code before any
THE SAME NAME
functions are defined. These variables
have a global scope, meaning they can be In C++, if you have a local variable and a global
accessed from any part of the code, variable with the same name, you can suppress
including all functions. Global variables
the local variable and access the global variable So, by using the scope resolution operator (::),
using the scope resolution operator (::). you can suppress the local variable and access
the global variable with the same name.
The scope resolution operator allows you to
specify the scope from which you want to access CONSTANT IN C++
a variable. To access the global variable with the
Constants are fixed values that do not change
same name as a local variable, you prepend the
during the execution of a program. In C++, there
variable name with the scope resolution operator
are two types of constants: literal constants and
followed by the scope you want to access (in this
symbolic constants.
case, the global scope).
literal constants
Here's an example to illustrate how to suppress
the local variable and access the global variable A literal constant is a value that is directly typed
with the same name: into the program where it is needed. It is a fixed
value that is written directly in the code. For
example, in the statement int num = 43;, the
value 43 is a literal constant.

Program Explanation:

The given program demonstrates the use of a


literal constant called x, which is later changed
in the program

In this example, we have a global variable named


num with a value of 100. Inside the example
function, we declare a local variable also named
num with a value of 50.

To differentiate between the local and global


variables, we use the scope resolution operator
(::) to access the global variable. By writing In this program, we include the necessary header
::num, we are explicitly referring to the global file iostream and use the namespace std;
variable num. Without the scope resolution statement for convenience.
operator, num refers to the local variable within
Inside the main function, we declare and
the function.
initialize two floating-point variables, x and y.
When we run the program, the output will be: The initial value of x is 43.5, which is a literal
constant directly typed into the program.
Local variable: 50
Later in the program, we assign a new value to x
Global variable: 100
using the assignment statement x = 7.8;. This
changes the value of the literal constant x from
43.5 to 7.8.
We then calculate the sum of x and y and store assign it the value 7.4. We calculate the sum of x
it in the variable sum. Finally, we display the and y and display the result.
result using the cout statement.
Note: In the second program, the line x = 7.8; is
When we run the program, the output will be: commented out because it would result in an
error. Constants declared using const cannot be
The sum of x and y is 15.2
modified once they are initialized.
Symbolic Constants
Both programs demonstrate the use of constants
Symbolic Constant (Defined Constants using to store fixed values that remain constant
#define): throughout the program.

Symbolic constants are constants represented by a OPERATORS IN C++


name in C++. They are defined using the #define
preprocessor directive. Once defined, they cannot Operators in C++ are symbols that perform
be changed. The format for defining a symbolic specific actions on one or more operands (values
constant is #define identifier value. or variables). They allow you to manipulate and
perform operations on data within your program.

C++ provides several categories of operators, each


serving a different purpose :-

1. Assignment Operator: The assignment


operator (=) is used to assign a value to a
variable. For example, x = 5; assigns the
value 5 to the variable x.

2. Arithmetic Operators: Arithmetic operators


perform mathematical operations on
operands. They include addition (+),
Declared Constants subtraction (-), multiplication (*), division
(/), and modulus (%). For example, x + y
Declared constants are constants declared using adds the values of x and y.
the const keyword. They allow you to declare
constants with a specific type, similar to 3. Relational Operators: Relational operators
variables. compare the relationship between two
operands. They include less than (<),
greater than (>), equal to (==), not equal
to (!=), less than or equal to (<=), and
greater than or equal to (>=). For
example, x < y checks if x is less than y.

4. Logical Operators: Logical operators are


used to combine and manipulate boolean
(true or false) values. They include logical
AND (&&), logical OR (||), and logical
NOT (!). For example, x && y checks if
In this program, we declare a constant x using both x and y are true.
the const keyword and assign it the value 3.5.
The constant x cannot be changed once it is
5. Increment/Decrement Operators: Increment
(++) and decrement (--) operators are used
initialized. We then declare a variable y and
to increase or decrease the value of an
operand by 1. For example, x++ goals and create complex behaviors in their
increments the value of x by 1. programs.

6. Conditional Operator: The conditional In programming, flow control is typically


operator (?:) is a shorthand way to write sequential, meaning that statements are executed
if-else statements. It allows you to one after another in the order they appear.
conditionally choose a value based on a However, flow control can also involve branching
condition. For example, x > y ? x : y statements, which enable the program to take
returns the value of x if x is greater than different paths based on certain conditions. This
y, otherwise it returns the value of y. is akin to a fork in the road, where the program
decides which direction to take based on specific
7. Comma Operator: The comma operator (,) conditions or user input.
is used to separate multiple expressions. It
evaluates each expression from left to Additionally, flow control can involve repetition
right and returns the value of the or looping, where a block of statements is
rightmost expression. For example, x = 5, executed repeatedly until a certain condition is
y = 10 assigns the value 5 to x and 10 to no longer met. This allows the program to
y. perform tasks iteratively, such as processing a list
of items or repeatedly asking for user input until
8. Sizeof Operator: The sizeof operator a valid response is provided.
returns the size in bytes of a data type or
variable. For example, sizeof(int) returns SELECTION STATEMENT
the size of the integer data type.

Selection statements, also known as conditional


statements, are a type of flow control mechanism
These are some of the common categories of
in programming that allows the program to make
operators in C++. They enable you to perform
decisions and choose different paths of execution
various operations and manipulations on data
based on certain conditions. They enable
within your program.
programmers to selectively execute blocks of code
depending on whether specific conditions are true
or false.
CHAPTER THREE
In simpler terms, think of selection statements as

PROGRAM CONTROL making choices in a program. Just like making


decisions in real life, programming involves
situations where different actions need to be
Flow control refers to the order in which
taken based on certain conditions. Selection
instructions or statements are executed in a
statements provide a way to program these
program. It allows programmers to determine
decisions.
which instructions are executed and when,
thereby influencing the overall behavior and One common type of selection statement is the
outcome of the program. "if statement." It has a condition that is
evaluated, and if the condition is true, the code
In simpler terms, think of flow control as the
block associated with the if statement is executed.
ability to make decisions and control the flow of
If the condition is false, the code block is
a program's execution. It's like being the
skipped, and the program moves on to the next
conductor of an orchestra, deciding when each
statement. This allows the program to selectively
instrument should play and for how long. By
execute specific code based on whether a
strategically organizing and directing the
condition is met or not.
instructions, programmers can achieve specific
For example, let's say we have a program that If needed, you can also extend the if statement
checks if a number is positive. We can use an if with an optional else clause to specify an
statement to make the decision: alternative code block to be executed if the
condition is false:
THE IF STATEMENT

The if statement is a fundamental conditional


statement in programming that allows a program
to execute a block of code only if a certain
condition is true. It provides a way to make
decisions and selectively execute code based on
In this modified example, if the condition age >=
the evaluation of a condition.
18 is true, the first code block will be executed.
The basic syntax of an if statement in most Otherwise, if the condition is false, the else code
programming languages is as follows: block will be executed, and the message "You are
not eligible to vote." will be printed.

The if statement provides a powerful tool for


making decisions and controlling the flow of a
program based on specific conditions. It allows
The condition is an expression that evaluates to programs to be more flexible and adapt to
either true or false. If the condition is true, the different scenarios.
code block following the if statement is executed.
If the condition is false, the code block is
skipped, and the program continues to the next
THE ELSE IF STATEMENT
statement.
In C++, the "else if" statement is used to extend
Here's an example to illustrate the usage of an if the functionality of the "if" statement by allowing
statement in Python: multiple conditions to be evaluated. It provides a
way to test multiple conditions sequentially and
execute different code blocks based on the first
condition that evaluates to true.

The syntax for the "else if" statement in C++ is


as follows:
In this example, the condition being evaluated is
age >= 18, which checks if the value of the
variable age is greater than or equal to 18. If the
condition is true, the code block print("You are
eligible to vote.") will be executed, and the
message "You are eligible to vote." will be
printed. However, if the condition is false, the
code block will be skipped, and nothing will be
printed.

It's important to note that the code block


associated with the if statement is indented. In Here's an example that demonstrates the usage of
most programming languages, indentation is used the "else if" statement in C++:
to define the scope of the code block. All
statements that are indented at the same level
belong to the same block of code.
The syntax for the "switch" statement in C++ is
as follows:

In this example, three different conditions are


evaluated sequentially. If the first condition age
< 18 is true, the code block inside the first "if" Here's an example that demonstrates the usage of
statement will be executed, and the message "You the "switch" statement in C++:
are a minor." will be displayed.

If the first condition is false, the program


proceeds to the next "else if" statement and
checks the second condition age >= 18 && age
< 65. If this condition is true, the code block
inside the second "else if" statement will be
executed, and the message "You are an adult."
will be displayed.

If both the first and second conditions are false,


the program continues to the next "else if"
statement or the final "else" statement, depending
on the number of conditions. The final "else"
statement serves as a fallback option if none of
the previous conditions are true. In this example,
if none of the conditions are satisfied, the
message "You are a senior citizen." will be
displayed.

The "else if" statement allows for more complex


decision-making by providing additional In this example, the variable day is evaluated
conditions to be evaluated after the initial "if" inside the switch statement. The program matches
statement. It helps in creating branching logic the value of day against the provided cases. If a
where different code paths can be followed based match is found, the corresponding code block is
on multiple conditions. executed. For example, if the value of day is 3,
the code block under case 3: will be executed,
and the message "Wednesday" will be displayed.
THE SWITCH STATEMENT
If none of the cases match the value of the
In C++, the "switch" statement is a flow control expression, the code block under the default:
mechanism that allows for multi-way branching label is executed. In this example, if the value of
based on the value of a variable or an day is not 1 to 7, the code block under default:
expression. It provides a concise and structured will be executed, and the message "Invalid day"
way to handle a series of possible values or cases will be displayed.
and execute different code blocks accordingly.
It's important to note that after executing a code code, checks the condition before each iteration,
block associated with a matching case, the break and updates the loop variable after each iteration.
statement is used to exit the switch statement.
Here's an example of a "while" loop in C++ that
Without the break statement, the program will
prints numbers from 1 to 5:
continue to execute the subsequent code blocks
until it encounters a break statement or reaches
the end of the switch statement.

The "switch" statement is useful when there are


multiple cases or conditions to be evaluated
against a single variable or expression. It provides
an alternative to using multiple "if-else" In this example, the condition i <= 5 is
statements, making the code more concise and evaluated before each iteration. As long as the
readable. condition is true, the code block inside the loop
will execute. The loop variable i starts from 1
and increments by 1 after each iteration. The
REPETITION STATEMENT loop continues until i becomes 6, which is when
the condition becomes false.
In simpler terms, a repetition statement in C++
Repetition statements are powerful tools for
allows you to repeat a block of code multiple
automating repetitive tasks and processing data
times. It is also known as a looping statement. It
iteratively. They allow you to efficiently perform
enables you to automate tasks that need to be
actions multiple times without writing the same
performed repeatedly, such as processing a list of
code over and over again.
items or iterating over a range of values.

Think of a repetition statement as a loop that


goes back and repeats a set of instructions until a FOR LOOP
certain condition is met. It's like doing something
over and over again until you achieve a desired In simpler terms, the "for" loop in C++ is a way
outcome. to repeat a block of code for a specific number
of times. It provides a convenient and structured
In C++, there are several types of repetition
approach for performing tasks iteratively.
statements, including the "while" loop, "do-while"
loop, and "for" loop. Think of the "for" loop as a three-step process:
initialization, condition, and update. It's like
The "while" loop repeatedly executes a block of
having a countdown timer that starts at a certain
code as long as a specified condition is true. It
value, checks if the countdown is complete, and
checks the condition before each iteration and
updates the timer after each iteration.
continues looping until the condition becomes
false. The basic syntax of a "for" loop in C++ is as
follows:
The "do-while" loop is similar to the "while"
loop, but it checks the condition after each
iteration. This guarantees that the code block is
executed at least once, even if the condition is
initially false. Here's how the three steps work:
The "for" loop provides a compact way to repeat
a block of code for a specified number of times.
It consists of three parts: initialization, condition,
and update. The loop executes the initialization
1. Initialization: This step is typically used to code as long as a given condition is true. It is a
initialize a loop variable before the loop form of repetition statement that allows you to
starts. It sets the initial value or performs automate tasks that need to be performed until a
any necessary setup. specific condition is no longer met.

2. Condition: This step is a condition that is In simpler terms, think of the while loop as a
checked before each iteration. If the "do this while that is true" statement. It
condition is true, the loop continues continues executing a set of instructions as long
executing the code block. If the condition as a certain condition remains true. It's like a
is false, the loop terminates, and the repeated action that keeps going until a particular
program continues with the next requirement is fulfilled.
statement after the loop.
The while loop consists of a condition and a code
3. Update: This step is executed after each block. The condition is checked before each
iteration. It typically updates the loop iteration, and if it evaluates to true, the code
variable or performs any necessary block is executed. After each iteration, the
modifications for the next iteration. condition is checked again, and the loop
continues as long as the condition remains true.
Here's an example of a "for" loop in C++ that
Once the condition becomes false, the loop
prints numbers from 1 to 5:
terminates, and the program proceeds to the next
statement after the loop.

Here's an example to illustrate the while loop:

In this example:

• The initialization step sets the loop


variable i to 1.
• The condition i <= 5 is checked before
each iteration. As long as it is true, the In this example, the variable count is initialized
loop continues. to 0. The while loop checks if count is less than

• After each iteration, the update i++ 5. If it is true, the code block inside the loop is

increments the value of i by 1. executed. It prints the current value of count and
then increments it by 1 using count++. This
The loop will execute the code block inside the process continues until count reaches 5. Once
curly braces {} for each value of i from 1 to 5. count becomes 5, the condition count < 5
In this case, it will print the numbers 1 2 3 4 5 evaluates to false, and the loop terminates.
to the console.
The output of this example will be:
The "for" loop is commonly used when you know
the number of iterations in advance or when you
want to perform a specific action a fixed number
of times. It provides a concise way to express
repetitive behavior and is widely used in various
programming scenarios.
The while loop allows for flexible repetition, as
WHILE LOOP the number of iterations is determined by the
condition. You can think of it as a continuous
The while loop is a flow control construct in loop that keeps going until a specific condition
programming that repeatedly executes a block of becomes false. Just make sure to include code
within the loop that eventually alters the
condition, ensuring the loop will eventually end Notice that even if the condition count < 5
to avoid an infinite loop. becomes false after the first iteration, the code
block is still executed at least once because the
DO WHILE LOOP condition is checked after the execution of the
block.
In Java, the do-while loop is a flow control The do-while loop is useful when you want to
construct that repeatedly executes a block of code ensure that a block of code is executed at least
at least once, and then continues to execute the once, regardless of the condition. It provides
code as long as a specified condition remains flexibility in scenarios where you need to perform
true. It is a variation of the while loop, but with an action first and then check if it should be
the condition checked after the execution of the repeated.
code block.
THE CONTINUE AND BREAK STATEMENT
In simpler terms, think of the do-while loop as a
"do this, and then keep doing it while that is In C++, the "continue" and "break" statements
true" statement. It ensures that the code block is are flow control statements that allow you to
executed at least once, and then it checks if the modify the behavior of loops.
condition is true to decide whether to continue or
The "continue" statement is used to skip the
stop the loop.
remaining code inside a loop iteration and move
The syntax for the do-while loop in Java is as to the next iteration. When encountered, it
follows: terminates the current iteration and jumps to the
beginning of the next iteration.

Here's an example of using the "continue"


statement in a for loop to print only even
numbers:

In this example, the variable count is initialized In this example, the loop iterates from 1 to 10.
to 0. The do-while loop executes the code block When the condition i % 2 != 0 is true (indicating
inside the do statement, which prints the current an odd number), the "continue" statement is
value of count, and then increments count by 1 encountered, and the code block following it is
using count++. After each iteration, the condition skipped. As a result, only even numbers are
count < 5 is checked. If it evaluates to true, the printed: 2 4 6 8 10.
loop continues and executes the code block again.
The "break" statement, on the other hand, is
If the condition is false, the loop terminates.
used to immediately exit the loop when
The output of this example will be: encountered, regardless of the loop condition. It
provides a way to prematurely terminate the
loop.

Here's an example of using the "break" statement


in a while loop to find the first occurrence of a
specific value:
In the code above, we ask the user to enter a
positive number. If the number is not positive
(less than or equal to zero), we use the goto
statement to transfer control to the error label.
The program then outputs an error message. If
the number is positive, it continues execution and
prints the entered number.

In this example, the loop continues until i Please note that this is just a simple example to
reaches 10. However, when i becomes equal to illustrate the usage of goto. In general, it's
the target value (5 in this case), the "break" recommended to use other control flow structures
statement is encountered. The loop is immediately like if-else or loops to achieve the desired
terminated, and the program continues with the behavior, as they usually make the code more
statements following the loop. As a result, only readable and maintainable.
the numbers 1 2 3 4 are printed. PRE-INCREMENT (++K) AND POST-
Both the "continue" and "break" statements INCREMENT (K++)
provide control over loop execution. The
In C++, both k++ and ++k are increment
"continue" statement allows you to skip specific
operators used to increase the value of a variable.
iterations, while the "break" statement allows you
The main difference between them lies in their
to exit the loop prematurely. These statements
behavior regarding the value used in expressions
are helpful when you need to customize the
and the timing of the increment.
behavior of your loops based on certain
conditions or when you want to optimize the Let's break it down with a simpler explanation
execution flow. and a simple example:

THE GO TO STATEMENT IN C++ 1. k++ (Post-increment):


• The value of k is used in the
In C++, the goto statement is a control flow expression before it is
statement that allows you to transfer the incremented.
program's execution to a labeled statement within • The increment occurs after the
the same function. It is generally considered bad value is used.
practice to use goto because it can make code
• The expression evaluates to the
harder to read and understand. However, I can
original value of k.
provide you with a simple example to
demonstrate how it works. Example:

Here's a clear explanation and an easy-to- int k = 5;


int result = k++; // Post-increment:
understand code example: value of k is used first, then
incremented
// At this point, result = 5 and k = 6

• ++k (Pre-increment):

• The value of k is incremented


before it is used in the expression.
• The increment occurs before the
value is used.
• The expression evaluates to the
updated value of k.
Example: In this case, numbers is the name of the array,
and it can hold 5 integers. Each element in the
int k = 5;
int result = ++k; // Pre-increment: k array can be accessed using its index. For
is incremented first, then its new instance, numbers[0] refers to the first element,
value is used numbers[1] refers to the second element, and so
// At this point, result = 6 and k = 6
on.
In both examples, the final value of k is 6. You can assign values to the array elements by
However, the value of result differs because of using the assignment operator (=) along with the
the difference in the timing of the increment. index. For example:
It's important to note that when k++ or ++k is numbers[0] = 10;
used independently (not as part of an expression),
the difference in behavior may not be noticeable. numbers[1] = 20;
However, when they are used within larger numbers[2] = 30;
expressions or assigned to other variables, the
distinction becomes significant. This assigns the values 10 , 20, and 30 to the
first three elements of the numbers array.

To access the values stored in an array, you can


ARRAY IN C++ use the array name followed by the index of the
element you want to access. For example,
numbers[1] would give you the value 20.
In programming, an array is a data structure that
allows you to store multiple values of the same Arrays are particularly useful when you need to
data type under a single identifier. It provides a perform operations on a collection of values, such
way to represent a collection or a list of values as calculating the sum of all numbers, finding the
in a structured manner. maximum or minimum value, or sorting the
elements.
Imagine you have a list of numbers and you
want to perform some operations on each Arrays provide a convenient way to store and
number. Instead of declaring individual variables manipulate multiple values of the same type.
for each number, which can be tedious and They allow you to work with a group of related
impractical, you can use an array to store all the data in a more efficient and organized manner.
numbers together. By using loops, you can easily iterate over the
elements of an array and perform operations on
An array is like a container that holds a fixed
each element.
number of elements, and each element can be
accessed using its index. The index represents the It's important to note that arrays have a fixed
position of an element within the array, starting size, which is determined at the time of
from 0 for the first element. declaration. Once an array is created, its size
cannot be changed. Therefore, you need to
To declare an array, you specify the data type of
choose an appropriate size that accommodates all
the elements it will hold, followed by the array
the elements you need to store.
name and the size of the array enclosed in square
brackets ([]). For example, to declare an array of Example :- In programming, when you have only
integers that can store 5 numbers, you would a few values, you could declare different
variables for each value. However, if you have
write:
many values, it becomes tedious and impractical
int numbers[5]; to handle them individually. To overcome this
issue, you can use a loop to enter and process
the values.
Let's take the example of entering six numbers In programming, an array is a data structure that
and calculating their sum. Instead of declaring six allows you to group together multiple elements of
individual variables (such as a, b, c, d, e, and f) the same type under a single name. Each element
and handling each value separately, you can use in the array is identified by its unique index or
an array and a loop. position within the array.

Here's an example of how it can be done: Think of an array as a set of labeled boxes,
where each box can hold one piece of data. Each
box is numbered or indexed, starting from 0, to
indicate its position in the array. The index is
like the address of the box that holds a particular
element.

To access a specific element in the array, you use


its index to refer to the corresponding box that
contains that element. You can retrieve or modify
In this code, an array called numbers is declared the data stored in that particular box.
to hold 6 floating-point numbers. The variable For example, consider an array of numbers: [10, 20, 30,
sum is initialized to 0.0, which will be used to 40, 50]. Each number is an element in the array, and they
store the sum of all the numbers. are ordered based on their position and index. The first
element is at index 0, the second element is at index 1,
The loop iterates 6 times, using the variable i as and so on.
the loop counter. In each iteration, the user is
To access the elements in the array, you can use their
prompted to enter a number using cin >>
index. For instance, to retrieve the value 30, you would
numbers[i]. The value entered is then stored in use array[2] because 30 is at index 2 in the array.
the corresponding element of the array numbers. Similarly, to change the value at index 3 to 60, you would
assign array[3] = 60.
After entering all the numbers, the loop adds
each number to the sum variable using sum += Arrays are useful when you need to store and
numbers[i]. This accumulates the sum of all the work with a collection of data items of the same
numbers. type. They provide a convenient way to organize
and access multiple elements using a single
By using an array and a loop, you can easily
identifier and their respective indices.
handle a large number of values without the need
to declare individual variables for each value. The size of an array is determined at the time of
This approach makes your code more concise, declaration, specifying the maximum number of
manageable, and flexible. You can extend it to elements it can hold. The elements in the array
handle any number of values by adjusting the are stored consecutively in memory, making it
loop condition and the size of the array. easy to traverse the array and perform operations
on its elements using loops or other techniques.
Arrays provide a way to store multiple values of
the same type in a single data structure. They Arrays are widely used in programming to handle
allow you to access and manipulate the values lists, store data sets, and facilitate efficient data
using a common identifier and an index. This manipulation. They allow you to efficiently store
eliminates the need to manually create and and retrieve data based on their relative
manage separate variables for each value. positions, providing a structured and ordered way
to work with multiple values.

WHAT’S AN ARRAY
ONE DIMENSIONAL ARRAY
structured and ordered way to store and work
with collections of data in a program.
DECLARATION OF ARRAYS

In programming, when you declare an array, you ACCESSING ARRAY ELEMENTS


specify the type of its elements, give it a name,
and indicate the number of elements it can hold. An array is a data structure that allows you to
The number of elements must be an integer group multiple elements of the same type
value. together. When you declare an array, the
For example, let's say you want to store the compiler reserves a contiguous block of memory
average temperature in Ethiopia for each of the to store the elements. Each element in the array
last 100 years. You can declare an array named is identified by its index or subscript, starting
annual_temp to hold these values, like this from 0 for the first element. If the array has n
elements, the indices range from 0 to n-1.
float annual_temp[100];
To access a specific element in the array, you use
This declaration tells the compiler to allocate the array's identifier followed by the index in
memory for 100 consecutive float variables, square brackets. For example, to set the 15th
which will be used to store the average element of the annual_temp array to 1.5, you
temperature values. Each element in the array would use the following assignment:
will be a float value.
annual_temp[14] = 1.5;
It's good practice to make the size of the array a
Here, the index is 14 because the first element
constant value using the const keyword. This
has index 0, and the 15th element corresponds to
allows for easy modification of the array size in
index 14.
the future if needed. For example:
You can use array elements just like any other
const int NE = 100;
float annual_temp[NE]; variable. Here are some examples:

• Reading a value into an array element:


In this case, NE is a constant variable with a
value of 100, representing the number of cin >> count[i];
elements in the array. By using a constant, you
can easily change the size of the array by Updating an array element:
modifying the value of NE without needing to
count[i] += 5;
modify the rest of the code.

It's important to note that the size of the array This shorthand form is equivalent to count[i] =
must be known at compile time. The compiler count[i] + 5.
needs to allocate the appropriate amount of • Using array elements in conditional
memory based on the size specified. If you were statements:
to use a regular variable for the size, it would
if (annual_temp[j] < 10.0)
not work because the compiler needs to know the
cout << "It was cold this year" << endl;
size in advance to allocate the necessary memory.

By declaring and defining an array, you create a Using a loop to access every element in an array:
fixed-size container that can hold multiple values
for (i = 0; i < NE; i++)
of the same type. Each element in the array has
cin >> annual_temp[i];
its own unique index, starting from 0, which
allows you to access and manipulate individual
elements using their index. Arrays provide a
Here, NE is the number of elements in the
annual_temp array. In this case, the array does not have a specified
You can also calculate various statistics using size, and the compiler will automatically allocate
array elements. For example, to find the average enough space to hold the number of elements in
temperature of the first ten elements in the array: the initialization list. In this example, the primes
array will have seven elements.
sum = 0.0;
for (i = 0; i < 10; i++) If you want to specify the size of the array
sum += annual_temp[i]; explicitly, you can do so. The size must be
av1 = sum / 10; greater than or equal to the number of elements
in the initialization list. For example:
It is good practice to use named constants instead
of literal numbers in your code. By defining a int primes[10] = {1, 2, 3, 5, 7};
constant, such as const int NUM_ELEMENTS =
10, you can easily modify the size or range of In this case, the array primes has a size of ten,
but only the first five elements are initialized
the array without having to change multiple
with the provided values. The remaining elements
occurrences of the number in the code. will be set to their default values (0 in the case
It's important to note that C++ does not check of int).
whether the subscript used to access an array
element is within the valid range. It is the
programmer's responsibility to ensure that the
subscript falls within the range of 0 to n-1.
Accessing elements outside this range can lead to
unpredictable behavior, such as accessing invalid
memory locations or overwriting other variables
or program code. Subscript overflow, which
occurs when you use an index out of range, can
cause errors and unexpected results in your
program.

To avoid subscript overflow, always ensure that


you use valid indices when accessing array
elements and validate user input to prevent out-
of-range access.

By understanding and properly handling array


indices, you can effectively work with arrays and
avoid common programming errors.

INITIALIZING ARRAYS
When initializing an array, you can provide
initial values to the array elements at the time of
declaration. This is done by enclosing the values
in curly brackets {}. For example, to initialize an
array primes with the first few prime numbers,
you can write :- COPYING ARRAYS
int primes[] = {1, 2, 3, 5, 7, 11, 13};
When it comes to copying arrays in C++, you In C++, if we have a class named "Square" to
cannot use the assignment operator (=) directly to represent each square on the chessboard, we can
assign one array to another. Instead, you need to declare a two-dimensional array named "board"
as follows:
copy the elements one by one using a loop.

Let's consider the example you provided: Square board[8][8];

const int SIZE = 10; This declaration creates an array with 8 rows and
int x[SIZE]; 8 columns, representing the 64 squares on the
int y[SIZE];
chessboard. Each element in the array can hold
an object of the "Square" class.
To copy the elements from array y to array x,
you need to iterate over the elements using a Alternatively, we could represent the same
loop and assign each element individually: chessboard using a one-dimensional array with 64
elements:
for (int i = 0; i < SIZE; i++) {
x[i] = y[i]; Square board[64];
}
However, using a one-dimensional array in this
In this loop, the index variable i is used to access case may not correspond as closely to the real-
each element of x and y. The value of y[i] is world chessboard, as the relationship between
assigned to x[i], effectively copying the value rows and columns is not explicitly defined.
from y to x. This process is repeated for each
When accessing elements in a multidimensional
element of the arrays until all elements are
array, each dimension is represented by its
copied.
corresponding subscript. For example, if we want
It's worth noting that using a constant, such as to access the fourth position in the first row of
SIZE, to store the array size is a good practice. the chessboard (assuming the first subscript
This allows you to easily change the size of the represents the row and the second subscript
arrays by modifying the constant value in one represents the column), we would use the
place, rather than having to update all the notation board[0][3]. In this case, the first
occurrences of the size throughout the code. This subscript value is 0 to indicate the first row, and
improves code maintainability and reduces the the second subscript value is 3 to indicate the
risk of missing any updates. fourth column.

Multidimensional arrays can be useful for


Multidimensional Arrays representing complex data structures that have
multiple dimensions, such as matrices, game
boards, or images. They allow you to organize
A multidimensional array is an array that has
and access data in a structured manner using
more than one dimension. Each dimension is
multiple subscripts.
represented by a subscript in the array
declaration. For example, a two-dimensional array INITIALIZATION OF MULTIDIMENSIONAL
has two subscripts, and a three-dimensional array ARRAYS
has three subscripts.
To initialize a multidimensional array, you need
To understand this concept, let's consider the
to assign the values to the array elements in a
example of a chessboard. A chessboard can be
specific order, with the last array subscript
represented as a two-dimensional array, where
changing while the first subscript remains steady.
one dimension represents the rows and the other
dimension represents the columns.
Let's consider an example with an array theArray will automatically determine the size of the array
of type int with dimensions 5 rows and 3 based on the number of elements given.
columns: int theArray[5][3].
For example, the following code initializes an
To initialize this array, you can assign the values integer array x with four elements:
directly in the declaration statement. The values
int x[] = { 1, 2, 3, 4 };
should be assigned in the order of the array
elements, with the first three elements going into In this case, the size of the array is automatically
theArray[0], the next three elements into set to 4, matching the number of initializing
theArray[1], and so on. elements.
Here's an example of initializing the array with However, when working with multidimensional
values: arrays, you cannot omit the size of the array.
int theArray[5][3] = { Each dimension must have a specified size.
{1, 2, 3},
For instance, the following code attempts to
{4, 5, 6},
initialize a two-dimensional array x without
{7, 8, 9},
{10, 11, 12}, specifying the size:
{13, 14, 15} int x[][] = { {1, 2}, {3, 4} };
};

In the above initialization, each row of the array


This will result in a compilation error because
is enclosed in curly braces. The inner braces
the size of the second dimension cannot be
clarify how the numbers are distributed within
determined. Instead, you must provide the size
each row. The values are separated by commas explicitly:
within and between the rows. The entire
initialization is enclosed in curly braces, and it int x[2][2] = { {1, 2}, {3, 4} };
ends with a semicolon.
In this case, the array x is declared as a two-
Note that the use of inner braces is optional but dimensional array with a size of 2 rows and 2
can help clarify the structure of the columns, and it is properly initialized.
multidimensional array initialization.
Here's an example of accessing and printing the
It's important to ensure that the number of values elements of a multidimensional array:
provided matches the size of the array. In this
case, the array has 5 rows and 3 columns, so
there should be a total of 15 values provided in
the initialization. If the number of values doesn't
match or if the initialization is incomplete, the
compiler may generate a warning or an error.

By properly initializing a multidimensional array,


you can set its initial values without the need for
additional assignment statements after declaration.

OMMITING THE ARRAY SIZE

In C++, when initializing a one-dimensional


array, you can omit the size if the number of
initializing elements is provided. The compiler In the above example, the nested for loops
iterate over the elements of the multidimensional
array SomeArray. The indices i and j are used to store the null character. Strings can be
to access and print each element of the array. initialized at the time of declaration, and the
length of the array should accommodate the
string length plus one for the null character.
STRINGS IN C++
STRING OUTPUT
In C++, a string is a sequence of characters. It is
represented as an array of characters, where the To output a string in C++, you can use the cout
last character is a special null character '\0' that object with the insertion operator (<<). For
example
indicates the end of the string. To convert an
array of characters into a string, we append this
cout << "The string s1 is " << s1 << endl;
null character at the end of the character
sequence. This code will print the string stored in the
variable s1. The output will be:
A C++ string is stored as an array of characters,
with each character occupying one element of the s1 :- The string s1 is example
array. Additionally, a null character ('\0') is
added at the end of the string to mark its
termination. So, if a string has n characters, it STRING INPUT
requires an array of size n+1 to store it, allowing
space for the null character. When reading input using cin in C++, spaces,
tabs, and newline characters are used as
For example, consider the string variable s1 separators and terminators. This means that
declared as char s1[10];. It can hold strings of up inputting a string with spaces or multiple words
to nine characters because one element is requires separate input operations. For example:
reserved for the null character.

Strings can be initialized at the time of char firstName[12], lastName[12];


declaration, similar to initializing other variables. cout << "Enter name: ";
For example: cin >> firstName;
cin >> lastName;
• char s1[] = "example"; initializes s1 with cout << "The name entered was " << firstName
the string "example". << " " << lastName;
• char s2[20] = "another example";
initializes s2 with the string "another It's important to note that cin reads only one
example". word at a time, so if a space is encountered
during input, it will terminate reading for that
In memory, these strings would be stored as
particular input operation. If the input string is
follows: longer than the available space in the character
array, it can overwrite adjacent memory, causing
• s1 would be stored as |e|x|a|m|p|l|e|\0|
unexpected errors.
(eight characters including the null
character). To read a string that contains spaces or blanks,
• s2 would be stored as |a|n|o|t|h|e|r| | we can use the cin.get() function instead of
e|x|a|m|p|l|e|\0|?|?|?|?| (sixteen cin. The cin.get() function allows us to read
characters including the null character a string along with spaces. Here's an example:
and additional uninitialized elements).

In summary, a string in C++ is represented as an


array of characters, where the last character is a
null character ('\0') indicating the end of the
string. The array requires one additional element
input, which can lead to a buffer overflow and
unexpected behavior. However, we can use
cin.width() and setw() to limit the number of
characters read by the >> operator.

Here's an example that demonstrates this :-

With cin.get(), we can input a string containing


spaces, and the entire line of input will be stored
in the str variable. It avoids the problem of
terminating input at the first space encountered.

Now, let's consider reading multiple lines of


input. We can modify the cin.get() function to
accept a third argument that specifies the
In this example, setw(MAX) is used to specify the
character at which the input should stop. By
maximum width or number of characters to be
default, this character is the newline character ('\
read from the input. It ensures that the >>
n'). However, we can specify a different character
operator will read at most MAX characters into
as the termination character. Here's an example
the str variable.
spaces using a dollar sign ('$') as the termination
character :-
By using setw() along with cin.width(), we can
prevent a buffer overflow if the user enters a
string longer than the size of the array. Any
characters beyond the specified width will be
discarded, avoiding overflow and ensuring that
the program behaves as expected.

With this modification, we can input multiple


lines of text, and the input will continue until we
enter the specified termination character ('$' in
this case). You must still press the Enter key after
typing the termination character.

In summary, using cin.get() allows us to read


strings with spaces or blanks without terminating
the input at the first space encountered. By
specifying a termination character as the third In this example, cin.width(MAX) is used to set
argument, we can read multiple lines of input the maximum width or number of characters to
until that character is encountered. be read from the input. It ensures that the >>
operator reads at most MAX characters into the
AVOIDING OVERFLOW
str variable.

When we read input using cin, there is a risk of


exceeding the size of the array used to store the
If the user enters a string longer than MAX me, replacing the original content. The output
characters, only the first MAX characters will be will be:
read and stored in the str variable. Any
Note that it's important to ensure that the
additional characters beyond the specified width
destination string has enough space to hold the
will be discarded.
characters from the source string, including the
For instance, if the user enters "Hello, World!" terminating null character.
as the input, and MAX is set to 10, the output
Additionally, there is another function called
will be:
strncpy() that is similar to strcpy(). The strncpy()
You entered: Hello, Wor function allows you to specify the number of
characters to copy. Here's an example:
COPYING STRINGS
Copying a string is a common operation in
programming, and there are library functions
available in C++ to make this task easier. The
two commonly used functions for copying strings
are strcpy() and strncpy().

Introduction: When we want to copy the contents


of one string to another, we can use the strcpy()
function. The strcpy() function is defined in the
string.h library and has the following prototype:

strcpy(destination, source);

The strcpy() function copies characters from the


source string to the destination string until it
encounters the terminating null character ('\0'). In this example, strncpy() is used to copy a
specified number of characters from str1 to
Example: Here's an example that demonstrates the
one. We manually add the null character at the
usage of strcpy():
end to ensure proper null-termination. The output
will be :

In summary, the strcpy() function is used to copy


strings, while the strncpy() function copies a
specified number of characters. It's important to
ensure that the destination string has sufficient
space to hold the copied content, including the
terminating null character.

In this example, we have a character array me CONCATENATING STRINGS


initialized with the string "David". We use Here's a simplified explanation of concatenating
strcpy() to copy the string "YouAreNotMe" into strings using strcat() and strncat() in C++:
Introduction: In C++, the + operator cannot be Additionally, there is another function called
used directly to concatenate strings like in some strncat() that is similar to strcat(). The strncat()
other programming languages. However, there are function allows you to specify the number of
library functions available, such as strcat() and characters to concatenate. Here's an example:
strncat(), which can be used to concatenate
strings.

Concatenating Strings: To concatenate or append


one string to another in C++, you can use the
strcat() function. The strcat() function is defined
in the string.h library and has the following
prototype:

strcat(destination, source);

The strcat() function appends the characters of


the source string to the end of the destination
string. It starts appending from the location of
the terminating null character ('\0') of the In this example, strncat() is used to concatenate
destination string. only the first 2 characters from "def" to str1. We
Example: Here's an example that demonstrates the manually add the null character at the desired
usage of strcat(): position to truncate the string.

In summary, the strcat() function is used to


concatenate strings by appending one string to
the end of another. The strncat() function is
similar but allows you to specify the number of
characters to concatenate. Ensure that the
destination string has enough space to hold the
concatenated strings and the terminating null
character.

COMPARING STRINGS
Here's a simplified explanation of comparing
strings using strcmp() and strncmp() in C++:

Introduction: In C++, you can compare strings


In this example, str1 is a character array using library functions such as strcmp() and
initialized with the string "abc". We use strcat() strncmp(). These functions allow you to determine
to append the string "def" to str1. Then, we the order or equality of two strings based on
concatenate the string str2 ("xyz") to str1. Finally, their contents.
we manually add the null character at the desired
position to truncate the string. Comparing Strings: To compare two strings in C+
+, you can use the strcmp() function. The
Note that it's essential to ensure that the strcmp() function is defined in the string.h library
destination string has enough space to hold both and has the following prototype:
strings and the terminating null character.
strcmp(str1, str2);

The strcmp() function compares the characters of


str1 and str2 and returns:
• A value less than 0 if str1 is less than In summary, the strcmp() function is used to
str2. compare strings and returns a value indicating
• 0 if str1 is equal to str2. the order or equality of the strings. The strncmp()
• A value greater than 0 if str1 is greater function is similar but allows you to compare a
than str2. specific number of characters. These functions are
helpful for determining the relative order of
Example: Here's an example that demonstrates the
strings based on their contents.
usage of strcmp() :-
POINTER IN C++

In programming, an operating system uses


memory to store and organize data. Each memory
location is assigned a unique and consecutive
number, starting from 0 and going up to the
maximum limit of memory.

A pointer is a special type of variable that holds


the memory address of another variable. It
"points" to the location in memory where a
specific variable is stored. By using a pointer, we
can access and manipulate the value of the
variable indirectly, by referring to its memory
address.

To declare a pointer variable in a programming


language, we use the following syntax :-
The output indicates the comparison results based type *pointer_name;
on the lexicographical order of the strings.
Here, type represents the type of data that the
Additionally, there is another function called
pointer is going to point to, not the type of the
strncmp() that is similar to strcmp(). The pointer itself. For example, if we want to declare
strncmp() function allows you to compare only a a pointer that can point to a variable of type
specified number of characters. Here's an double, we would write:
example:
double *p;

In this case, p is the name of the pointer


variable, and double indicates that the pointer
will be used to point to a double type variable.

If we want to declare multiple pointer variables


in a single statement, we use the asterisk (*)
before each pointer variable name. For example :-

int *p1, *p2, v1, v2;

Here, p1 and p2 are pointers that can point to


In this example, strncmp() is used to compare variables of type int, while v1 and v2 are regular
different pairs of strings by considering only a variables of type int.
specific number of characters. The output will
depend on the comparison results.
In summary, pointers are variables that store location that ptr is pointing to. So, in this case,
memory addresses of other variables. They allow *ptr gives you the value of i (which is 17).
us to indirectly access and modify the data stored
To summarize, the address-of operator (&) allows
in those variables. Declaring a pointer involves
you to find the memory address of a variable,
specifying the type of data it will point to using
and the dereferencing operator (*) allows you to
the asterisk (*) symbol.
access and manipulate the value stored at a
Address-of Operator (&): memory address pointed to by a pointer.

Imagine you have a variable, let's say v1, that EXAMPLE :-


holds a value. The address-of operator (&) allows
you to find out the memory address where v1 is
stored. It's like putting a label on v1 that shows
where it is located in the memory.

For example, if you have an integer variable v1,


you can use the address-of operator to assign its
memory address to a pointer variable. Let's call
the pointer variable p1. You can do this like so :-

int *p1, v1;


p1 = &v1;

Now, p1 is a pointer that "points" to v1. We can


say that p1 holds the address of v1. In simpler
terms, p1 is like a note card that tells us where
v1 is stored in the memory.

De-referencing Operator (*) :- The first two lines (42) indicate that v1 and *p1
(the value pointed to by p1) both hold the value
Now, let's talk about the de-referencing operator 42 after the assignment. The next two lines
(*). Once you have a pointer that points to a (0x7ffc78b09a74) show the memory address of
variable, you can use the dereferencing operator v1 and the value stored in p1, respectively.
to access the value stored in that variable
indirectly. EXAMPLE :-

For example, if you have a pointer ptr that


points to an integer variable i, you can use *ptr
to access the value stored in i. It's like looking
inside the box that the pointer is pointing to.

Here's an example :-

In simpler terms, when you use *ptr, you are


looking at the value stored in the memory
In simpler terms: Example

1. Declare two integer variables value1 and


value2 and assign them initial values of 5
and 15 respectively.
2. Declare a pointer variable called
mypointer which can point to integers.
3. Assign the memory address of value1 to
mypointer using the address-of operator
(&). Now mypointer "points" to value1.
4. Use the dereferencing operator (*) to
change the value pointed to by mypointer
to 10. Since mypointer points to value1,
this line updates the value of value1 to
10.
5. Change the memory address stored in POINTER ASSIGNMENT
mypointer to the address of value2. Now
In C++, the assignment operator (=) can be used
mypointer "points" to value2.
to assign the value of one pointer to another
6. Use the dereferencing operator (*) to
pointer. When you assign one pointer to another,
change the value pointed to by mypointer
both pointers will point to the same memory
to 20. Since mypointer now points to
location or variable.
value2, this line updates the value of
value2 to 20. For example, let's say you have two pointers p1
7. Print the values of value1 and value2 and p2, and p1 points to a variable named v1. If
using cout. They should now be 10 and you assign p1 to p2 using the assignment
20 respectively. operator (p2 = p1;), both p1 and p2 will now
8. End the main function and return 0, point to the same memory location or variable
indicating successful program execution. (v1 in this case).

This means that if you access the value through


Example :- *p1, *p2, or v1, you will be accessing the same
variable.

It's important to be cautious when making


assignments to pointer variables. For example :-

p1 = p3; // Changes the location that p1 "points"


to p3

In this case, assigning p3 to p1 will make p1


point to the memory location or variable that p3
was pointing to. The original value of p1 is
overwritten.

*p1 = *p3; // Changes the value at the location


that p1 "points" to p3

In this case, the assignment *p1 = *p3 changes


the value at the memory location that p1 is
pointing to. This means that the value stored in
the memory location pointed to by p1 will be
replaced with the value stored in the memory 8. Change the value stored at the memory
location pointed to by p3. location pointed to by p1 to 20 by
dereferencing p1 and assigning a new
So, when assigning pointers, you need to be
value: *p1 = 20;.
aware of whether you are changing the memory
location that the pointer points to (p1 = p3;) or 9. Print the values of value1 and value2
changing the value stored at the memory location using the cout statement.
(*p1 = *p3;). 10.The program ends and returns 0 to
indicate successful execution.

In summary, the program demonstrates the use of


pointers in C++. It initializes two variables,
value1 and value2, and assigns their memory
addresses to two pointers, p1 and p2. It then
manipulates the values stored at these memory
locations by dereferencing the pointers and
assigning new values. Finally, it prints the
modified values of value1 and value2 using the
cout statement.

FUNCTION IN C++

Modular programming and modules

Modular programming is an approach to software


Detailed Description: development that involves breaking down a
program into smaller, independent components
1. Declare and initialize two integer
called modules. Each module is designed to
variables: value1 with a value of 5 and
perform a specific task or provide a specific
value2 with a value of 15.
functionality. By organizing a program into
2. Declare two integer pointers: p1 and p2. modular components, it becomes easier to
These pointers will be used to store develop, test, maintain, and understand complex
memory addresses. software systems.
3. Assign the memory address of value1 to
Here are some key aspects and benefits of
p1 using the & operator: p1 = &value1;.
modular programming:
4. Assign the memory address of value2 to
p2 using the & operator: p2 = &value2;. 1. Independent Modules: In modular
5. Change the value stored at the memory programming, modules are designed to be
location pointed to by p1 to 10 by self-contained and independent. Each
dereferencing p1 and assigning a new module focuses on a specific functionality
value: *p1 = 10;. or task and can be developed and tested
6. Copy the value pointed to by p1 to the separately from other modules. This
memory location pointed to by p2 by modularity allows for easier code
dereferencing p2 and assigning *p1 to it: maintenance and updates, as changes in
*p2 = *p1;. one module are less likely to affect the
7. Assign the value of p2 (memory address functioning of other modules.
of value2) to p1, making p1 point to the
2. Encapsulation: Modules encapsulate a set
same location as p2: p1 = p2;.
of related functions, data, or procedures
within a single unit. This encapsulation
hides the internal details and facilitates adding new features or
implementation of the module, exposing modifying existing ones without disrupting
only the necessary interfaces or APIs the entire system. This scalability and
(Application Programming Interfaces) for maintainability benefit allows for more
interaction with other modules. This agile development and easier adaptation
concept of encapsulation promotes code to changing requirements.
reusability and helps in building more
DEFINITION OF FUNCTIONS
robust and scalable applications.

3. Code Organization and Readability: By Functions in programming are named blocks of


breaking a program into smaller modules, code that perform a specific task or provide a
the overall code structure becomes more specific functionality. They are an essential part
organized and readable. Each module is of any programming language, including C++.
responsible for a specific task, making it Functions allow you to organize your code into
easier to locate and understand relevant reusable and modular units, making it easier to
code sections. This improves code write, read, and maintain.
maintainability, collaboration among
developers, and reduces the complexity of Here's a detailed explanation of functions in C++:
the overall system. 1. Subprograms: Functions in C++ are often
4. Modularity and Reusability: Modular referred to as subprograms because they
programming encourages code reusability. are self-contained units of code that can
Modules can be reused in different parts be called from other parts of the program.
of an application or even in different They can act on data, perform operations,
projects, saving development time and and return a value if required.
effort. Well-designed modules with clear 2. Main Function: In C++, every program
interfaces and well-defined functionality has at least one function called main().
can be easily integrated into different When the program starts, main() is
contexts, promoting code sharing and automatically called. It serves as the entry
reducing duplication. point for the program and contains the
5. Testing and Debugging: Since modules are instructions that are executed first.
designed to be independent, testing and 3. Calling and Returning: Functions are
debugging can be done at a module level. invoked or called by their name followed
This allows for focused and targeted by parentheses (). When a function is
testing, making it easier to identify and called, the program execution branches to
fix issues. Modular programming supports the body of that function. The function
the concept of unit testing, where may perform operations on the given data
individual modules are tested in isolation, and may return a value to the caller
ensuring their correctness and using the return statement. After
functionality before integrating them into executing the function, the program
the larger system. resumes at the line after the function call.
6. Scalability and Maintainability: Large 4. Function Design: Well-designed functions
programs or projects can become complex are designed to perform a specific and
and difficult to maintain over time. easily understood task. They follow the
Modular programming helps in managing principle of "single responsibility,"
complexity by breaking down the system meaning each function should focus on
into smaller, manageable parts. It one task or functionality. If a task is
complicated, it is recommended to break body. This approach eliminates the need for a
it down into multiple functions. This separate declaration or prototype.
modular approach improves code
A function prototype is a statement that declares
readability, reusability, and the function's return type, name, and parameter
maintainability. list without providing the function's
implementation. It serves as a forward declaration
5. User-Defined Functions: In C++, you can
of the function, allowing the compiler to know
define your own functions known as user- about the function's existence, return type, and
defined functions. These functions are parameter types before it is used in the program.
created by the programmer to fulfill
specific requirements. User-defined Here are the key aspects of function prototypes:
functions allow you to encapsulate a
Syntax: The syntax of a function prototype
sequence of statements into a single unit,
follows this pattern:
making it reusable and easy to manage.
return_type function_name([type
6. Built-In Functions: C++ also provides parameterName1, type parameterName2, ...]);
built-in functions as part of the language
and standard libraries. These functions are Return Type and Name: The function prototype
supplied by the compiler or library and begins with the return type, which indicates the
are available for your use. Examples of type of value the function will return when
built-in functions in C++ include printf(), called. It is followed by the function name,
scanf(), sqrt(), strlen(), etc. which is the identifier used to call the function.

Parameter List: The parameter list includes the


DECLARING A FUNCTION types and names of the function's parameters.
Each parameter is specified with its type followed
Before using a function in your program, you by its name, separated by commas. The
need to declare it. The declaration tells the parameter list is enclosed in parentheses ().
compiler the name, return type, and parameters
Agreement with Function Definition: The function
of the function. It serves as a prototype or
prototype must match the function definition in
signature of the function. There are three ways to
terms of the return type, function name, and
declare a function:
parameter list. If there is any discrepancy
File Inclusion: You can write the function between the prototype and the definition, a
prototype in a separate file, typically referred to compile-time error will occur.
as a header file (with a .h extension), and then
Parameter Names in Prototypes: While it is legal
include that file using the #include directive in
to omit parameter names in the function
your program. This allows you to reuse the same
prototype and only provide their types, it is
function prototype across multiple source files.
recommended to include parameter names for
Local Declaration: Alternatively, you can write clarity and documentation purposes. Including
the function prototype directly in the same file parameter names makes the prototype and the
where the function is used. This is called a local function's purpose more evident to readers.
declaration. This approach is useful when the
Default Return Type: All functions in C++ have a
function is only used within a single source file.
return type. If the return type is not explicitly
Function Definition: When you define a function stated in the function prototype, it defaults to
before it is called by any other function, the int. However, explicitly declaring the return type
definition acts as its own declaration. In this for every function, including main(), improves
case, you write the complete function definition code readability and avoids potential confusion.
including the name, return type, parameters, and
Here are some examples of function prototypes: define the operations and logic that will be
executed when the function is called.

Terminating Semicolons: Within the function


body, each statement must be terminated with a
semicolon ;. However, the function definition as a
whole does not end with a semicolon; it is
In these examples, the function prototypes declare concluded with a closing brace }.
functions with different return types (long, void,
Return Type and Parameter List: The function
and int) and different parameter lists. Each
definition must match the return type and
prototype provides the necessary information for
parameter list specified in the function prototype.
the compiler to understand the functions'
It is essential for the definition to agree with the
signatures.
prototype to ensure consistency and proper
By including function prototypes in your functioning of the program.
program, you ensure that the compiler is aware
Explicit Return Type: Every function in C++ must
of the functions and can perform necessary type
have an explicit return type. If a function does
checking and validation. Function prototypes also
not return any value, its return type should be
serve as documentation, making it clear what a
specified as void. This indicates that the function
function does and how it should be called.
does not produce a result.
Function Definition Return Statements: If the function is expected to
return a value, it should conclude with a return
The function definition consists of the function
statement. The return statement specifies the
header and its body. The header specifies the
value to be returned and ends the function
return type, name, and parameter list of the
execution. Return statements can appear
function, while the body contains the actual
anywhere within the body of the function, but it
statements and logic of the function.
is common to place them at the end of the
Here are the key aspects of function definitions: function.

Syntax: The syntax of a function definition void Return Type: If the function does not return
follows this pattern: a value, the return type should be explicitly
declared as void. A void return type indicates
return_type function_name([type that the function does not produce any result.
parameterName1, type parameterName2, ...])
{
// Statements and logic Example :-
}

Function Header: The function header is identical


to the function prototype, except that the
parameters must be named in the definition. The
header specifies the return type, function name,
and named parameters. The parameters' names in
the definition should match those in the
prototype.

Function Body: The body of the function consists


of a set of statements enclosed within braces {}.
It represents the actual implementation of the
function. The statements inside the function body
Execution Of Functions 6. Recursion: Functions can call themselves,
which is known as recursion. Recursion
The execution of functions follows a specific flow allows a function to solve a problem by
within a program. When a function is called, the breaking it down into smaller instances of
program's execution branches to the body of that the same problem. Each recursive call
function, starting from the first statement after creates a new instance of the function,
the opening brace ({). Let's explore the execution and when the base condition is met, the
flow of functions in more detail: recursive calls are unwound, and the
results are combined to solve the original
1. Function Call: When a function is called,
problem.
the program execution temporarily shifts
to the called function. The control flow The execution flow between functions continues
moves to the first statement within the as the program progresses, with control moving
function's body. back and forth between different functions as
they are called and return their results. This
2. Execution within the Function: Within the
allows for the modular organization and
function, the statements and logic defined
coordination of code within a program.
in the function's body are executed
sequentially. The function performs its
designated tasks, which may include SCOPE OF VARIABLES
calculations, data manipulation, condition
checking, or calling other functions. The scope of a variable refers to the region or
part of a program in which the variable is
3. Branching and Control Structures:
accessible and can be referred to by its name. It
Functions can utilize control structures,
defines the visibility and lifetime of a variable
such as if statements or loops, to
within a program. In other words, the scope
introduce branching in their execution.
determines the portion of the code where a
These control structures allow the function
variable can be used and accessed.
to make decisions based on specific
conditions and execute different code The scope of a variable is determined by the
paths accordingly. block in which it is defined. A block is a section
of code enclosed within curly braces {}. Variables
4. Calling Other Functions: Functions can declared within a block have visibility and
call other functions within their body. accessibility limited to that block and its nested
This means that while executing one blocks. Once the execution flow exits the block,
function, another function can be invoked the variables declared within it are no longer
to perform a specific task. By calling accessible or valid.
other functions, the program can break
down complex operations into smaller, 1. Local Variables: Local variables are variables
manageable units, promoting code declared within the body of a function. They
reusability and modularity. have local scope, meaning they are only
accessible and visible within the function in
5. Returning to the Calling Function: After which they are defined. Local variables exist only
the execution of the called function is while the function is executing and are destroyed
completed, the program resumes execution when the function returns or completes its
at the next line of code in the calling execution.
function. The calling function continues
Key Points:
its execution from the point immediately
after the function call statement. • Local variables are declared like any other
variables within the function.
• Parameters passed into a function are also
considered local variables and can be used
within the function.
• Local variables have block scope, meaning
their visibility is limited to the block (set
of braces) in which they are defined.
They are not accessible outside the block
in which they are declared. FUNCTION ARGUMENTS
• Local variables can be defined anywhere
within the function, not just at the top. Function arguments, also known as function
Global Variables: Global variables are variables parameters, allow you to pass values to a
declared outside of any function, typically at the function when calling it. Function arguments are
top of the program or in a separate file. They specified within the parentheses after the function
have global scope, meaning they are accessible name. They provide input values that the
from any part of the program, including all function can use to perform specific operations or
functions, including main(). Global variables exist calculations.
throughout the entire execution of the program, Here are some key points about function
and their value persists until it is explicitly arguments:
changed.
Different Types of Arguments: Function arguments
Key Points: do not have to be of the same type. You can
• Global variables are defined outside of pass arguments of various types, including
any function. integers, floating-point numbers, characters, and
• Global variables have global scope, even expressions. This flexibility allows you to
allowing them to be accessed by any provide a wide range of inputs to functions,
function within the program. depending on their requirements.
• Local variables with the same name as Valid Expressions as Arguments: Any valid C++
global variables do not modify the global expression can be used as a function argument.
variables. However, if a local variable has This includes constants, mathematical and logical
the same name as a global variable, it expressions, and even other functions that return
will hide the global variable within the a value. The expression is evaluated before being
scope of the function. passed as an argument to the function.
• When a function has a variable with the
same name as a global variable, the
variable name within the function refers
to the local variable, not the global
variable.

SCOPE RESOLUTION OPERATOR

When it comes to global variables, the scope


resolution operator :: allows you to explicitly
specify the global scope. It enables you to access
global variables even when there are local
variables with the same name, effectively
overriding the local scope.
PASSING ARGUMENTS the function will affect the original object in the
calling function. Pass by reference can be
achieved using pointers or references.
Pass by Value: When passing arguments to a
function by value, a local copy of each argument
Direct Access to Original Object: When passing an
is made within the function. This means that
object by reference, the function receives direct
changes made to the arguments within the
access to the original object rather than a copy.
function do not affect the original values in the
Any modifications made to the object within the
calling function. Pass by value is the default
function will affect the original object in the
behavior in C++.
calling function.
Here are some key points about pass by value:
Modifying the Object: Pass by reference allows
1. Local Copy of Arguments: When a the function to change the object being referred
function is called, the values of the to. Any modifications made to the object within
arguments are copied into the function's the function will be reflected in the original
parameter variables. These parameter object, enabling the function to have a direct
variables act as local variables within the impact on the calling function's data.
function.

2. Changes Do Not Affect Calling Function:


Any modifications made to the parameter
variables within the function do not
impact the original values of the
arguments in the calling function. The
changes are confined to the local scope of
the function.

RETURN VALUES

In programming, functions can return a value to


the caller. The return value represents the result
or output of the function's computation. A return
value can be of any valid data type, such as
integers, floating-point numbers, characters, or
even user-defined types.

Pass by Reference: In C++, passing arguments by Here are some key points about returning a value
reference allows you to pass the actual original from a function:
object into the function rather than creating a
local copy. Changes made to the object within Return Type: Functions are declared with a
specific return type, which indicates the data type
of the value that the function will return. For program jumps to the instructions of that
example, a function declared with a return type function and then returns to the calling code
of int is expected to return an integer value. once the function is executed. However, for very
small functions that consist of just a few lines of
Using the return Keyword: To return a value code, this jumping process can introduce some
from a function, the return keyword is used. It is performance overhead.
followed by the value that is being returned. This
To optimize the performance in such cases, the
value can be a literal value, a variable, or an
inline keyword can be used when declaring a
expression that evaluates to a value.
function. When a function is declared as inline,
Returning a Value vs. Returning void: Functions the compiler includes the code of that function
can either return a value or have a return type of directly into the calling code instead of creating a
void. If a function has a return type of void, it separate function. It's as if the statements of the
means that the function does not return any function were written directly in the calling
value. In such cases, the return statement is used function.
without any value after it, simply indicating the
Here are a few key points about inline functions:
end of the function.

End of Function Execution: When the return


• Performance Optimization: Inline functions
are used to improve performance by
statement is encountered, it signifies the end of
reducing the overhead of function calls
the function's execution. The program control
for small, frequently used functions.
immediately returns to the calling function, and
any statements following the return statement are • Copying Code: When a function is
not executed. declared as inline, the compiler copies the
function's code directly into the calling
Multiple return Statements: It is possible to have
function. This eliminates the need for
multiple return statements within a single
jumps and function calls, resulting in
function. Each return statement can return a
potentially faster execution.
different value based on certain conditions or
logic within the function. When a return • Size Considerations: Although inline
statement is executed, the function's execution functions can improve speed, they can
terminates, and the corresponding value is also increase the size of the executable
returned to the caller. program. If an inline function is called
multiple times, the code is replicated at
To put it simply, returning a value from a
each call site, which can lead to larger
function means providing an output or result that
executable sizes.
can be used by the calling code. The return
keyword is used to specify the value to be • Suitability for Small Functions: Inline
returned, and it marks the end of the function's functions are most effective for small
execution. functions that consist of a few lines of

It's important to note that the return value can code. For larger functions, the benefits of

be captured and utilized by the caller, allowing inlining may be outweighed by the

the function's result to be used in further increase in program size.

computations or operations within the program. It's important to note that the decision to use the
inline keyword should be based on careful
INLINE FUNCTION AND RECURSIVE FUNCTION consideration. While it can provide performance
improvements for small functions, it may not
INLINE FUNCTIONS :- In programming, functions always be beneficial for larger functions or in
are typically defined separately from where they cases where the increased program size is a
are called. When a function is called, the concern.
So this skipping of the separate instructions is Another interesting type of function is called a
what we call "inline" functions. It helps speed recursive function. A recursive function is defined
things up because the computer doesn't need to in terms of itself. It usually has a base case,
jump to a different set of instructions and then which is a simple case that can be solved without
come back again. The instructions are right there, recursion, and a recursive case, which refers back
where they are needed, and it saves time. to the function itself to make progress towards
the base case.
But there is a catch. If the instructions are too
long, copying them everywhere can make the Let's take an example of a recursive function
program bigger and slower. So, we only use called "f" defined on non-negative integers:
inline functions for very short sets of instructions.
• f(0) is the base case, where the value is
To sum it up, an inline function is like copying a directly known.
short set of instructions directly into the place • For any value x greater than 0, f(x) is
where they are needed, instead of going to a defined as 2 * f(x - 1) + x^2.
different place to follow those instructions. It can
To evaluate the value of f(3), we need to
make things faster for short instructions, but we
evaluate f(2) first, then f(1), and finally f(0). By
need to be careful not to use it for long
substituting the values according to the
instructions that would make the program bigger
definition, we can compute the value of f(3) as
and slower.
21.

When writing recursive functions, it's important


to follow four basic rules:

1. Base case: Every recursive function must


have a base case that can be solved
without recursion. It's the starting point
or simplest case.
2. Making progress: The recursive call in the
function should move the problem closer
to the base case. It should make progress
towards the solution.

Examples of recursive functions include the


factorial function, which calculates the product of
RECURSIVE FUNCTIONS all positive integers up to a given number, and
the Fibonacci sequence, where each number is
In programming, functions can be defined in
the sum of the two preceding ones.
different ways. One common way is to define a
function using a formula or set of rules. For Recursive functions are powerful tools but can be
example, you can define a mathematical function expensive in terms of time complexity. It's
that converts Fahrenheit temperatures to Celsius generally recommended to use recursion for
by using the formula C = 5(F - 32) / 9. problems that are better suited for it and can't be
easily implemented iteratively. Understanding
recursion is important for computer scientists, but
it's essential to consider the time requirements
and potential performance impact when choosing
between recursion and iterative solutions.
variables for each component. Instead, we can
use a data structure called an array to group
similar variables together.

An array is like a container that can hold


multiple values of the same type. It allows us to
store these values in a single, contiguous block of
memory. We can think of it as a row of labeled
boxes, where each box holds a specific value.

By using an array, we can easily store and access


multiple values without having to create separate
variables for each one. We can access individual
values in the array by referring to their index,
which is their position in the array. The first
value has an index of 0, the second has an index
of 1, and so on.
In this example, we have a recursive function
called factorial() that takes an integer n as a Arrays allow us to work with collections of data
parameter and returns the factorial of n. The efficiently, as we can perform operations on
factorial of a number n is the product of all multiple values using loops or other techniques.
positive integers from 1 to n. They provide a way to organize and manage
related data, making our code more organized
Inside the factorial() function, we have a base
and easier to work with.
case that checks if n is 0 or 1. If n is 0 or 1, we
return 1 because the factorial of 0 or 1 is defined In addition to arrays, we can also define our own
as 1. custom data types in programming. These user-
defined data types allow us to create structures
In the recursive case, when n is greater than 1,
or objects that can hold multiple variables of
we calculate the factorial of n by multiplying n
different types, allowing us to model more
with the factorial of n-1. This recursive call
complex concepts and entities in our programs.
allows us to break down the problem into smaller
sub problems until we reach the base case. Structure :- In C++, a structure is a way to create
a user-defined type that groups together multiple
In the main() function, we call the factorial()
variables. It allows us to define a blueprint or
function with the number 5 and store the result
template for a data structure that consists of
in the result variable. Finally, we display the
several variables, which are called member
factorial of the number on the console.
variables.
The recursive nature of the factorial() function
To define a structure, we use the struct keyword
allows us to compute the factorial of a number
followed by the name of the structure. Inside the
by repeatedly calling the function itself with
structure, we list the member variables along
smaller values until we reach the base case.
with their types and names. For example, we can
define a structure called date that contains three
STRUCTURE IN C++ member variables of type int: day, month, and
year.

In programming, we often need to work with Once we have defined a structure, we can create
groups of related values. For example, if we want variables of that structure type just like any other
to store a date consisting of a day, month, and variable. These variables are called structure
year, it would be inconvenient to create separate variables. When we create a structure variable, it
will have all the member variables defined in the and year. The only difference is the name we
structure definition. give to each structure variable.

For example, if we create two structure variables To access the member variables of a structure
based on the date structure, both variables will variable, we use the dot (.) operator. We combine
have the same member variables: day, month, the structure variable's name with the member
and year. The only difference is the name we variable's name to refer to a specific member
give to each structure variable. variable. For example, if we have a structure
variable called myDate, we can access its day
To access the member variables of a structure
member variable as myDate.day.
variable, we use the dot (.) operator. We combine
the structure variable's name with the member It's important to note that member variables are
variable's name to refer to a specific member distinguished by the structure variable they
variable. For example, if we have a structure belong to. This means that we can have multiple
variable called myDate, we can access its day structure variables with the same member
member variable as myDate.day. variable names, but they are independent and
separate from each other.
It's important to note that member variables are
distinguished by the structure variable they
belong to. This means that we can have multiple DEFINING STRUCTURES
structure variables with the same member
variable names, but they are independent and
When defining a structure in C++, you are
separate from each other.
essentially creating a blueprint or template for a
STRUCTURE :- user-defined type. The structure specifies the
layout and types of its member variables.
In C++, a structure is a way to create a user-
To define a structure, you use the struct keyword
defined type that groups together multiple
followed by the structure name, which serves as
variables. It allows us to define a blueprint or
the type identifier. Inside the structure, you
template for a data structure that consists of
enclose the member variables within curly braces
several variables, which are called member
{}. Each member variable is declared just like
variables.
any other variable, specifying its type and name.
To define a structure, we use the struct keyword
For example, let's consider a structure called
followed by the name of the structure. Inside the
student. It has two member variables: an int
structure, we list the member variables along
variable named id and a character array of size
with their types and names. For example, we can
15 named name.
define a structure called date that contains three
member variables of type int: day, month, and
year.

Once we have defined a structure, we can create


variables of that structure type just like any other
variable. These variables are called structure
In this example, we have defined the structure
variables. When we create a structure variable, it
student with its member variables. Note that the
will have all the member variables defined in the
member variables do not have initial values; they
structure definition.
are just declarations within the structure
For example, if we create two structure variables definition.
based on the date structure, both variables will
It's important to remember that the structure
have the same member variables: day, month,
definition itself does not create any storage or
memory. It simply provides a blueprint for the
structure type. The actual storage for the member
variables will be allocated when you create a
structure variable based on this structure.

For example, to create a structure variable of


type student, you can use the structure name
followed by a variable name of your choice:

student s1; // Creates a structure variable 's1' of


type 'student'

In this code, the structure date is defined without


Now, s1 is an instance of the student structure.
It will have the member variables id and name, initializing its member variables in the structure
which you can access using the dot (.) operator : definition. Then, within the main function, a
structure variable d is created, and its member
variables day, month, and year are assigned
specific values.

Remember, you cannot directly initialize structure


member variables within the structure definition,
Example :-
but you can assign values to them after creating

The code below mentioned attempts to initialize a structure variable.


the member variables of a structure within the
Declaring and using struct data types
structure definition. However, in C++, it is not
allowed to initialize member variables directly
inside the structure definition. Once you have defined a structure, you can
create a variable from it just like creating any
other variable. Let's consider the examples

In this code, the intention is to initialize the day, In the first line, we declare a variable i of type
month, and year member variables of the date int. This is a built-in type provided by the
structure to specific values (24, 10, and 2001, programming language.
respectively). In the second line, we declare a variable std1 of
However, this syntax is not valid in C++. type student. Here, student is a user-defined type
Member variables of a structure must be defined using a structure. The student structure
initialized when you create a structure variable, has characteristics or attributes that represent the
not within the structure definition itself. id and name of a student.

To properly initialize the member variables, you In the third line, we declare a variable birthday
can do it after creating a structure variable using of type date. Similarly, date is a user-defined
the assignment operator (=) or through a type defined using a structure. The date structure
constructor if you define one for your structure. has member variables such as day, month, and
year to represent a date.
Here's an example of initializing the member
variables after creating a structure variable When a structure variable is created, a block of
memory is reserved to hold all of its member
variables. Each member variable occupies a You can use any expressions that result in values
portion of that memory block. The member to initialize the member variables. For example,
variables are stored at specific offsets within the you can use variables and arithmetic operations.
memory block. For example, in the date However, once a structure variable has been
structure, the day member variable may be declared, you cannot assign values to multiple
located at offset 0, and the month member members using an initialization block. You need
variable may be located at offset 4 (assuming to access each member individually for
each member variable occupies 4 bytes). assignment.

So, by creating structure variables, we can store It's important to note that you can assign fewer
and access multiple related pieces of data in a values than the number of member variables in
single variable, making it easier to work with the structure, but you cannot assign more values.
complex data structures. If you omit a value in the initialization, no value
will be assigned to the corresponding member
variable.
INITIALIZING STRUCTURE VARIABLES
ACCESSING MEMBERS OF A STRUCTURE VARIABLE
When you define a structure, you cannot directly
To access the members of a structure variable,
initialize its member variables in the structure
you use the structure member operator, which is
definition. However, you can initialize the
the period (dot) symbol. You specify the structure
member variables of a structure variable when
variable's name, followed by the period, and then
you create it.
the name of the member variable you want to
To initialize the member variables of a structure access.
variable, you use an initialization block. After the
For example, if you have a structure variable
variable declaration, you use the assignment
called s1 with member variables id and name,
operator (=) and provide a list of initializers
you can access them using s1.id and s1.name.
enclosed in curly braces. The values are assigned
This allows you to read and assign values to the
to the member variables in the order they are
member variables, as well as display their
declared in the structure definition.
contents.
For example, consider the following code:
In the provided example, a program creates a
structure called student, which has member
variables id and name. The program creates two
student variables, s1 and s2, and prompts the
user to enter their IDs and names. The
In the first line, a variable called nco_birthday of
information is stored in the respective variables,
type date is created and initialized with the
and then the program displays the students'
values {19, 8, 1979}. The values are assigned to
information by accessing their member variables
the member variables day, month, and year in
using the structure member operator.
the same order they are declared in the structure
definition. By using the structure member operator, you can
access and manipulate the individual member
Similarly, in the second line, a variable called
variables of a structure variable, allowing you to
std1 of type student is created and initialized
work with the data stored in the structure.
with the values {"Ababe", "Scr/2222/22"}. The
values are assigned to the member variables
name and id in the same order they are declared
in the structure definition.
This can be useful when you want to group
variables together in one place without affecting
other parts of the program.

For example, you can define a structure called


pointtag and create a variable named point right
after the structure definition:

In this case, point is a variable that refers to


the structure definition. The above code is
equivalent to:

Example :-

In this code, we define a Date structure with


member variables day, month, and year.

Inside the main function, a Date variable named


birth is created. The user is prompted to enter
their birth date, and the values are stored in the
respective member variables.

The program then outputs the entered birth date


using std::cout. It also calculates the century
based on the year input and assigns it to the
century variable. Finally, the program displays
the calculated century using std::cout.

VARIABLES WITH DEFINITION


In this example, we define a structure called
Person with two member variables name and age.
In C++, it is possible to create variables based on
After the structure definition, we declare a
a structure definition without using separate
statements. The syntax allows for creating structure variable named person using the syntax
variables right after the structure definition: struct Person { } person;.

Inside the main() function, we assign values to


the member variables of person using the dot
operator (person.name = "John Doe" and
person.age = 30).

Finally, we access and display the values of the


member variables using the dot operator and
The structure variables created in this way will std::cout. The output will show the name and age
have the same scope as their structure definition. of the person stored in the person variable.
ARRAY OF STRUCTS The program creates an array of student structs
named s with a size of 5. This means we can
An array of structs is a collection or sequence of store 5 instances of the student struct in the
multiple instances of a particular structure type. array.
It allows you to group related data together and
Using a for loop, the program prompts the user
store multiple instances of the same structure in a
to enter the id and name for each student in the
contiguous block of memory.
array. The loop iterates 5 times, allowing the
Definition 1: An array of struct is a data structure user to input information for each student.
that holds multiple elements, where each element
After all the input is collected, the program
is an instance of a specific struct type. The
displays the information of all the students in a
elements are stored in consecutive memory
formatted manner using another for loop.
locations, forming a sequential collection of struct
instances. Here's the code with a brief explanation:

Definition 2: An array of struct is a way to


organize and store multiple instances of a struct
type in a systematic manner. It provides a This code allows the user to input information for
convenient way to access and manipulate related 5 students and then displays the entered
data by using index-based referencing. information in a tabular format. Each row
represents a student, and the columns represent
In simpler terms, an array of structs is like a the id and name of each student.
container that can hold multiple instances of a
struct. It allows you to store and access Using an array of structs in this way allows us to
structured data efficiently, making it easier to efficiently store and manipulate multiple instances
work with related information in your program. of the same struct type, making it easier to
manage and work with related data.
The code we provided below demonstrates the
concept of an array of structs. Here's a brief
explanation of the code and the concept:

In this code, we have a struct called student,


which has two member variables: id and name.

DECLARING STRUCT TYPES AS PART OF A


STRUCT

Declaring struct types as part of a struct means


including a structure definition as a member
variable within another structure definition.

In C++, you have the flexibility to define a


structure that contains other structures as its
members. This can be useful when you want to
represent complex data that consists of multiple relationships between different entities or
levels of information. components of your system.

By including a structure definition as a member By using nested structures, you can achieve better
variable within another structure definition, you code organization, improve readability, and
can create a hierarchical structure that organizes enhance the maintainability of your programs. It
and encapsulates related data together. helps in avoiding naming conflicts and provides a
clear and structured representation of the data
For example, consider a scenario where you have
relationships.
a Person structure that represents an individual,
and within the Person structure, you want to
include an Address structure to store the person's
address details. This allows you to associate
FILE MANAGEMENT
address information with each person.
File management is an important aspect of
By nesting structures in this way, you can access programming where we work with files, such as
and manipulate the member variables of the saving data to the computer's storage and reading
nested structure using the dot operator (.) to data from it. The files stored on the computer's
access the specific members within the structure storage are called physical files. In order to work
hierarchy. with files in a program, we create a logical file
in the computer's memory (RAM). This logical file
When you declare a structure type as part of
is represented as an object with a specific file
another structure, you create a hierarchical
type. To keep track of this logical file, we use a
relationship between the structures. This
variable called a file variable or file handler.
hierarchy allows you to organize related data and
access it in a structured manner.

In the provided example, the Person structure


includes the Address structure as a member
variable. This means that each instance of the
Person structure will have an associated Address
structure, allowing you to store and access
address details for each person.

By nesting structures, you can achieve a more


intuitive representation of real-world entities that
have multiple levels of information. For example,
a Person structure may have additional member
variables such as name, age, and gender, along
with the nested Address structure.

To access the member variables of the nested


structure, you use the dot operator (.) along with
the appropriate variable names. For instance, to
access the streetNumber member variable within
the Person structure, you would use
person.address.streetNumber.

This hierarchical structure provides a convenient


way to encapsulate related data and access it in a
logical and organized manner. It allows you to
create complex data structures that reflect the
In C++, there are classes specifically designed to A file pointer is a pointer to information about a
simplify file input and output operations for file, including its name, status, and current
programmers. These classes provide easier ways position. It is used by the associated stream to
to read from and write to files compared to control the input/output operations on the file.
directly manipulating the physical files.
STANDARD STREAMS :- When a program starts,
Streams can be thought of as a way to move three standard streams are automatically opened:
information between a program and a device, stdin for standard input, stdout for standard
such as a file or the console. Imagine a stream as output, and stderr for standard error. These
a pipe connecting your program to a file or the streams are typically connected to the console
screen. You can send data through this pipe and can be used for input/output operations on
(write) or receive data from it (read). Streams the console using the C file system.
provide a convenient and consistent way to
interact with different devices, hiding the specific Example :-
details of each device.

Text streams are like pipes that transfer


sequences of characters. They can perform certain
translations or modifications on the characters as
needed by the system. Text streams handle
character-level operations and are suitable for
working with textual data.

On the other hand, binary streams are pipes that


transfer sequences of bytes. They don't perform
any translations or modifications on the data.
Whatever you write to a binary stream is exactly
what will be stored in the file, and when you
read from it, you get the same bytes that were
stored. Binary streams are useful when dealing
with non-textual data, such as images, audio, or In simpler terms, this C++ program is using the
binary file formats. They preserve the exact "iostream" and "fstream" libraries to work with
content of the data without any modifications. files. It focuses on writing data to a file.
In summary, text streams handle character-level The program begins by including the necessary
operations and may perform translations or libraries. "iostream" provides input/output
modifications, while binary streams deal with raw functionality, while "fstream" specifically handles
bytes without any modifications. file input/output operations.
A file in C++ can refer to various things like a The "main" function is the entry point of the
disk file, terminal, or printer. To associate a program. Inside the "main" function, an object
stream with a specific file, we perform an open called "outFile1" is created. This object represents
operation. Once a file is open, we can exchange a file that we want to write to. It is of the type
information between it and our program. Files "ofstream" which stands for "output file stream".
can have a position indicator that keeps track of
the current position in the file. When a file is Next, the program opens a file named
closed, any pending data in the associated stream "ethio1.txt" using the "open" function of the
is written to the external device. All files are "outFile1" object. This means that we want to
automatically closed when the program terminates write data to a file with that name. If the file
normally. does not exist, it will be created.
After the file is opened, the program uses the Next, we use the open function of the inFile1
"<<" operator, which is overloaded for file object to open the file named "ethio1.txt" for
streams, to write the text "Ethio programming reading. This assumes that the file exists in the
your channel of choice" to the file. This means same directory as the program.
that this text will be written to the file
After opening the file, we use the >> operator
"ethio1.txt".
to read data from the file into the variable x. In
Finally, the program closes the file using the this case, it will read a single word or a
"close" function of the "outFile1" object. This sequence of characters until a space or newline is
step is important to ensure that all the data is encountered.
properly written and that the file is closed.
We then use the cout object (part of the iostream
In the end, the program returns 0, indicating that library) along with the << operator to print the
it has completed successfully. content of x to the console.

Example :- Finally, we close the file using the close function


of the inFile1 object. Closing the file is important
to release the resources associated with it.

The return 0; statement signifies the end of the


main function and indicates that the program
executed successfully.

Example :-

In this code, we are using the C++ standard


libraries iostream and fstream for input/output
operations.

The code starts by including the necessary


libraries and declaring the using namespace std;
statement to avoid writing std:: before each
standard library function or object.

Inside the main function, we declare a string


variable named x. This variable will be used to In this code, we are using the C++ standard
store the data read from the file. libraries iostream and fstream for input/output
We then create an ifstream object named inFile1, operations.
which represents an input file stream. This object The code starts by including the necessary
allows us to read data from a file. libraries and declaring the using namespace std;
statement to avoid writing std:: before each Next, we use the open function of the inFile1
standard library function or object. object to open the file named "ethio1.txt" for
reading. The ios::in flag is passed as the second
Inside the main function, we declare three string
argument to indicate that the file should be
variables: x, y, and z. These variables will be
opened for input. This flag is optional since
used to store the data read from the file.
ios::in is the default mode for opening files.
We then create an ifstream object named inFile1,
After opening the file, we use the >> operator
which represents an input file stream. This object
to read the first word from the file into the
allows us to read data from a file.
variable x.
Next, we use the open function of the inFile1
We then use the cout object (part of the iostream
object to open the file named "ethio1.txt" for
library) along with the << operator to print the
reading. This assumes that the file exists in the
content of x to the console.
same directory as the program.
We repeat the same process for the variables y,
After opening the file, we use the >> operator
z, and r, reading the next words from the file
to read the first word from the file into the
and printing them to the console.
variable x.
Finally, we close the file using the close function
We then use the cout object (part of the iostream
of the inFile1 object. Closing the file is important
library) along with the << operator to print the
to release the resources associated with it.
content of x to the console.
The return 0; statement signifies the end of the
We repeat the same process for the variables y
main function and indicates that the program
and z, reading the next words from the file and
executed successfully.
printing them to the console.
Regarding the ios::in flag, it is an input mode
Finally, we close the file using the close function
flag that specifies the file should be opened for
of the inFile1 object. Closing the file is important
input operations. This flag is optional because
to release the resources associated with it.
opening a file for input is the default behavior
The return 0; statement signifies the end of the when using ifstream. The ios::in flag can be
main function and indicates that the program useful when you want to be explicit about the
executed successfully. file's intended purpose or when you're using a
different input mode in combination with other
Example :-
flags, such as ios::binary for binary input.
In this code, we are using the C++ standard
libraries iostream and fstream for input/output
operations.

The code starts by including the necessary


libraries and declaring the using namespace std;
statement to avoid writing std:: before each
standard library function or object.

Inside the main function, we declare four string


variables: x, y, z, and r. These variables will be
used to store the data read from the file.

We then create an ifstream object named inFile1,


which represents an input file stream. This object
allows us to read data from a file.
statement to avoid writing std:: before each
standard library function or object.

Inside the main function, we create an ofstream


object named outFile1, which represents an
output file stream. This object allows us to write
data to a file.

We then use the open function of the outFile1


object to open the file named "ethio2.txt" in
append mode for writing. The ios::app flag is
passed as the second argument to indicate that
we want to append data to the existing content
of the file, rather than overwriting it. If the file
doesn't exist, it will be created.

After opening the file, we use the << operator


to write the message "Hello World" to the file.

Finally, we close the file using the close function


of the outFile1 object. Closing the file is
important to ensure that all the data is written
and the resources are properly released.

The return 0; statement signifies the end of the


main function and indicates that the program
executed successfully.

Example :-
Example :-

In this code, we are using the C++ standard


libraries iostream and fstream for input/output
operations.

The code starts by including the necessary


libraries and declaring the using namespace std;
In this code, we are using the C++ standard In the case of outFile4, we use the put function
libraries iostream and fstream for input/output along with the character 'E' to write a single
operations. character 'E' to the file.

The code starts by including the necessary Finally, we close all the opened files using the
libraries and declaring the using namespace std; close function of each file object. Closing the files
statement to avoid writing std:: before each is important to ensure that all the data is written
standard library function or object. and the resources are properly released.

Inside the main function, we create five ofstream The return 0; statement signifies the end of the
objects: outFile1, outFile2, outFile3, outFile4, and main function and indicates that the program
outFile5. These objects represent output file executed successfully.
streams, allowing us to write data to files.

We then open the files using the open function of In this code, we are using the C++ standard
each file object. The files "ethio1.txt", libraries iostream and fstream for input/output
"ethio2.txt", "ethio3.txt", and "ethio5.txt" are operations.
opened in append mode (ios::app) to append data The code starts by including the necessary
to the existing content of the files. The file libraries and declaring the using namespace std;
"ethio4.txt" is opened without any specific mode, statement to avoid writing std:: before each
so it will be opened for writing and overwrite standard library function or object.
any existing content.
Inside the main function, we declare string
Next, we use the << operator to write messages variables x and z to store read words and lines,
to the files. For example, outFile1 << "Hello respectively. We also declare character variables y
World"; writes the message "Hello World" to the and a to store read characters.
file associated with outFile1.
We then create five ifstream objects: inFile3,
inFile4, inFile5, inFile6, and inFile7. These
objects represent input file streams, allowing us
to read data from files.

We use the open function of each inFile object to


open the respective files ("ethio3.txt",
"ethio4.txt", "ethio5.txt", "ethio6.txt", and
"ethio7.txt") for reading.

Using the input operations, we read data from


the files. For example, inFile3 >> y; reads a
character from inFile3 and stores it in the
variable y. Similarly, inFile4 >> x; reads a word
from inFile4 and stores it in the variable x. The
getline function is used to read a line from
inFile5 and store it in the variable z. Finally,
inFile7.get(a); reads a character from inFile7 and
stores it in the variable a.

We then use cout to print the read character,


word, and line to the console.

Finally, we close all the opened files using the


close function of each file object. Closing the files
is important to release the resources associated
with them.

The return 0; statement signifies the end of the


main function and indicates that the program
executed successfully.

You might also like