Nothing Special   »   [go: up one dir, main page]

C++ Project File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

A

INTERNSHIP REPORT
On

“Beginning of C++ Programming


-From Beginner to Beyond”
Submitted in partial fulfillment of the requirement
for the award of the degree
of

BACHELOR OF TECHNOLOGY
in
“Computer Science and Engineering”
by

SHIVANGI SRIVASTAVA
(Roll No: 1901200100106)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


INSTITUTE OF TECHNOLOGY & MANAGEMENT, GIDA, GORAKHPUR

SESSION: 2021-22
INSTITUTE OF TECHNOLOGY & MANAGEMENT
GIDA, GORAKHPUR

CANDIDATE’S DECLARATION / CERTIFICATE


This is certified that the work which is being presented in the mini project entitled “Beginning of C++ Programming-
From Beginner to Beyond” in partial fulfillment of the requirement for the award of the degree of Bachelor of
Technology and submitted in the Department of Computer Science and Engineering of Institute of Technology &
Management, GIDA, Gorakhpur is an authentic record of my own work carried out during the semester under the
supervision of “UDEMY”.

The matter presented in this mini project has not been submitted by me for the award of any other degree of this or any
other Institute/University.

SHIVANGI SRIVASTAVA

This is to certify that the above statement made by the candidate is correct to the best of my knowledge.

Date: 20/12/2021 (Candidate Signature)

Mr. CHHITEESH RAI Mrs. SACHI MALL

Mini Project Coordinator H.O.D (CSE/IT)


ABSTRACT

In this project report, I have presented an overview of C++ language. The whole report is divided into nine
main chapters. Each chapter is further divided in several subtopics. There are nine chapters in total stated as
Introduction to Programming Languages, Programming Fundamentals I, Programming Fundamentals
II, Functions, Space and Time Complexity, Character Arrays, Pointers, Dynamic Memory Allocation,
STL-Strings. Every subtopic contains detailed explanation about the topic.
ACKNOWLEDGEMENT

Whenever a module of work is completed, there is always a source of inspiration. I always find my
parents as my torch bearers. While completing this task, I realized from my inner core that Rome was not built
in day. I found a stack of mini project reports in the library of ITM Gorakhpur library. Those reports are the
landmarks for me on the way of this task. The presented report is an effort of day and night works. Selection
is always tough; undoubtedly I am accepting this fact.

I am sincerely thankful to HOD(CSE/IT) Mrs. SACHI MALL & MINI PROJECT COORDINATOR
Mr. CHHITEESH RAI SIR for his support. I express my gratitude and thanks to all the faculties and staff
members of Computer Science & Engineering department for their sincere cooperation in furnishing relevant
information to complete this mini project report well in time successfully.

Finally, my greatest debt is to my parents, my family for their enduring love, support and forbearance
during my project work.

SHIVANGI SRIVASTAVA

B.Tech. (CSE), 5th Sem.

(ROLL NO: 1901200100106)


LIST OF FIFURES

Figure No Title Page No.

1.1 Shapes used in Flowchart 8


1.2 Flowchart of sum of 2 numbers 9
5.1 Space & Time Complexity 25
6.1 Taking input & printing output 27
6.2 Code for Palindrome char array 27
6.3 Code for largest word in a sentence 28
7.1 Working demo of Pointer 29

LIST OF TABLES

Table No Title Page No.

2.1 Data-types in C++ 12


2.2 C++ Type Modifiers 13
3.1 Arithmetic Operators 19
3.2 Relational Operators 20
3.3 Logical Operators 20
3.4 Bitwise Operators 21
3.5 Assignment Operators 21
3.6 Misc Operators 21
3.7 Precedence of Operators 22
INDEX

Title Page No.


Certificate iii
Abstract iv
Acknowledgement v
List of Figures vi
List of Tables Vi

1. Introduction to Programming Languages 8-11


