PF Notes
PF Notes
Programming Fundamentals
Introduction to Computers, the Internet and the Web:
Computers process data under the control of sequences of instructions called computer programs. These software programs guide the computer
through ordered actions specified by people called computer programmers.
Hardware
A computer consists of various devices referred to as hardware (e.g., the keyboard, screen, mouse, hard disks, memory, DVD drives and processing
units).
Input Devices
Input devices are hardware devices that allow users to input data or commands into a computer system. These devices enable users to interact with
the computer and provide the necessary input for the system to process and execute tasks.
Keyboard, Mouse, Touchscreen, Trackpad, Scanner, Webcam, Microphone
Output Devices
A hardware components used to display information to the user of the computer are called Output Devices.
❖ Monitor ❖ Speaker ❖ Printer ❖ Plotters ❖ Screen image projector ❖ Voice response system
Memory
Hardware components used to stores data and instructions temporarily is called memory.
❖ Main memory is also called volatile memory because its contents are lost when the computer is turned off
Components of a CPU:
1. Control Unit (CU): The control unit manages and coordinates the operations of the CPU. It fetches instructions from memory, decodes them, and
controls the flow of data between different parts of the CPU and other devices.
2. Arithmetic Logic Unit (ALU): The ALU performs arithmetic operations (addition, subtraction, multiplication, and division) and logical operations
(comparison, AND, OR, NOT) on data. It is responsible for carrying out calculations and making logical decisions.
3. Registers: Registers are small, high-speed memory units located within the CPU. They store data, instructions, and intermediate results during
processing. Common types of registers include the program counter (PC), instruction register (IR), and accumulator.
4. Cache: Cache is a small but faster memory located within the CPU. It stores frequently accessed data and instructions to reduce the time it takes
to access them from the main memory. The cache improves the overall performance of the CPU by reducing memory latency.
Software:
“A set of instructions that tells the computer what to do”.
➢There are two main types ❖System Software ❖Application Software Important
Data Hierarchy:
Data hierarchy refers to the organization and arrangement of data in a structured manner. It helps in understanding the relationship between
different levels of data and how they are related to each other. Data hierarchy is crucial in database management systems and is used to ensure
efficient data storage, retrieval, and manipulation.
1. Bit: The smallest unit of data in a computer system is called a bit. It can have two values, either 0 or 1. Bits are used to represent the most basic
form of information in a computer system.
2. Byte: A byte is a group of 8 bits. It is the fundamental unit of storage in computer systems. Bytes are used to represent characters, numbers, and
other types of data. For example, the letter 'A' is represented by the byte 01000001.
3. Field: A field is a collection of related bytes that represents a specific attribute of an entity. It is the basic unit of data that can be accessed and
manipulated. For example, in a database of students, a field could be the student's name or age.
4. Record: A record is a collection of related fields that represents a complete set of information about an entity. It is a logical grouping of data that
represents a single entity or object. For example, a record in a database of students could contain fields such as name, age, address, and grade.
5. File: A file is a collection of related records. It represents a complete set of data about a particular entity or object. Files are used to organize and
store data in a structured manner. For example, a file in a database of students could contain multiple records, each representing a different student.
6. Database: A database is a collection of related files. It is a centralized repository of data that is organized and managed using a database
management system (DBMS). Databases are used to store, retrieve, and manipulate large amounts of data efficiently. They provide a structured and
secure way to manage data in organizations.
1. Machine Languages:
- Machine language is the lowest-level programming language understood by computers.
- It consists of binary code (0s and 1s) that represents specific instructions and data.
- Each computer architecture has its own machine language, which is specific to that architecture.
- Machine language programs are executed directly by the computer's hardware.
- It is difficult to read and understand machine language code, as it is not human-friendly.
2. Assembly Languages:
- Assembly language is a low-level programming language that is a step above machine language.
- It uses mnemonic codes to represent machine language instructions.
- Each mnemonic corresponds to a specific machine language instruction.
- Assembly language programs are converted into machine language using an assembler.
- Assembly language allows programmers to write more readable code compared to machine language.
- It provides direct control over the computer's hardware and memory.
3. High-Level Languages:
- High-level languages are programming languages that are designed to be easier to read, write, and understand by humans.
- They are independent of the computer's architecture and can be used on different platforms.
- High-level languages use English-like statements and expressions to write programs.
- Examples of high-level languages include Python, Java, C++, and Ruby.
- Programs written in high-level languages are converted into machine language using a compiler or interpreter.
- High-level languages provide built-in functions and libraries, making programming tasks more efficient.
- They offer abstraction from hardware details, allowing programmers to focus on problem-solving rather than low-level
implementation.
Key Differences:
- Machine languages are specific to a computer architecture, while assembly languages and high-level languages are portable
across different platforms.
- Machine language is written in binary code, assembly language uses mnemonic codes, and high-level languages use English-
like statements.
- Machine language provides direct control over hardware, while assembly and high-level languages offer more abstraction.
- Machine language is executed directly by the computer's hardware, while assembly and high-level languages require
translation into machine language.
What is Programming?
A program is a set of instructions to tell the computer what to do.
Programming Languages - C++
1. Introduction to C++:
- C++ is a general-purpose programming language that was developed as an extension of the C programming language.
- It supports procedural, object-oriented, and generic programming paradigms.
- C++ is known for its efficiency, performance, and low-level access to memory, making it suitable for system-level programming and resource-
constrained environments.
- It is widely used in the development of applications, games, embedded systems, and high-performance software.
7. Memory Management:
- C++ provides manual memory management through the use of pointers and dynamic memory allocation.
- Pointers are variables that store memory addresses, allowing direct access and manipulation of memory.
- Dynamic memory allocation is done using the 'new' keyword to allocate memory on the heap and 'delete' to free the allocated memory.
- Improper memory management can lead to memory leaks or crashes, making it essential to handle memory carefully.
Key Concepts:
1. Objects: Objects are instances of classes that represent real-world entities or concepts. They have attributes (data) and methods (behavior)
associated with them.
2. Classes: Classes are blueprints or templates for creating objects. They define the structure and behavior of objects, including their attributes and
methods.
3. Encapsulation: Encapsulation is the process of hiding the internal details of an object and providing a public interface to interact with it. It helps
in achieving data security and code reusability.
4. Inheritance: Inheritance is a mechanism that allows a class to inherit the properties and methods of another class. It promotes code reuse and
supports the concept of hierarchical relationships between classes.
5. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility and
extensibility in programming.
6. Abstraction: Abstraction refers to the process of simplifying complex systems by breaking them down into smaller, manageable components. It
focuses on the essential characteristics of an object, hiding unnecessary details.
Internet
The internet is a global network of computers that allows the sharing of information and resources.
- The World Wide Web (WWW) is an information system on the internet that allows users to access and interact with webpages.
1. C++ 11 Features:
a. Lambda expressions: C++ 11 introduced lambda expressions, allowing developers to write anonymous functions inline. This feature is
particularly useful in functional programming and for simplifying code.
b. Range-based for loop: The range-based for loop simplifies iterating over elements in a container, such as an array or a vector. It provides a
cleaner and more expressive syntax compared to traditional for loops.
c. Smart pointers: C++ 11 introduced smart pointers, which are objects that manage the lifetime of dynamically allocated memory. They
automatically deallocate memory when it is no longer needed, reducing the risk of memory leaks.
d. Move semantics: Move semantics allow for more efficient resource management by enabling the transfer of ownership of resources, such as
memory or file handles, from one object to another. This feature improves performance and reduces unnecessary copying.
e. Threading support: C++ 11 added a standard threading library, making it easier to write multithreaded applications. It provides classes and
functions for creating and managing threads, synchronization, and inter-thread communication.
2. Boost Libraries:
a. Boost is a collection of high-quality, peer-reviewed, open source C++ libraries. It provides a wide range of functionality, including algorithms,
data structures, concurrency, networking, and more.
b. Boost libraries are designed to work well with C++ 11 and often serve as a testing ground for new features before they are standardized. They
are known for their quality, portability, and extensive documentation.
Introduction to C++ Programming:
What is C++?
Features of C++?
The syntax of C++ is almost identical to that of C, as C++ was developed as an extension of C.
In contrast to C, C++ supports classes and objects, while C does not.
What is a Compiler?
A compiler is used to run the program of a certain language which is generally high-level by
converting the code into a language that is low-level that our computer could understand.
#include <iostream>
Using namespace std;
int main()
{
cout << "Hello World";
return 0;
}
Output:
Hello World
It is common for C++ programs to include many built-in elements from the standard C++ library,
including classes, keywords, constants, operators, etc. It is necessary to include an appropriate header
file in a program in order to use such pre-defined elements.
In the above program, #include <iostream> was the line put to include the header file iostream. The
iostream library helps us to get input data and show output data.
Definition Section
Here, all the variables, or other user-defined data types are declared. These variables are used
throughout the program and all the functions.
Function Declaration
After the definition of all the other entities, here we declare all the functions a program
needs. These are generally user-defined.
Every program contains one main parent function which tells the compiler where to start
the execution of the program.
All the statements that are to be executed are written in the main function.
Only the instructions enclosed in curly braces {} are considered for execution by the compiler.
After all instructions in the main function have been executed, control leaves the main
function and the program ends.
1. Keywords
Keywords are reserved words that can not be used elsewhere in the program for naming a variable or
a function. They have a specific function or task and they are solely used for that. Their functionalities
are pre-defined.
2. Identifiers
Identifiers are names given to variables or functions to differentiate them from one another. Their
definitions are solely based on our choice but there are a few rules that we have to follow while
naming identifiers. One such rule says that the name can not contain special symbols such as @, -, *, <,
etc.
C++ is a case-sensitive language so an identifier containing a capital letter and another one containing
a small letter in the same place will be different. For example, the three words: Code, code, and cOde
can be used as three different identifiers.
3. Constants
Constants are very similar to a variable and they can also be of any data type. The only difference
between a constant and a variable is that a constant’s value never changes.
4. String Literal
String literals or string constants are a sequence of characters enclosed in double quotation marks.
Escape sequences are also string literals.
5. Symbols and Operators
Symbols are special characters reserved to perform certain actions. Using them lets the compiler know
what specific tasks should be performed on the given data. Several examples of symbols are
arithmetical operators such as +, *, or bitwise operators such as ^, &.
C++ Comments
A comment is a human-readable text in the source code, which is ignored by the compiler. Comments
can be used to insert any informative piece which a programmer does not wish to be executed. It
could be either to explain a piece of code or to make it more readable.
Comments can be singled-lined or multi-lined.
Multi-line comments
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables.
Some of them are as follows:
an integer variable defined with the keyword int stores integers (whole numbers), without
decimals, such as 63 or -1.
a floating point variable defined with keyword float stores floating point numbers, with
decimals, such as 79.97 or -13.26.
a character variable defined with the keyword char stores single characters, such as 'A' or 'z'.
Char values are bound to be surrounded by single quotes.
a boolean variable defined with the keyword bool stores a single value 0 or 1 for false and
true respectively.
Naming a Variable
Variable Scope
The scope of a variable is the region in a program where the existence of that variable is valid. Based
on its scope, variables can be classified into two types:
Local variables:
Local variables are declared inside the braces of any function and can be assessed only from that
particular function.
Global variables:
Global variables are declared outside of any function and can be accessed from anywhere.
A variable, as its name is defined, can be altered, or its value can be changed, but the same is not true
for its type. If a variable is of integer type, it will only store an integer value through a program. We
cannot assign a character type value to an integer variable. We can not even store a decimal value into
an integer variable.
Data types define the type of data a variable can hold; for example, an integer variable can hold
integer data, a character can hold character data, etc.
Data types in C++ are categorized into three groups:
These data types are pre-defined for a language and could be used directly by the programmer.
Examples are: Int, Float, Char, Double, Boolean
Some of the popular built-in data types and their applications are:
These data types are derived from the primitive built-in data types.
Examples are: Array, Pointer, Function
C++ Constants
Constants are unchangeable; when a constant variable is initialized in a program, its value cannot be
changed afterwards.
C++ Operators
Special symbols that are used to perform actions or operations are known as operators. They could be
both unary or binary.
For example, the symbol + is used to perform addition in C++ when put in between two numbers, so it
is a binary operator. There are different types of operators. They are as follows:
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, etc.
They could be both binary and unary. A few of the simple arithmetic operators are
Example:
#include <iostream>
int main()
int a = 4, b = 5;
cout << "The value of a++ is " << a++ << endl;
cout << "The value of a-- is " << a-- << endl;
cout << "The value of ++a is " << ++a << endl;
cout << "The value of --a is " << --a << endl;
Output:
The value of a + b is 9
The value of a - b is -1
The value of a * b is 20
The value of a / b is 0
The value of a % b is 4
Relational Operators
Relational operators are used to check the relationship between two operands and to compare two or
more numbers or even expressions in cases. The return type of a relational operator is a Boolean that
is, either True or False (1 or 0).
#include <iostream>
Example:
int main()
int a = 4, b = 5;
cout << "The value of a < b is " << (a < b) << endl;
cout << "The value of a > b is " << (a > b) << endl;
Output:
Logical Operators
Logical Operators are used to check whether an expression is true or false. There are three logical
operators i.e. AND, OR, and NOT. They can be used to compare Boolean values but are mostly used to
compare expressions to see whether they are satisfying or not.
AND: it returns true when both operands are true or 1.
OR: it returns true when either operand is true or 1.
NOT: it is used to reverse the logical state of the operand and is true when the operand is
false.
#include <iostream>
int main()
int a = 1, b = 0;
cout << "The value of a && b is " << (a && b) << endl;
Output:
The value of a || b is 1
The value of !a is 0
Assignment Operators
Assignment operators are used to assign values.
Important Points:
1. Implicit Conversion
The type conversion that is done automatically done by the compiler is known as implicit type conversion. This type of
conversion is also known as automatic conversion.
C++ Explicit Conversion
When the user manually changes data from one type to another, this is known as explicit conversion. This type of
conversion is also known as type casting.
Types of Errors
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
4. Linked Errors
5. Semantic Errors
Syntax Errors
These are also referred to as compile-time errors. These errors have occurred when the rule of C++ writing
techniques or syntax has been broken. These types of errors are typically flagged by the compiler prior to
compilation.
Runtime Errors
A runtime error occurs when a program you're using or writing crashes or produces a wrong output.
Logical Errors
Even if the syntax and other factors are correct, we may not get the desired results due to logical issues.
These are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically
correct but results in one blank loop. In that case, it will display the desired output.
Linker Errors
When the program is successfully compiled and attempting to link the different object files with the main
object file, errors will occur. When this error occurs, the executable is not generated. This could be due to
incorrect function prototyping, an incorrect header file, or other factors. If main() is written as Main(), a
linked error will be generated.
Semantic Errors
When a sentence is syntactically correct but has no meaning, semantic errors occur. This is similar to
grammatical errors. If an expression is entered on the left side of the assignment operator, a semantic
error may occur.
What is an Algorithm?
An algorithm is a set of commands that must be followed for a computer to perform calculations or other problem-
solving operations.According to its formal definition, an algorithm is a finite set of instructions carried out in a
specific order to perform a particular task. It is not the entire program or code; it is simple logic to a problem
represented as an informal description in the form of a flowchart or pseudocode.
Problem: A problem can be defined as a real-world problem or real-world instance problem for which you
need to develop a program or set of instructions. An algorithm is a set of instructions.
Algorithm: An algorithm is defined as a step-by-step process that will be designed for a problem.
Input: After designing an algorithm, the algorithm is given the necessary and desired inputs.
Processing unit: The input will be passed to the processing unit, producing the desired output.
Example
Now, use an example to learn how to write algorithms.
Problem: Create an algorithm that multiplies two numbers and displays the output.
Step 1 − Start
Step 6 − print z
Step 7 − Stop
Pseudocode
• When we broke down the problem into steps, we expressed each step as an English phrase.
• We can think of this as writing pseudocode for the problem.
• Typically, pseudocode is a combination of English phrases and formulas.
• Pseudocode is used in
• designing algorithms
• communicating an algorithm to the customer
• converting an algorithm to code (used by the programmer)
Example:
End_While
Control Structure
The work of control structures is to give flow and logic to a program. There are three types of basic
control structures in C++.
Sequence Structure
Sequence structure refers to the sequence in which program execute instructions one after another.
Selection Structure
Selection structure refers to the execution of instruction according to the selected condition, which can
be either true or false. There are two ways to implement selection structures. They are done either by
if-else statements or by switch case statements.
Loop Structure
Loop structure refers to the execution of an instruction in a loop until the condition gets false.
C++ If Else
If else statements are used to implement a selection structure. Like any other programming language,
C++ also uses the if keyword to implement the decision control instruction.
The condition for the if statement is always enclosed within a pair of parentheses. If the condition is
true, then the set of statements following the if statement will execute. And if the condition evaluates
to false, then the statement will not execute, instead, the program skips that enclosed part of the
code.
An expression in if statements are defined using relational operators. The statement written in an if
block will execute when the expression following if evaluates to true. But when the if block is followed
by an else block, then when the condition written in the if block turns to be false, the set of
statements in the else block will execute.
#include <iostream>
int main()
int age;
else
The break keyword in a case block indicates the end of a particular case. If we do not put the break in
each case, then even though the specific case is executed, the switch will continue to execute all the cases
until the end is reached. The default case is optional. Whenever the expression's value is not matched
with any of the cases inside the switch, then the default case will be executed.
Example:
#include <iostream>
int main()
{
int i = 2;
switch (i)
case 1:
break;
case 2:
break;
default:
The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as
of if-else statement but the conditional operator takes less space and helps to write the if-else statements
in the shortest way possible. It is also known as the ternary operator in C as it operates on three operands.
Syntax of Conditional/Ternary Operator in C
The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Break Statement
Break statement is used to break the loop or switch case statements execution and brings the control
to the next block of code after that particular loop or switch case it was used in.
Break statements are used to bring the program control out of the loop it was encountered in. The
break statement is used inside loops or switch statements in C++ language.
Example:
#include <iostream>
int main()
{
int i;
if (i == 6)
break;
return 0;
Continue Statement
The continue statement is used inside loops in C++ language. When a continue statement is
encountered inside the loop, the control jumps to the beginning of the loop for the next iteration,
skipping the execution of statements inside the body of the loop after the continue statement.
It is used to bring the control to the next iteration of the loop. Typically, the continue statement skips
some code inside the loop and lets the program move on with the next iteration. It is mainly used for
a condition so that we can skip some lines of code for a particular condition.
It forces the next iteration to follow in the loop unlike a break statement, which terminates the loop
itself the moment it is encountered.
Example:
#include <iostream>
int main()
{
if (i < 6)
continue;
return 0;
C++ Loops
The need to perform an action, again and again, with little or no variations in the details each time
they are executed is met by a mechanism known as a loop. This involves repeating some code in the
program, either a specified number of times or until a particular condition is satisfied. Loop-controlled
instructions are used to perform this repetitive operation efficiently ensuring the program doesn’t look
redundant at the same time due to the repetitions.
For Loop
While Loop
Do While Loop
For Loop
A for loop is a repetition control structure that allows us to efficiently write a loop that will execute a
specific number of times. The for-loop statement is very specialized. We use a for loop when we
already know the number of iterations of that particular piece of code we wish to execute. Although,
when we do not know about the number of iterations, we use a while loop which is discussed next.
Here,
initialize counter: It will initialize the loop counter value. It is usually i=0.
test counter: This is the test condition, which if found true, the loop continues, otherwise
terminates.
Increment/decrement counter: Incrementing or decrementing the counter.
Set of statements: This is the body or the executable part of the for loop or the set of
statements that has to repeat itself.
Example:
#include <iostream>
int main()
int i;
return 0;
First, the initialization expression will initialize loop variables. The expression i=0 executes once when
the loop starts. Then the condition i < num is checked. If the condition is true, then the statements
inside the body of the loop are executed. After the statements inside the body are executed, the
control of the program is transferred to the increment of the variable i by 1. The expression i++
modifies the loop variables. Iteratively, the condition i < num is evaluated again.
The for loop terminates when i finally becomes greater than num, therefore, making the condition
i<num false.
While Loop
A While loop is also called a pre-tested loop. A while loop allows a piece of code in a program to be
executed multiple times, depending upon a given test condition which evaluates to either true or false.
The while loop is mostly used in cases where the number of iterations is not known. If the number of
iterations is known, then we could also use a for loop as mentioned previously.
Example:
#include <iostream>
int main()
int i = 5;
i++;
return 0;
Do While Loop
A do-while loop is a little different from a normal while loop. A do-while loop, unlike what happens in
a while loop, executes the statements inside the body of the loop before checking the test condition.
So even if a condition is false in the first place, the do-while loop would have already run once. A do-
while loop is very much similar to a while loop, except for the fact that it is guaranteed to execute the
body at least once.
Unlike for and while loops, which test the loop condition first, then execute the code written inside the
body of the loop, the do-while loop checks its condition at the end of the loop.
Following is the syntax for using a do-while loop.
First, the body of the do-while loop is executed once. Only then, the test condition is evaluated. If the
test condition returns true, the set of instructions inside the body of the loop is executed again, and
the test condition is evaluated. The same process goes on until the test condition becomes false. If the
test condition returns false, then the loop terminates.
Example:
#include <iostream>
int main()
int i = 5;
do
i++;
return 0;
Here, even if i was less than 5 from the very beginning, the do-while let the print statement execute
once, and then terminated.
Arrays
An array is a collection of items that are of the data type stored in contiguous memory locations. And
it is also known as a subscript variable.
It can even store the collection of derived data types such as pointers, structures, etc.
An array can be of any dimension. The C++ Language places no limits on the number of dimensions in
an array. This means we can create arrays of any number of dimensions. It could be a 2D array or a
3D array or more.
Advantages of Arrays?
It is used to represent multiple data items of the same type by using only a single name.
Accessing any random item at any random position in a given array is very fast in an array.
There is no case of memory shortage or overflow in the case of arrays since the size is fixed
and elements are stored in contiguous memory locations.
Defining an array
3. int arr[3];
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3};
cout << arr[1] << endl;
}
Output:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3};
arr[2] = 8; //changing the element on index 2
cout << arr[2] << endl;
}
Output:
Pointers
A pointer is a data type that holds the address of another data type. A pointer itself is a variable that
points to any other variable. It can be of type int, char, array, function, or even any other pointer.
Pointers in C++ are defined using the ‘*’ (asterisk) operator.
The ‘&’(ampersand) operator is called the ‘address of’ operator, and the ‘*’(asterisk) operator is called
the ‘value at’ dereference operator.
Applications of a Pointer
Operations on Pointers
& is also known as the Referencing Operator. It is a unary operator. The variable name used along
with the Address of operator must be the name of an already defined variable.
Using & operator along with a variable gives the address number of the variable.
Here’s one example to demonstrate the use of the address of the operator.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << "Address of variable a is " << &a << endl;
return 0;
}
Output:
0x61febc
Indirection Operator
* is also known as the Dereferencing Operator. It is a unary operator. It takes an address as its
argument and returns the content/container whose address is its argument.
#include <iostream>
using namespace std;
int main()
{
int a = 100;
cout << "Value of variable a stored at address " << &a << " is " << (*(&a)) << endl;
return 0;
}
Output:
Pointer to Pointer
Pointer to Pointer is a simple concept, in which we store the address of one pointer to another
pointer. This is also known as multiple indirections owing to the operator’s name. Here, the first
pointer contains the address of the second pointer, which points to the address where the actual
variable has its value stored.
#include <iostream>
using namespace std;
int main()
{
int a = 100;
int *b = &a;
int **c = &b;
cout << "Value of variable a is " << a << endl;
cout << "Address of variable a is " << b << endl;
cout << "Address of pointer b is " << c << endl;
return 0;
}
Output:
Storing the address of an array into pointer is different from storing the address of a variable into the
pointer. The name of an array itself is the address of the first index of an array. So, to use the
(ampersand)& operator with the array name for assigning the address to a pointer is wrong. Instead,
we used the array name itself.
An example program for storing the starting address of an array in the pointer,
Output:
In order to access other elements of the same array that pointer p points to, we can use pointer
arithmetic, such as addition and subtraction of pointers.
*(p+1) returns the value at the second position in the array marks. Here’s how it works.
Output:
Strings
A string is an array of characters. Unlike in C, we can define a string variable and not necessarily a
character array to store a sequence of characters. Data of the same type are stored in an array, for
example, integers can be stored in an integer array, similarly, a group of characters can be stored in a
character array or a string variable. A string is a one-dimensional array of characters.
Declaring a string is very simple, the same as declaring a one-dimensional array. It’s just that we are
considering it as an array of characters.
string string_name ;
In the above syntax, string_name is any name given to the string variable and it can be given a string
input later or it can even be initialised at the time of definition.
Example of a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// declare and initialise string
string str = "We Are on the cruise";
cout << str << endl;
return 0;
}
Output:
Functions
Functions are the main part of top-down structured programming. We break the code into small
pieces and make functions of that code. Functions could be called multiple or several times to provide
reusability and modularity to the C++ program.
Functions are also called procedures or subroutines or methods and they are often defined to perform
a specific task. And that makes functions a group of code put together and given a name that can be
called anytime without writing the whole code again and again in a program.
Advantages of Functions
The use of functions allows us to avoid re-writing the same logic or code over and over again.
With the help of functions, we can divide the work among the programmers.
We can easily debug or can find bugs in any program using functions.
They make code readable and less complex.
Aspects of a function
Declaration: This is where a function is declared to tell the compiler about its existence.
Definition: A function is defined to get some task executed. (It means when we define a
function, we write the whole code of that function and this is where the actual
implementation of the function is done).
Call: This is where a function is called in order to be used.
The function prototype is the template of the function which tells the details of the function which
include its name and parameters to the compiler. Function prototypes help us to define a function
after the function call.
// Function prototype
return_datatype function_name(datatype_1 a, datatype_2 b);
Types of functions
Library functions:
Library functions are pre-defined functions in C++ Language. These are the functions that are included
in C++ header files prior to any other part of the code in order to be used.
E.g. sqrt(), abs(), etc.
User-defined functions
User-defined functions are functions created by the programmer for the reduction of the complexity
of a program. Rather, these are functions that the user creates as per the requirements of a program.
E.g. Any function created by the programmer.
Functions Parameters
A function receives information that is passed to them as a parameter. Parameters act as variables
inside the function.
Parameters are specified collectively inside the parentheses after the function name. parameters inside
the parentheses are comma separated.
Formal Parameters
So, the variable which is declared in the function is called a formal parameter or simply, a parameter.
For example, variables a and b are formal parameters.
Actual Parameters
The values which are passed to the function are called actual parameters or simply, arguments. For
example, the values num1 and num2 are arguments.
The file is a patent of data stored on the disk. Anything written inside the file is called a patent, for
example: “#include” is a patent. The text file is the combination of multiple types of characters, for
example, the semicolon “;” is a character.
The computer read these characters in the file with the help of the ASCII code. Every character is
mapped on some decimal number. For example, the ASCII code for the character A is 65 which is a
decimal number. These decimal numbers are converted into binary numbers to make them readable
for the computer because the computer can only understand the language of 0 & 1.
A large program deployed for heavy applications cannot function without files, since we can get input
from them as well as print output from them very easily. We can also save a lot of program space by
accessing the file's data only when needed, making the program more efficient and faster.
Files are stored in non-volatile memory which is better in terms of storing data. Non-volatile memory
stays intact even after the system shuts down. They get retrieved again after the system is turned on.
Operations on files
Creating a File:
We can create a file using C++ language, in any directory, without even leaving our compiler. We can
select the name or type we want our file to have, along with its location.
Opening a File:
We can open an existing file and create a new file and open it using our program. We can perform
different operations on a file after it has been opened.
Closing a File:
When we are done with the file, meaning that we have performed whatever we want to perform on
our file, we can close the file using the close function.
Read/Write to a file:
After opening a file, we can access its contents and read, write, or update them.
These are some useful classes for working with files in C++
fstream - A combination of ofstream and ifstream: creates, reads, and writes to files
ofstream - creates and writes to files
ifstream - reads from files
The fstream library allows us to handles files. So, to be able to use files in a program, one must include
the <fstream> header file.
A. Opening a file
In order to work with files in C++, we will first have to open it. Primarily, there are two ways to open
a file:
A file could be opened for a number of uses. It could be to write to it or to read from it.
#include <iostream>
#include <fstream>
int main()
{
ofstream out("example.txt");
return 0;
}
The file example.txt gets created if it’s not already there in the system and opened. Object out gets
created of the type ofstream, which means it could only be used to write into the opened file.
#include <iostream>
#include <fstream>
For this to work, a file named example.txt must already be created and present in the same folder as
that of the program. Object in gets created of the type ifstream, which means it could only be used to
read from the file.
B. Closing a file
When working with C++, closing open files is considered a good practice. A programmer often makes
the mistake of not closing an open file. This becomes crucial because files do not automatically get
closed after a program uses them. The closing has to be done manually.
To close a file, we have to use the close method. This is how we use them in C++.
Syntax:
file_objectname.close();
C. Writing to a file
Writing to a file is as easy as printing any other stuff in C++. It is very similar to what we used to do
when we had to print an output in the terminal. In order to write to a file, we use the insertion
operator (<<). First, we create an object of the type ofstream and pass the name of the file along with
its extension to the method. And then, use the extraction operator to write stuff in the file fed to the
object.
Example:
#include <iostream>
#include <fstream>
int main()
{
string str = "Welcome_To_New Great Pirate Era!";
ofstream out("example.txt");
out << str;
return 0;
}
Reading from a file is as easy as reading any other stuff as an input in C++. It is very similar to what
we used to do when we had to read input from the terminal. In order to read from a file, we use the
extraction operator (>>). First, we create an object of the type ifstream and pass the name of the file
along with its extension to the method. And then, use the extraction operator to read stuff from the
file fed to the object.
Example:
#include <iostream>
#include <fstream>
int main()
{
string str;
ifstream in("example.txt");
in >> str;
cout << str;
return 0;
}
Copy
The file example.txt had “Welcome_To_New Great Pirate Era!” as its content, hence the output:
Practice Questions:
Calculator
3. Write a program to take the marks obtained by a student in five different subjects through the
keyboard, find out the aggregate marks and percentage marks obtained by the student. Assume
that the maximum marks that can be obtained by a student in each subject is 100.