1.1 Computer Program and Programming Languages 8-9
1.2 Algorithm 9
1.3 Flowchart 9
1.4 Pseudocode 9-10
1.5 A little about C++ Language 10
1.6 Hello world program 10-11
2. Programming Fundamentals l 12-17
2.1 Data Types in C++ 12-13
2.2 C++ Type Modifiers 13
2.3 Input and output in C++ 13-14
2.4 Decision Making 15-16
2.5 Loops in C++ 16-17
3. Programming Fundamentals ll 18-22
3.1 Jumps in Loops 18
3.2 Switch Statement 18-19
3.3 Operators in C++ 19-22
4. Functions 23-24
4.1 Introduction to Functions 23
4.2 Examples 23-24
5. Space and Time complexity 25-26
5.1 Time Complexity 25-26
5.2 Space Complexity 26
6. Character Arrays 27-28
6.1 Introduction 27
6.2 Important Questions 27-28
7. Pointers 29
7.1 Getting Started with Pointers 29
7.2 Array Pointers 29
8. Dynamic Memory Allocation 30
8.1 Stack Memory Allocation 30
8.2 Heap Memory Allocation 30
8.3 Delete and New Operator 30
9. STL-Strings 31-32
9.1 Introduction 31
9.2 Different Functions of String 31-32
1. Introduction to Programming Languages
1.1 Computer Program and Programming Languages
A program is a set of instructions that tells a computer what to do in order to come up with a solution
to a particular problem. Programs are written using a programming language. A programming language
is a formal language designed to communicate instructions to a computer. There are two major types of
programming languages: low-level languages and high-level languages.

Low-Level Languages

Low-level languages are referred to as 'low' because they are very close to how different hardware elements
of a computer actually communicate with each other. Low-level languages are machine oriented and require
extensive knowledge of computer hardware and its configuration. There are two categories of low-level
languages: machine language and assembly language.
Machine language, or machine code, is the only language that is directly understood by the computer,
and it does not need to be translated. All instructions use binary notation and are written as a string of 1s
and 0s. However, binary notation is very difficult for humans to understand. This is where
assembly languages come in.
An assembly language is the first step to improve programming structure and make machine language
more readable by humans. An assembly language consists of a set of symbols and letters. A translator is
required to translate the assembly language to machine language called the 'assembler.'
While easier than machine code, assembly languages are still pretty difficult to understand. This is why
high-level languages have been developed.

High-Level Languages

A high-level language is a programming language that uses English and mathematical symbols, like +, -, %
and many others, in its instructions. When using the term 'programming languages,' most people are
actually referring to high-level languages. High-level languages are the languages most often used by
programmers to write programs. Examples of high-level languages are C++, Fortran, Java and Python.
Learning a high-level language is not unlike learning another human language - you need to learn
vocabulary and grammar so you can make sentences. To learn a programming language, you need to
learn commands, syntax and logic, which correspond closely to vocabulary and grammar.
The code of most high-level languages is portable and the same code can run on different hardware
without modification. Both machine code and assembly languages are hardware
specific which means that the machine code used to run a program on one specific computer
needs to be modified to run on another computer.
A high-level language cannot be understood directly by a computer, and it needs to be translated into
machine code. There are two ways to do this, and they are related to how the program is executed: a
high-level language can be compiled or interpreted.

Compiler vs Interpreter
A compiler is a computer program that translates a program written in a high-level language to the
machine language of a computer.
The high-level program is referred to as 'the source code.' The compiler is used to translate source code
into machine code or compiled code. This does not yet use any of the input data. When the compiled code
is executed, referred to as 'running the program,' the program processes the input data to produce the
desired output.
An interpreter is a computer program that directly executes instructions written in a programming
language, without requiring them previously to have been compiled into a machine language program.

1.2 Algorithm
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain
order to get the desired output. Algorithms are generally created independent of underlying languages,
i.e. an algorithm can be implemented in more than one programming language.

Qualities of a good algorithm

1. Input and output should be defined precisely.


2. Each step in the algorithm should be clear and unambiguous.
3. An algorithm should be written in such a way that it can be used in different programming
languages.

Good, logical programming is developed through good pre-code planning and organization. This is
assisted by the use of pseudocode and program flowcharts.

1.3 Flowcharts
Flowcharts are written with program flow from the top of a page to the bottom. Each command is
placed in a box of the appropriate shape, and arrows are used to direct program flow. The following
shapes are often used in flowcharts:

Fig.1.1 Shapes often used in Flowchart

1.4 Pseudocode
Pseudocode is a method of describing computer algorithms using a combination of natural language and
programming language. It is essentially an intermittent step towards the development of the actual
code. It allows the programmer to formulate their thoughts on the organization and sequence of a
computer algorithm without the need for actually following the exact coding syntax.

Examples: Write a flowchart and pseudocode for finding the sum of 2 numbers.

Fig.1.2 Flowchart of Sum of 2 numbers

Pseudocode
1. Start
2. Input 2 numbers ʹ number1 and number2
3. Add number1 and number2 to find sum
4. Print sum
5. End

1.5 A little about C++ language

C++ is a cross-platform language that can be used to create high-performance applications. It was
developed by Bjarne Stroustrup, as an extension to the C language. The language was updated 3 major
times in 2011, 2014, and 2017 to C++11, C++14, and C++17.

Why Use C++?


1. C++ is one of the world's most popular programming languages.
2. C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.
3. C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.
4. C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
5. C++ is fun and easy to learn!
6. As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa.

1.6 Hello World Program


// Hello world program in C++
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!\n";
return 0;}
1. Comments
The two slash (//) signs are used to add comments in a program. It does not have any effect on the
behaviour or outcome of the program. It is used to give description of the program you’re writing.

2. #include<iostream>
#include is the pre-processor directive that is used to include files in our program. Here we are including
the iostream standard file which is necessary for the declarations of basic standard input/output library in
C++.

3. Using namespace std


All elements of the standard C++ library are declared within namespace. Here we are using std namespace.

4. int main()
The execution of any C++ program starts with the main function, hence it is necessary to have a main
function in your program. ‘int’ is the return value of this function. (We will be studying about functions in
more detail later).

5. {}
The curly brackets are used to indicate the starting and ending point of any function. Every opening
bracket should have a corresponding closing bracket.

6. Cout<<”Hello World!\n”;
This is a C++ statement. cout represents the standard output stream in C++. It is declared in the iostream
standard file within the std namespace. The text between quotations will be printed on the screen.
\n will not be printed, it is used to add line break.
Each statement in C++ ends with a semicolon (;)

7. return 0;
return signifies the end of a function. Here the function is main, so when we hit return 0, it exits the
program. We are returning 0 because we mentioned the return type of main function as integer (int main).
A zero indicates that everything went fine and a one indicates that something has gone wrong.
2. Programming Fundamentals I

Variables
A variable is a container (storage area) used to hold data. Each variable should be given a unique name
(identifier).
int a=2;
Here a is the variable name that holds the integer value 2. The value of a can be changed, hence the name
variable.

There are certain rules for naming a variable in C++ :


1. Can only have alphabets, numbers and underscore.
2. Cannot begin with a number.
3. Cannot begin with an uppercase character.
4. Cannot be a keyword defined in C++ language (like int is a keyword).

2.1 Data Types in C++


Data types are declarations for variables. This determines the type and size of data associated with
variables which is essential to know since different data types occupy different size of memory.

Data Type Meaning Size (in Bytes)


int Integer 4
float Floating-point 4
double Double Floating-point 8
char Character 1
Wchar_t Wide Character 2
bool Boolean 1
void Empty 0
Tab.2.1 Data-types in C++

1. Int
• This data type is used to store integers.
• It occupies 4 bytes in memory.
• It can store values from -2147483648 to 2147483647.
Eg. int age = 18

2. float and double


• Used to store floating-point numbers (decimals and exponentials)
• Size of float is 4 bytes and size of double is 8 bytes.
• Float is used to store upto 7 decimal digits whereas double is used to store upto 15 decimal digits.
Eg. float pi = 3.14
double distance = 24E8 // 24 x 108

3. Char
• This data type is used to store characters.
• It occupies 1 byte in memory.
• Characters in C++ are enclosed inside single quotes.
• ASCII code is used to store characters in memory.
Eg.͘ char ch = ‘a’
4. Bool
• This data type has only 2 values ʹ true and false.
• It occupies 1 byte in memory.
• True is represented as 1 and false as 0.
Eg. bool flag = false

2.2 C++ Type Modifiers


Type modifiers are used to modify the fundamental data types.
Data Type Size (in Bytes) Meaning
signed int 4 used for integers (equivalent to int)
unsigned int 4 can only store positive integers
short 2 used for small integers (range -32768 to 32767)
long at least 4 used for large integers (equivalent to long int)
used for very large integers (equivalent to long
long int 8
long int).
unsigned long used for very large positive integers or 0
8
long (equivalent to unsigned long long int)
long double 8 used for large floating-point numbers
used for characters (guaranteed range -127 to
signed char 1
127)
unsigned char 1 used for characters (range 0 to 255)
Tab. 2.2 C++ Type Modifiers
Derived Data Types
These are the data types that are derived from fundamental (or built-in) data types.
For example, arrays, pointers, function, reference.

User-Defined Data Types


These are the data types that are defined by user itself.
For example, class, structure, union, enumeration, etc.

2.3 Input and Output in C++


The header file iostream must be included to make use of the input/output (cin/cout) operators.

Standard Output (cout)


By default, the standard output of a program points at the screen. So with the cout operator and the
“insertion” operator (<<) you can print a message onto the screen.
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
To print the content of a variable the double quotes are not used.
#include<iostream>
using namespace std;
int main()
{
char Yes = 'y';
cout << Yes;
return 0;
}
The << operator can be used multiple times in a single statement. Take a look at an example:
#include<iostream>
using namespace std;
int main()
{
cout << "Hello, " << "this is a test " << "string.";
return 0;
}
It is possible to combine variables and text:
#include<iostream>
using namespace std;
int main()
{
char Yes = 'y';
cout << "Print the character " << Yes;
return 0;
}
The cout operator does not put a line break at the end of the output. So if you want to print two sentences
you will have to use the new-line character ( \n ).
cout << "This is one sentence.\n";
cout << "This is another.\n";
It is possible to use the endl manipulator instead of the new-line character.
cout << "This is one sentence." << endl;
cout << "This is another." << endl;

Standard input (cin)


In most cases the standard input device is the keyboard. With the cin and >> operators it is possible to read
input from the keyboard.
Take a look at an example:
#include<iostream>
using namespace std;
int main()
{
char ch;
cout << "Press a character and press return: ";
cin >> ch;
cout << ch;
return 0;
}
Note: The input is processed by cin after the return key is pressed.
The cin operator will always return the variable type that you use with cin. So if you request an integer you
will get an integer and so on. This can cause an error when the user of the program does not return the
type that you are expecting. (Example: you ask for an integer and you get a string of characters.)
The cin operator is also chainable. For example:
cin >> X >> Y;
In this case the user must give two input values, that are separated by any valid blank separator (tab, space
or new-line).
2.4 Decision Making

if/else
The if block is used to specify the code to be executed if the condition specified in if is true, the else block is
executed otherwise.
#include <iostream>
using namespace std ;
int main () {
int age ;
cin >> age ;
if ( age >= 18 ) {
cout << "You can vote." ;
}
else {
cout << "Not eligible for voting." ;
}
return 0 ;
}

else if
To specify multiple if conditions, we first use if and then the consecutive statements use else if.
#include <iostream>
using namespace std ;
int main () {
int x,y ;
cin >> x >> y ;
if ( x == y ) {
cout << "Both the numbers are equal" ;
}
else if ( x > y ) {
cout << "X is greater than Y" ;
}
else {
cout << "Y is greater than X" ;
}
return 0 ;
}

nested if
To specify conditions within conditions we make the use of nested ifs.
#include <iostream>
using namespace std ;
int main () {
int x,y ;
cin >> x >> y ;
if ( x == y ) {
cout << "Both the numbers are equal" ;
}
else {
if ( x > y ) {
cout << "X is greater than Y" ;
}
else {
cout << "Y is greater than X" ;
}
}
return 0 ;
}

2.5 Loops in C++


A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. A loop
consists of an initialization statement, a test condition and an increment statement.

for loop
The syntax of the for loop is
for (initialization; condition; update) {
// body of-loop
}
#include<iostream>
using namespace std;
int main(){
for(int i=1;i<=5;i++){
cout<<i<<" ";
}
return 0;
}
Output –

The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of i
remains lesser than or equal to 5. In each iteration the value of i is incremented by one by doing i++.

while loop
The syntax for while loop is
while (condition) {
// body of the loop
}
#include<iostream>
using namespace std;
int main(){
int i=1;
while(i<=5){
cout<<i<<" ";
i++;
}
return 0;
}
Output

The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop is executed till the value of
i remains lesser than or equal to 5. In each iteration the value of i is incremented by one by doing i++.

do….while loop
The syntax for while loop is
do {
// body of loop;
}
while (condition);
#include<iostream>
using namespace std;
int main(){
int i=1;
do
{
cout<<i<<" ";
i++;
} while (i<=5);
return 0;
}
Output

The do while loop variable is initialized by the value 1, in each iteration the value of i is incremented by one
by doing i++, the test condition is i<=5 i.e the loop is executed till the value of i remains lesser than or equal
to 5. Since the testing condition is checked only once the loop has already run so a do while loop runs at
least once.
3. Programming Fundamentals II

3.1 Jumps in Loops


Jumps in loops are used to control the flow of loops. There are two statements used to implement jump in
loops - Continue and Break. These statements are used when we need to change the flow of the loop when
some specified condition is met.

1. Continue
Continue statement is used to skip to the next iteration of that loop. This means that it stops one iteration
of the loop. All the statements present after the continue statement in that loop are not executed.
int i;
for (i=1; i<=20; i++) {
if (i%3==0) {
continue;
}
cout<<i<<endl;
}
In this for loop, whenever i is a number divisible by 3, it will not be printed as the loop will skip to the next
iteration due to the continue statement.
Hence, all the numbers except those which are divisible by 3 will be printed.

2. Break
Break statement is used to terminate the current loop. As soon as the break statement is encountered in a
loop, all further iterations of the loop are stopped and control is shifted to the first statement after the end
of loop.
int i;
for (i=1; i<=20; i++) {
if (i==11) {
break;
}
cout<<i<<endl;
}
In this loop, when i becomes equal to 11, the for loop terminates due to break statement, Hence, the
program will print numbers from 1 to 10 only.

3.2 Switch Statement


Switch case statements are a substitute for long if statements that compare a variable to multiple values.
After a match is found, it executes the corresponding code of that value case.
Syntax:
switch (n)
{

case
1: // code to be executed if n==1;
break;
case 2: // code to be executed if n == 2;
break;
w
default: // code to be executed if n doesn't match any of the above cases
}
• The variable in switch should have a constant value.
• The break statement is optional. It terminates the switch statement and moves control to the next
line after switch.
• If break statement is not added, switch will not get terminated and it will continue onto the next
line after switch.
• Every case value should be unique.
• Default case is optional. But it is important as it is executed when no case value could be matched.

3.3 Operators in C++


Operators are nothing but symbols that tell the compiler to perform some specific operations. Operators
are of the following types -

1. Arithmetic Operators
Arithmetic operators perform some arithmetic operation on one or two operands. Operators that operate
on one operand are called unary arithmetic operators and operators that operate on two operands are
called binary arithmetic operators.
+,-,*,/,% are binary operators.
++, -- are unary operators.
Suppose : A=5 and B=10

Operator Operation Example


+ Adds two operands A+B = 15
- Subtracts right operand from left operand B-A = 5
* Multiplies two operands A*B = 50
/ Divides left operand by right operand B/A = 2
% Finds the remainder after integer division B%A = 0
++ Incrementer A++ = 6
-- Decrementer A-- = 4
Tab.3.1 Arithmetic Operators

Pre-incrementer : It increments the value of the operand instantly.


Post-incrementer : It stores the current value of the operand temporarily and only after that statement is
completed, the value of the operand is incremented.
Pre-decrementer : It decrements the value of the operand instantly.
Post-decrementer : It stores the current value of the operand temporarily and only after that statement is
completed, the value of the operand is decremented.

Example -
int a=10;
int b;
b = a++;
cout<<a<<" "<<b<<endl;
Output : 11 10

int a=10;
int b;
b = ++a;
cout<<a<<" "<<b<<endl;
Output : 11 11

2. Relational Operators
Relational operators define the relation between 2 entities. They give a boolean value as result i.e true or
false.
Suppose : A=5 and B=10
Operator Operation Example
A==B is not
== Gives true if two operands are equal
true
!= Gives true if two operands are not equal A!=B is true
Gives true if left operand is more than right A>B is not
>
operand true
< Gives true if left operand is less than right operand A<B is true
Gives true if left operand is more than right A>=B is not
>=
operand or equal to it true
Gives true if left operand is more than right
<= A<=B is true
operand or equal to it
Tab.3.2 Relational Operators

Example -
We need to write a program which prints if a number is more than 10, equal to 10 or less than 10. This
could be done using relational operators with if else statements.
int n;
cin>>n;
if(n<10){
cout<<"Less than 10"<<endl;
}
else if(n==10){
cout<<"Equal to 10"<<endl;
}
else{
cout<<"More than 10"<<endl;
}

3. Logical Operators
Logical operators are used to connect multiple expressions or conditions together.
We have 3 basic logical operators.
Suppose : A=0 and B=1

Operator Operation Example


(A && B) is
&& AND operator. Gives true if both operands are non-zero
false
OR operator. Gives true if atleast one of the two operands
|| (A || B) is true
are non-zero.
! NOT operator. Reverse the logical state of operand !A is true
Tab.3.3 Logical Operators

Example -
If we need to check whether a number is divisible by both 2 and 3, we will use AND operator
(num%2==0) && num(num%3==0)

If this expression gives true value then that means that num is divisible by both 2 and 3.
(num%2==0) || (num%3==0)

If this expression gives true value then that means that num is divisible by 2 or 3 or both.
4. Bitwise Operators
Bitwise operators are the operators that operate on bits and perform bitby-bit operations.
Suppose : A=5(0101) and B=6(0110)

Operator Operation Example


Binary AND. Copies a bit to the result if it exists in both 0101& 0110
&
operands. =0100
0101| 0110
| Binary OR. Copies a bit if it exists in either operand.
=0111
Binary XOR. Copies the bit if it is set in one operand but not 0101^ 0110
^
both. =0011
~0101=>
~ Binary Ones Complement. Flips the bit.
1010
4 (0100)
Binary Left Shift. The left operand’s bits are moved left by the
<< 4<<1
number of places specified by the right operand.
=1000 = 8
Binary Right Shift Operator. The left operand’s bit are moved 4>>1
>>
right by the number of places specified by the right operand. =0010 = 2
Tab.3.4 Bitwise Operators
If shift operator is applied on a number N then,
• N<<a will give a result N*2^a
• N>>a will give a result N/2^a

5. Assignment Operators
Operator Operation Example
A=B will put value
= Assigns value of right operand to left operand
of B in A
Adds right operand to the left operand and A+=B means A =
+=
assigns the result to left operand. A+B
Subtracts right operand from the left operand
-= A-=B means A=A-B
and assigns the result to left operand.
Multiplies right operand with the left operand
*= A*=B means A=A*B
and assigns the result to left operand.
Divides left operand with the right operand and
/= A/=B means A=A/B
assigns the result to left operand.
Tab.3.5 Assignment Operators

6. Misc Operators
Operator Operation Example
If a is integer then
sizeof() Returns the size of variable sizeof(a) will return
4
Condition? Conditional operator. If condition is true, then
A+=B means A=A+B
X:Y returns value of X or else value of Y
Casting operators convert one data type to int(4.350) would
Cast
another. return 4.
Comma operator causes a sequence of operations
to be performed. The value of the entire comma
Comma (,)
expression is the value of the last expression of the
comma-separated list.
Tab.3.6 Misc Operators
Precedence of Operators
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Tab. 3.7 Precedence of Operators
4. Functions

A function is a block of code that performs a specific task.

Why are functions used?


• If some functionality is performed at multiple places in software, then rather than writing the same
code, again and again, we create a function and call it everywhere. This helps reduce code redundancy.
• Functions make maintenance of code easy as we have to change at one place if we make future
changes to the functionality.
• Functions make the code more readable and easy to understand.

4.1 Introduction to Functions


The syntax for function declaration is
return-type function_name (parameter 1, parameterϮ …… parameter n){
//function_body
}

return-type
The return type of a function is the data type of the variable that that function returns.
For eg. if we write a function that adds 2 integers and returns their sum then the return type of this
function will be ‘int’ as we will returning sum that is an integer value.
When a function does not return any value, in that case the return type of the function is ‘void’.

function_name
It is the unique name of that function.
It is always recommended to declare a function before it is used.

Parameters
A function can take some parameters as inputs. These parameters are specified along with their data
types.
For eg. if we are writing a function to add 2 integers, the parameters would be passed like –
int add (int num1, int num2)

Main function
The main function is a special function as the computer starts running the code from the beginning of the
main function. Main function serves as the entry point for the program.

4.2 Examples
Ques1. Write a program to add 2 numbers using functions.
#include <iostream>
using namespace std;
int add(int num1, int num2){
int sum = num1 + num2;
return sum;
}
int main()
{
int a,b;
cin>>a>>b;
cout<<add(a,b)<<endl;
return 0;
}

Ques2. Write a program to print a given number using functions.


#include <iostream>
using namespace std;
void display(int a){
cout<<a<<endl;
return;
}
int main()
{
int a;
cin>>a;
print(a);
return 0;
}
5. Space and Time Complexity

Fig.5.1 Space & Time Complexity

5.1 Time Complexity


Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a
function of the length of the input.

Types of notations
1. O-notation: It is used to denote asymptotic upper bound. For a given function g(n), we denote it
by O(g(n)). Pronounced as “big-oh of g of n”. It also known as worst case time complexity as it
denotes the upper bound in which algorithm terminates.

2. Ω-notation: It is used to denote asymptotic lower bound. For a given function g(n), we denote it
by Ω(g(n)). Pronounced as “big-omega of g of n”. It also known as best case time complexity as it
denotes the lower bound in which algorithm terminates.

3. -notation: It is used to denote the average time of a program.

Examples:

Linear Time Complexity. O(n)

Quadratic time Complexity. O(n2)


Time complexity: O(n*m)

Time complexity: O(log(n))

Comparison of functions on the basis of time complexity


It follows the following order in case of time complexity:
O(nn) > O(n!) > O(n3) > O(n2) > O(n.log(n)) > O(n.log(log(n))) > O(n) > O(sqrt(n)) > O(log(n)) > O(1)

Note: Reverse is the order for better performance of a code with corresponding time complexity, i.e. a
program with less time complexity is more efficient.

5.2 Space Complexity


Space complexity of an algorithm quantifies the amount of time taken by a program to run as a function of
length of the input. It is directly proportional to the largest memory your program acquires at any instance
during run time.
For example: int consumes 4 bytes of memory.
6. Character Arrays
6.1 Introduction
Arrays of characters is known as Character Arrays.

Declaration
To declare a character array of n size, we do char arr[n+1];

Note: We declare an array of n+1 as 0 to n-1 indices store the actual string and nth character stores ‘\0’
(null character).

Fig.6.1 Taking input and Printing output


We can also directly take input if there are no spaces between the characters in
the word
cin >> arr;
In the similar way, we can output the character array
cout << arr;

6.2 Important Questions


1. Check if a given character array is a palindrome or not.
Palindrome: Given a string s, on reversing the string we get the same string we
call that string is a palindrome.
Algorithm:
1) Let the length of the character array be n.
2) Keep a boolean variable ans to store the result and initialize it with true.
3) Iterate over the string and check if ith character is equal to (n-i-1)th, there can be 2 cases
a) If equal, then do nothing
b) If unequal, then put ans = false
4) When the loop ends, if ans is true, then the string is palindrome else it is not a palindrome.
Code:

Fig.6.2 code for Palindrome char array


2. Largest word in a sentence
To input a complete sentence, we use the getline() function.
cin.getline(arr, n)
where arr is the character array and n is the total length of sentence.

Approach:
1. Iterate over the sentence and keep variables currLen and maxLen which store the current length of the
present word being iterated and the overall maximum length word’s length.
2. Whenever we encounter a space during iteration, we will maximize our maxLen variable.
maxLen = max(maxLen, currLen)

Code:

Fig.6.3 Code for largest word in sentence


7. Pointers

Pointers are variables that store the address of other variables.


Syntax

7.1 Getting started with the Pointers


Every variable is stored in the memory and each memory location has its own memory address. It enables
us to pass variables by reference.
‘&’ Operator: It gives the address of the variable.
‘*’ Operator: It gives the value stored at the address, i.e dereferences the value stored at the address.

Fig.7.1 Working Demo

In the above example,


1. We declared an integer variable ‘a’, and an integer pointer ‘aptr’.
2. The address of ‘a’ (&a) is stored in aptr.
3. cout << *aptr; gives the value stored at the memory address.
4. *aptr = 20 changes the value at the memory address to 20. Value of ‘a’ gets changed to 20.

7.2 Array Pointers


In C++, The name of the array is a pointer that points to the first element of the array.

*(arr + i) is equivalent to arr[i].


(arr + i) is the address of the ith element of the array.

Swapping 2 variables using the address


Address of ‘a’ and ‘b’ gets interchanged, thus their values get swapped.
8. Dynamic Memory Allocation

8.1 Stack Memory Allocation


The memory is allocated on the function call stack. The memory gets deallocated as soon as the function
call gets over. Deallocation is handled by the compiler.

8.2 Heap Memory Allocation


Allocation takes place on the pile of memory space available to programmers to allocated and de-allocate.
The programmer has to handle the deallocation.
NOTE: It is different from the heap data structure.

8.3 Delete and New Operator


Delete Operator
To de-allocate a memory p, we pass its address to the delete() function.

New Operator
New operator is used to allocate a block of memory of the given data type.

Dangling Pointer
If the memory location pointed by the pointer gets freed/ deallocated, then the pointer is known as the
Dangling Pointer.
9. STL-Strings

9.1 Introduction
To use strings in a program, you need to include a header called string.
For example: # include<string>

Declaring a string
string str = “rishabh”;
It declares a string of value “rishabh”
string str(10);
It declares a string of size 10.
string s(5, ‘N’);
It declares a string of size 5 with all characters ‘N’.
string abc(str);
It declares a copy of the string str.

Taking Input
We use cin to input the string.
cin >> str;
Using getline() function: To input the string with space we use getline() function instead of cin.

Throwing Output
We use cout to throw output to the terminal.
cout << str;

9.2 Different Functions of string


1. append(): Inserts additional characters at the end of the string (can also be done using ‘+’ or ‘+=’
operator). Its time complexity is O(N) where N is the size of the new string.

2. assign(): Assigns new string by replacing the previous value (can also be done using ‘=’ operator).

3. at(): Returns the character at a particular position (can also be done using ‘[ ]’ operator). Its time
complexity is O(1).

4. begin(): Returns an iterator pointing to the first character. Its time complexity is O(1).

5. clear(): Erases all the contents of the string and assign an empty string (“”) of length zero. Its time
complexity is O(1).

6. compare(): Compares the value of the string with the string passed in the parameter and returns an
integer accordingly. Its time complexity is O(N + M) where N is the size of the first string and M is the size
of the second string.

7. c_str(): Convert the string into C-style string (null terminated string) and returns the pointer to the C-
style string. Its time complexity is O(1).

8. empty(): Returns a boolean value, true if the string is empty and false if the string is not empty. Its time
complexity is O(1).

9. end(): Returns an iterator pointing to a position which is next to the last character. Its time complexity is
O(1).
10.erase(): Deletes a substring of the string. Its time complexity is O(N) where N is the size of the new
string.

11.find(): Searches the string and returns the first occurrence of the parameter in the string. Its time
complexity is O(N) where N is the size of the string.

12.insert(): Inserts additional characters into the string at a particular position. Its time complexity is O(N)
where N is the size of the new string.

13.length(): Returns the length of the string. Its time complexity is O(1).

14.resize(): Resize the string to the new length which can be less than or greater than the current length.
Its time complexity is O(N) where N is the size of the new string.

15.size(): Returns the length of the string. Its time complexity is O(1).

16.substr(): Returns a string which is the copy of the substring. Its time complexity is O(N) where N is the
size of the substring.

17.stoi(): Returns the strings converted to int datatype.

Note:
1. To convert an integer to a string, we use to_string() function.
2. Sorting a string: To sort a string, we need to include a header file known as algorithm in our code.Then
we can use sort() function that is present in above header file on our string. Sort() function takes 2
arguments viz. iterator to start of the string and iterator to end of the string.

You might also like