0% found this document useful (0 votes)
210 views143 pages

24CS101 Unit - I

Uploaded by

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

24CS101 Unit - I

Uploaded by

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

Please read this disclaimer before proceeding:

This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail.
Please notify the sender immediately by e-mail if you have received this document by
mistake and delete this document from your system. If you are not the intended
recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.
24CS101
Programming in C++

Department :CSE, IT
Batch / Year : 2024 – 2028 / I
Created by : Subject Handling Faculties
Date : 20.09.2024
1.CONTENTS
S.NO CONTENTS

1 Contents

2 Course Objectives

3 Prerequisites

4 Syllabus

5 Course Outcomes

6 CO-PO Mapping

7 Lecture Plan

8 Activity Based Learning

9 Lecture Notes

10 Assignments

11 Part- A Questions & Answers

12 Part-B Questions

13 Supportive Online Courses

14 Real Time Applications

15 Content beyond the Syllabus

16 Assessment Schedule

17 Prescribed Text books & Reference Books

18 Mini Project Suggestions


Unit - 1 Content
Chapter No. CONTENTS

1.1 Procedural Languages vs Object Oriented Languages -Types


of computer programming
1.2 Genesis of C++ - Program Life Cycle -Structure of C++
program
1.3 Identifiers - Variables - Keywords

1.4 Number System -Binary Number System -Octal Number


System
1.5 Decimal Number System

1.6 Hexadecimal Number System

1.7 Data types - Constants - Errors

1.8 operators

1.9 Expressions

1.10 Type Conversions

1.11 Control-Flow Statements - Conditional Statements

1.12 Iterative Statements

1.13 Unconditional Control Statements

1.14 Arrays - One- Dimensional Arrays

1.15 Two-Dimensional Arrays -Multi -Dimensional Arrays

1.16 Strings

1.17 String Manipulation Functions

1.18 Array of Strings.


2. Course Objectives
• To learn problem solving and programming fundamentals.
• To gain knowledge on pointers and functions.
• To apply the principles of object orientated programming.
• To understand operator overloading, inheritance and polymorphism.
• To use the functionalities of I/O operations, files build C++ programs
using exceptions.
3. Prerequisites

24CS101 – Programming in C++


 Programming in C
 Logical Thinking
 Basic of Mathematics
4. Syllabus
PROGRAMMING IN C++ L T P C
24CS101
(Common to All Branches) 3 0 3 4.5
OBJECTIVES:
The Course will enable learners to:
 To learn problem solving and programming fundamentals.
 To gain knowledge on pointers and functions.
 To apply the principles of object orientated programming.
 To understand operator overloading, inheritance and polymorphism.
 To use the functionalities of I/O operations, files build C++ programs using
exceptions.
UNIT I PROGRAMMING FUNDAMENTALS 9+9
Procedural Languages vs Object Oriented Languages - Types of computer programming
languages - Genesis of C++ - Program Life Cycle -Structure of C++ program - Identifiers
- Variables - Keywords - Number System -Binary Number System -Octal Number System-
Decimal Number System -Hexadecimal Number System - Data types - Constants - Errors
– Operators- Expressions - Type Conversions - Control-Flow Statements - Conditional
Statements - Iterative Statements - Unconditional Control Statements - Arrays - One-
Dimensional Arrays - Two-Dimensional Arrays - Multi -Dimensional Arrays - Strings -
String Manipulation Functions - Array of Strings.
List of Exercise/Experiments:
1. Write C++ programs for the following:
a. Find the sum of individual digits of a positive integer.
b. Compute the GCD of two numbers.
c. Find the roots of a number (Newton ‘s method)
2. Write C++ programs using arrays:
a. Find the maximum of an array of numbers.
b. Remove duplicates from an array of numbers.
c. Print the numbers in an array after removing even numbers.
3. Write C++ programs using strings:
a. Checking for palindrome.
b. Count the occurrences of each character in a given word.
UNIT II POINTERS AND FUNCTIONS 9+9
Pointers - Pointer Variables - Pointer Operators & Expressions -Pointers with Arrays -
Functions - Scope Rules -Function Arguments -return Statement - Function Variables -
Storage Classes - Types of storage classes - Create Header Files - User-Defined
Functions - Inline Functions - Function Overloading -Recursion - Namespaces.
List of Exercise/Experiments:
1. Generate salary slip of employees using structures and pointers. Create a structure
Employee with the following members:EID, Ename, Designation, DOB, DOJ, Basic
pay
Note that DOB and DOJ should be implemented using structure within structure.
2. Compute internal marks of students for five different subjects using structures and
functions.
UNIT III CLASSES AND OBJECTS 9+9
Concepts of Object Oriented Programming – Benefits of OOP – Simple C++ program -
4. Syllabus Contd...
Classes and Objects - Member functions - Nesting of member functions - Private member
functions - Memory Allocation for Objects - Static Data Members - Static Member functions
- Array of Objects - Objects as function arguments - Returning objects - friend functions –
Const Member functions - Constructors – Destructors.
List of Exercise/Experiments:
1. Write a program Illustrating Class Declarations, Definition, and Accessing Class
Members.
2. Program to illustrate default constructor, parameterized constructor and copy
constructors.
Practice Questions & Scenario Based Questions:

1. Imagine you are working as a software engineer at a tech company. Your team is
developing a mathematical software library that will be used in various applications
across the company. One of the features that your team lead has asked you to
implement is a function that calculates the number of trailing zeros in the factorial of a
number.
The team lead has emphasized the importance of encapsulation in your
implementation.
2. Create a C++ class Calculator representing a simple calculator. The class should have
the following attributes and methods:

Attributes: Two operands and an operation (+, -, *, /)


Methods: Perform the operation and return the result
Implement constructors to initialize the calculator with default values (0,0) and with
specified values. Also, implement a destructor to perform any necessary cleanup.
OPERATOR OVERLOADING, INHERITANCE AND 9+9
UNIT IV
POLYMORPHISM
Operator Overloading - Overloading Using Friend functions – Inheritance – Types of
inheritance – Virtual Base Class - Abstract Class – Constructors in Derived Classes -
member class: nesting of classes.
Pointer to objects – this pointer- Pointer to derived Class - Virtual functions – Pure Virtual
Functions – Polymorphism.

List of Exercise/Experiments:
1. Write a Program to Demonstrate the i) Operator Overloading. ii) Function Overloading.
2. Write a Program to Demonstrate Friend Function and Friend Class.
3. Program to demonstrate inline functions.
4. Program for Overriding of member functions.
5. Write C++ programs that illustrate how the following forms of inheritance are
supported:
a) Single inheritance b) Multiple inheritance c) Multi level inheritance d) Hierarchical
inheritance.
Practice Questions & Scenario Based Questions:
1. Joy is a software developer at a 3D modeling company. The company is developing a
new software tool that will be used by architects and engineers to design and analyze
3D models of various structures. One of the features that her project manager has
asked is to implement a function that calculates the volume of basic 3D shapes like
cylinders and cuboids. The project manager has emphasized the importance of using
function overloading in her implementation..
2. Imagine you are a software developer tasked with creating a utility program for a school
that handles student scores. The school wants a simple program where teachers can
enter the scores of students for a particular test, and the program will then provide the
highest and lowest scores among them. This will help the teachers quickly identify the
top performer and the student who might need extra help.
Your task is to write program that satisfies the above scenario using inline function
3. Develop a software system to manage part-time worker students at a university. These
students have unique attributes such as their name, student ID, hourly wage, and
hours worked per week. Your goal is to create a C++ program that models this system.
3 Ramu is a software developer at a company specializing in developing software
solutions for geometric shapes. Recently, a client approached with a request to
create a program to calculate the areas of rectangles and triangles.

UNIT V I/O, FILES AND EXCEPTIONS 9+9


C++ Streams – Unformatted I/O - Formatted Console I/O – Opening and Closing File –
File modes - File pointers and their manipulations – Templates – Class Templates –
Function Templates - Exception handling.

List of Exercise/Experiments:
1. Program to demonstrate pure virtual function implementation.
2. Count the number of account holders whose balance is less than the minimum balance
using sequential access file.
3. Write a Program to Demonstrate the Catching of all Exceptions.
Practice Questions & Scenario Based Questions:
1. Develop a simple library management system. Create a base class Book representing
a book in the library. The class should have attributes such as title, author, and ISBN
(International Standard Book Number). Implement a virtual function displayDetails() to
display information about the book.
2. A software developer working on a banking application. One of the requirements is to
analyze account holders' balances based on a minimum balance threshold. The
application should read account information from a sequential access file, where each
line represents an account record in the format: account_holder_name, balance.
3. The financial company is developing a new software tool that will be used by financial
analysts to perform various calculations. One of the features of that project is to
implement is a function that performs division of two numbers.
Write a program that takes two integer inputs, numerator and denominator, from the
user. Implement error handling to check if the denominator is zero. If the denominator
is zero, display the message "Division by zero is not allowed!" using an exception. If
the denominator is not zero, calculate the result of the division and display it.
4. Mini project.
TOTAL: 45 (L) + 45 (P) = 90 PERIODS
OUTCOMES:
Upon completion of the course, the students will be able to:
CO1: Solve problems using basic constructs in C++.
CO2: Implement C++ programs using pointers and functions.
CO3: Apply object-oriented concepts and solve real world problems.
CO4: Develop C++ programs using operator overloading and polymorphism.
CO5: Implement C++ programs using Files and exceptions.
CO6: Develop applications using C++ concepts
TEXT BOOKS:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015.
2. E Balagurusamy,” Object Oriented Programming with C++”, 4th Edition, Tata McGraw-
Hill Education, 2008.
REFERENCES:
1. Karl Beecher,” Computational Thinking: A beginner's guide to problem-solving and
programming”, BCS Learning & Development Ltd, 2017. (Unit 1)
2. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th Edition,
Jones and Barklett Publishers, 2010.
3. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
4. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
5. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata McGraw-
Hill Publishing Company Ltd., 2007.
6. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
7. Paul Deitel, Harvey Deitel, “C++ How to Program”, 10th Edition, Pearson Education
Inc. 2017.
8. https://infyspringboard.onwingspan.com/web/en/app/toc/
lex_auth_01297200240671948837_shared/overview
LIST OF EQUIPMENTS:
1. Standalone desktops with C/C++ compiler (or) Server with C/C++ compiler.
5. Course Outcomes

CO1: Solve problems using basic constructs in C++.


CO2: Implement C++ programs using pointers and functions.
CO3: Apply object-oriented concepts and solve real world problems.
CO4: Develop C++ programs using operator overloading and polymorphism.
CO5: Implement C++ programs using Files and exceptions.
CO6: Develop applications using C++ concepts
6. CO – PO Mapping
POs and PSOs

PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
COs 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3

CO1 3 2 1 2 1

CO2 3 2 1 2 1

CO3 3 2 1 2 1

CO4 3 3 3 2 1

CO5 3 2 1 2 1

CO6 3 3 3 1 1 1 2 1
1
7. Lecture Plan - Unit I

S. Topic No. of Proposed Actual Pertaining Taxonomy Mode of


No. Periods Date Lecture CO Level Delivery
Date
1 1 09.09.2024 09.09.2024 CO1 K1 Chalk & Talk
Procedural Languages vs Object
Oriented Languages -Types of
computer programming
2 1 10.09.2024 10.09.2024 CO1 K1 Power point
Genesis of C++ - Program Life
presentation
Cycle -Structure of C++ program
3 1 11.09.2024 11.09.2024 CO1 K1 Chalk & Talk
Identifiers
- Variables - Keywords
4 1 12.09.2024 12.09.2024 CO1 K2 Chalk & Talk
Number System -Binary Number
System -Octal Number System
5 1 13.09.2024 13.09.2024 CO1 K2 Chalk & Talk
Decimal Number System -
Hexadecimal Number System

6 Data types - Constants - Errors 1 14.09.2024 14.09.2024 CO1 K1 Power point


presentation
7&8 Operators- Expressions - Type 1 16.09.2024 16.09.2024 CO1 K2 Chalk & Talk
Conversions

9 Control-Flow Statements - 1 18.09.2024 18.09.2024 CO1 K2 Chalk &


Conditional Statements Talk

10 Iterative Statements 1 19.09.2024 19.09.2024 CO1 K2 Chalk & Talk

11 Unconditional Control Statements 1 20.09.2024 20.09.2024 CO1 K3 Chalk & Talk

12 1 21.09.2024 21.09.2024 CO1 K2 Chalk &


Arrays - One- Dimensional Arrays Talk
13 1 23.09.2024 23.09.2024 CO1 K2 Chalk &
Two-Dimensional Arrays - Multi -
Talk
Dimensional Arrays

14 Strings - String Manipulation 1 24.09.2024 24.09.2024 CO1 K2 Power point


Functions presentation
15 Array of Strings. 1 25.09.2024 25.09.2024 CO1 K2 Chalk & Talk
8. Activity Based Learning
Learning Method Activity

Tutorial Sessions can be conducted


Learn by solving problems Tutorial sessions available in Code
Tantra for practice

Learn by questioning Quiz

Learn by doing hands-on


Practice in Lab
9. Lecture Notes
UNIT I PROGRAMMING FUNDAMENTALS
15
Procedural Languages vs Object Oriented Languages - Types of
computer programming languages - Genesis of C++ - Program Life Cycle -
Structure of C++ program – Identifiers - Variables - Keywords - Number System -
Binary Number System -Octal Number System- Decimal Number System -
Hexadecimal Number System - Data types - Constants - Errors – Operators-
Expressions - Type Conversions - Control-Flow Statements - Conditional
Statements - Iterative Statements - Unconditional Control Statements - Arrays -
One- Dimensional Arrays -Two-Dimensional Arrays - Multi -Dimensional Arrays -
Strings - String Manipulation Functions - Array of Strings.
1.1 Procedural Languages vs Object Oriented Languages

Procedural Programming

Procedural Programming can be defined as a programming model which is


derived from structured programming, based upon the concept of calling
procedure. Procedures, also known as routines, subroutines or functions, simply
consist of a series of computational steps to be carried out. During a program’s
execution, any given procedure might be called at any point, including by other
procedures or itself.

Languages used in Procedural Programming:


FORTRAN, ALGOL, COBOL,
BASIC, Pascal and C.
Object-Oriented Programming

Object-oriented programming can be defined as a programming model which is


based upon the concept of objects. Objects contain data in the form of attributes
and code in the form of methods. In object-oriented programming, computer
programs are designed using the concept of objects that interact with the real
world. Object-oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also
determine their types.

Languages used in Object-Oriented Programming:


Java, C++, C#, Python,
PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.
Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented


programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided In object-oriented programming, the program is


into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-


approach. up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper Object-oriented programming provides data
way of hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept of In object-oriented programming, the concept of


data hiding and inheritance. data hiding and inheritance is used.

In procedural programming, the function is more In object-oriented programming, data is more


important than the data. important than function.

Procedural programming is based on the unreal Object-oriented programming is based on


world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept
procedure abstraction. of data abstraction.

Code reusability present in object-oriented


Code reusability absent in procedural programming,
programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Types of computer programming languages

Programming Language :

A programming language is a computer language that is used by programmers


(developers) to communicate with computers.
It is a set of instructions written in any specific language ( C, C++, Java, Python) to
perform a specific task.
A programming language is mainly used to develop desktop applications, websites,
and mobile applications.
Types of computer programming Languages

1. Low Level Language:-


• They are easy to understand by the computer.
• But difficult for programmers to read, write and understand.
• These are of two types :-
a. Machine Language
b. Assembly Language
a. Machine Language:-
• A Computer can only understand the Machine Language.
• Machine Language are written in series of 0's and 1's only. (also known as Binary
digits)
• It is more difficult to understand and use by the humans.
• The processing speed is very fast. Therefore, most of Games and simulation
programs are written in machine languages.

b. Assembly Language:-
• Assembly Language is a symbolic programming language.
• It uses letter codes instead of binary digits.
• These letter codes are alphabetical abbreviation, known as Mnemonics
• For example- For Addition, the Mnemonics ADD may be used.
• other examples are For Subtraction, the Mnemonics SUB, For Multiply, the
Mnemonics MULT, For Divide, the Mnemonics DIV and so on may be used.

2.High Level Language:-


• These languages are also known as Fourth generation languages.
• They are very similar to human languages.
• Therefore, they are easy to read, write and understand for programmers.

• TYPES:
• Procedural Oriented programming language

• Object-Oriented Programming language


a. Procedural Oriented programming language
• Procedural Oriented Programming (POP) language is derived from structured
programming and based upon the procedure call concept. It divides a program
into small procedures called routines or functions.

• Procedural Oriented programming language is used by a software programmer to


create a program that can be accomplished by using a programming editor like
IDE, Adobe Dreamweaver, or Microsoft Visual Studio.

• The advantage of POP language is that it helps programmers to easily track the
program flow and code can be reused in different parts of the program.

• Example:

• C

• FORTRAN

• Basic

• Pascal, etc.
b. Object-Oriented Programming language

• Object-Oriented Programming (OOP) language is based upon the objects. In

this programming language, programs are divided into small parts called objects.

It is used to implement real-world entities like inheritance, polymorphism,

abstraction, etc in the program to makes the program re-usable, efficient, and

easy-to-use.

• The main advantage of object-oriented programming is that OOP is faster and

easier to execute, maintain, modify, as well as debug.

• Object-Oriented Programming language follows a bottom-up approach.


• Example:
• C++,
• Java
• Python
• C#, etc.
1.2 Genesis of C++

• C++ was developed by Bjarne Stroustrup at Bell Laboratories over a period starting in
1979.
• Since C++ is an attempt to add object-oriented features (plus other improvements)
to C, earlier it was called “C with Objects”.
• As the language developed, Stroustrup named it C++ in 1983.
• It was developed to add a feature of OOP (Object Oriented Programming) in C
without significantly changing the C component.
• Stroustrup was inspired by the Simula programming language, which was one of
the first object-oriented languages. He wanted to create a language that had the
same features as Simula, but that was also as efficient as C.
• C++ was originally developed as an extension to the C language. It added a number
of new features to C, including object-oriented programming, generic programming,
and exception handling.
• C++ quickly became one of the most popular programming languages in the world. It
is used to develop a wide variety of applications, including operating systems, games,
and embedded systems.

Program Life Cycle


• Every C Program that is in text form goes through a series of transformations to obtain
the final executable.
• The various Phases of this transformation are as follows:
• Preprocessing
•Assembling
• Compiling
• Linking
•Loading to main memory
Structure of C++ program
Structure of c++ Program
1. Documentation Section:
• This section comes first and is used to document the logic of the program that the
programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not
compiled by the compiler.
• Documentation Section is optional since the program can execute without them.
2. Linking Section:
The linking section contains two parts:
a. Header Files:
Generally, a program includes various programming elements like built-in functions,
classes, keywords, constants, operators, etc. that are already defined in the
standard C++ library.
In order to use such pre-defined elements in a program, an appropriate header must
be included in the program.
b. Namespaces:
A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
Any user can create separate namespaces of its own and can use them in any other
program.
In the below snippets, namespace std contains declarations for cout, cin, endl, etc.,
statements. using namespace std;
Namespaces can be accessed in multiple ways:
using namespace std;
using std :: cout;
3. Definition Section:
It is used to declare some constants and assign them some value.
In this section, anyone can define your own datatype using primitive data types.
• Eg : #define PI 3.14
• #define AGE 20
4. Global Declaration Section:
• Here, the variables and the class definitions which are going to be used in the
program are declared to make them global.
• The scope of the variable declared in this section lasts until the entire program
terminates.
• These variables are accessible within the user-defined functions also.
5. Function Declaration Section:
• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for this, write
the function prototype in this section for the function which for you are going to
write code after the main function.
6. Main Function:
The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
All the statements that are to be executed are written in the main function.
The compiler executes all the instructions which are written in the curly
braces {} which encloses the body of the main function.
Once all instructions from the main function are executed, control comes out of the
main function and the program terminates and no further execution occur.

1.3 C++ Identifiers


In C++ programming language, identifiers are the unique names assigned to
variables, functions, classes, structs, or other entities within the program. For
example, in the below statement,
int num = 11; #num is an identifier.
Rules to Name of an Identifier in C++
We can use any word as an identifier as long as it follows the following rules:
An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_).
Special characters and spaces are not allowed.
An identifier can only begin with a letter or an underscore only.
C++ has reserved keywords that cannot be used as identifiers since they have
predefined meanings in the language. For example, int cannot be used as an
identifier as it has already some predefined meaning in C++. Attempting to use these
as identifiers will result in a compilation error.
Identifier must be unique in its namespace.
Additionally, C++ is a case-sensitive language so the identifier such
as Num and num are treated as different.

The below images show some valid and invalid C++ identifiers.

C++ Variables

Variables are containers for storing data values.


• In C++, there are different types of variables (defined with different
keywords), for example:
• int - stores integers (whole numbers), without decimals, such as 123 or -
123
• double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• string - stores text, such as "Hello World". String values are surrounded by
double quotes
• bool - stores values with two states: true or false
Syntax :
type variableName = value;
Example:
int myNum = 15;
cout << myNum;

C++ Keywords

• Keywords(also known as reserved words) have special meanings to the C++


compiler and are always written or typed in short(lower) cases.
• Keywords are words that the language uses for a special purpose, such
as void, int, public, etc.
• It can’t be used for a variable name or function name or any other identifiers.
The total count of reserved keywords is 95.
1.4 Number System
• Number systems are the technique to represent numbers in the computer system
architecture, every value that you are saving or getting into/from computer
memory has a defined number system.
Computer architecture supports following number systems.
• Binary number system
• Octal number system
• Decimal number system
• Hexadecimal (hex) number system

TYPES OF NUMBER SYSTEM


Decimal Number system:
Decimal Number system has base 10 as it uses 10 digits from 0 to 9.
• The number system that we use in our day-to-day life is the decimal
number system.
• In decimal number system, the successive positions to the left of the
decimal point represents units, tens, hundreds, thousands and so on.
Each position represents a specific power of the base (10).
• For example, the decimal number 1234 consists of the digit 4 in the
units position, 3 in the tens position, 2 in the hundreds position, and 1
in the thousands position, and its value can be written as,
• (1×1000) + (2×100) + (3×10) + (4×l)
• (1×103) + (2×102) + (3×101) + (4×l00)
• 1000 + 200 + 30 + 1
• 1234

Binary Number system:


Base 2. Digits used in binary number system are 0 and 1
• Uses two digits, 0 and 1. Also called base 2 number system
• Each position in a binary number represents a 0 power of the base 2.
Example: 20
• Last position in a binary number represents an x power of the base (2).
Example: 2x where x represents the last position – 1

Octal Number System:


Base 8. Digits used in octal number system are 0 to 7
• Uses eight digits, 0,1,2,3,4,5,6,7. Also called base 2 number system
• Each position in a Octal number represents a 0 power of the base 8.
Example: 80
• Last position in a Octal number represents an x power of the base (8).
Example: 8x where x represents the last position – 1
Hexadecimal Number System:
Base 16. Digits used in hexadecimal number system are 0 to 9
and
letters from A to F

• Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

• Letters represents numbers starting from 10.


A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

• Also called base 16 number system.

• Each position in a hexadecimal number represents a 0 power of the base


(16). Example 160

• Last position in a hexadecimal number represents an x power of the base


(16). Example 16x where x represents the last position - 1.
Number Systems – Representation
Conversion in Number Systems
1.5 DECIMAL TO OTHER BASE SYSTEM

❖ Step 1 − Divide the decimal number to be converted by the value of the new
base.

❖ Step 2 − Get the remainder from Step 1 as the rightmost digit (least
significant digit) of new base number.

❖ Step 3 − Divide the quotient of the previous divide by the new base.

❖ Step 4 − Record the remainder from Step 3 as the next digit (to the left) of
the new base number.

❖ Repeat Steps 3 and 4, getting remainders from right to left, until the quotient
becomes zero in Step 3.

❖ The last remainder thus obtained will be the Most Significant Digit (MSD) of
the new base number.
Conversion from Decimal To
✔ Binary
✔ Octal
✔ Hexadecimal
✔ 1.Decimal to Binary Conversion
Convert 108.18810 into binary number.

.18810 = .001102

108.18810 = 1101100.001102
10810 = 11011002
✔ 2.Decimal to Octal Conversion

Convert 2477.6410 into octal number.

247710 = 46558 .6410 = .50758 (approx.)

2477.6410 = 4655.50758 (approx.)

✔ 3.Decimal to Hexadecimal Conversion

Convert 2479.56510 into Hexadecimal number.

247910 = 9AF16

.56510 = .90A3D7016

2479.56510 = 9AF.90A3D7016
BINARY TO OTHER BASE SYSTEM

Conversion from Binary To

✔ Decimal
✔ Octal
✔ Hexadecimal

✔ 1.Binary to Decimal Conversion


Convert 11011011.10112 into decimal number.

110110112= 21910 .10112= .687510

11011011.10112= 219.687510
✔ 2.Binary to Octal Conversion
Convert 1010111100.10112 into Octal number.

001 010 100 . 101 100


. 4
111
5
1 2 7 4

1010111100.10112= 1274.548
✔ 3.Binary to Hexadecimal Conversion
Convert 11111011101110010.0111010101011112 into Hexadecimal number.

11111011101110010.0111010101011112 = 1F772.655EH
OCTAL TO OTHER BASE SYSTEM

Conversion from Octal To

✔ Decimal
✔ Binary
✔ Hexadecimal
1.Octal to Decimal Conversion
Convert 1725.438 into decimal number.

1725.438= 981.54687510

165128=
749810
✔ 2.Octal to Binary Conversion
Convert 35.3468 into Binary number.

35.3468= 001101.0111001102
✔ 3.Octal to Hexadecimal Conversion

The following two ways to convert octal to hexadecimal number-

One: First octal to decimal then decimal to hexadecimal

Two: First octal to binary then binary to hexadecimal (Easy method)

Convert (375.246)8 into Hexadecimal number.


1.6 HEXADECIMAL TO OTHER BASE SYSTEM
Conversion from Hexadecimal To
✔ Decimal
✔ Binary
✔ Hexadecimal

✔ 1.Hexadecimal to Decimal Conversion


Convert 54.D216 into decimal number.

54.D216= 84.820312510
✔ 2. Hexadecimal to Binary Conversion
Convert A12C16 into binary number.

A12C16= 10100001001011002
✔ 3. Hexadecimal to Octal Conversion
Convert 1A16 into Octal number.

1A16= 328
Convert A4B.59E16 into Octal number

A4B.59E16= 5113.26368
1.7 Data types in C++

• A data type is the type of data a variable can hold. For example, a Boolean
variable can have boolean data, and an integer variable can hold integer data.

• While coding, we need to use different variables to store different information.

• Variables are just storage locations reserved for storing values. Therefore when
we declare the variable, some space in memory will be reserved.

• You may want to store information for different data types, such as integers,
floats, strings, and Boolean values.

• Memory is allocated based on the variable's data type. The amount of memory
required depends on the data type.

int score = 99;

score here is an int datatype variable. The variable score can only store 2-
byte or 4-byte integers, depending on the compiler/system.

In C++, data types can be classified as follows:


• Primitive / Fundamental Datatypes
• Derived Datatypes
• User-defined Datatypes
Primitive Data types in C++
• Users can use the primitive data types to declare variables, and these are built-in
data types in C++, for instance, float, bool, etc. Primitive data types present in
C++ are defined below:
1. Integer
• The keyword int can represent integer data types. The range of integers is -
2147483648 to 2147483647, and they take up 4 bytes of memory.
For example,
int data = 1526;
data here is an integer data type variable. The variable data requires 2 or 4 bytes of
memory space.
2. Character
• The keyword char represent characters. It is 1 byte in size. Single quotes ' ' are
used to enclose characters in C++.
For example,
char ch = 's';
ch here is a character datatype variable. This means that the variable requires 1 byte
of memory space.

3. Boolean
The boolean data type's keyword is bool. True or false are the two possible values for
the boolean data type. Boolean values are generally used in conditional statements
and loops.
For example,
bool is_true = true;
is_true here is a boolean data type variable. This means that the variable requires 1
byte of memory space.
4. Floating Point
float is the keyword used to hold floating-point numbers (decimals and exponentials).
The float variable has a size of 4 bytes.
For example,
float val = 15.26;
val here is a floating-point datatype variable. This means that the variable requires 4
bytes of memory space.
5. Double Floating Point
• double is the keyword used to hold floating-point numbers (decimals and
exponentials) with double precision. The double variable has a size of 8
bytes.
For example,
double val = 2019.1526;
val here is a double floating-point datatype variable. This means that the
variable requires 8 bytes of memory space.
6. Void or Valueless
• The term void refers to something that has no worth. The void data type
represents a valueless entity. Variables of the void type cannot be declared.
It is only used for functions, not returning any data.
7. Wide Character
• The wide-character wchar_t data type is similar to the char data type, but
its size is 2 or 4 bytes rather than 1 byte. It's used to represent characters
that take up more memory than a single char to represent.
For example,
wchar_t w = L'C';
w here is a wide-character datatype variable that has a value of
67 (L'C') and has a size of 4 bytes. This means that the variable requires 2
bytes or 4 bytes of memory space.
Derived Data types in C++
• Derived Data Types are data types that are created by combining primitive or
built-in datatypes. There are four different types of derived data types. These are :
1. Function
• A function is a code segment or a block of code defined to accomplish a specific
purpose.
• A function is often designed to spare the user from repeatedly writing the same
lines of code for the same input.
• All the lines of code are combined into a single function that may be invoked from
anywhere. Every C++ application includes a default function called main().
• The function also has a return type, which is used to specify the type of data
the function would return when its execution is complete.
• The function's return type could be any data type, including the void, which
states that there is no need to return anything once the execution of that
function is complete.
Syntax:
function_return_type function_name(parameters) { }

Example:
int sum(int num1, int num2) { return (num1 + num2); }
Here, the return type of the sum function is an integer, and the function is
used to calculate the sum of 2 numbers.
2. Array
• An array is a set of elements that are kept in memory in a continuous manner
and also have the same type of data present within the array. The purpose of
an array is to store a lot of data in a single variable name and sequential
order.
Syntax:
datatype array_name[size_of_array];
Example:
int arr[4]={0,1,2,3};
Here, we have defined an integer array of size 4, which can continuously
store four integer variables in memory.

3. Pointer
• Pointers are symbolic representations of addresses.
• Pointers store the addresses of the variables having the same datatype as
that of the pointer.
• The size of the pointer is either 4 bytes or 8 bytes, no matter what the data
type is.
• They enable programs to create and change dynamic data structures, as well
as to imitate call-by-reference.
• In C++, its generic declaration looks like this:
Syntax:
data_type* variable_name;
Example:
int* point_int;
point_int holds the address of a variable of an integer datatype.

4. Reference
When we declare a variable as a reference, it becomes an alternate name
for an existing variable. By adding '&' to a variable's declaration, it can be
declared as a reference.
Example:
int val = 1526; int &ref = val;
Here ref becomes the reference to integer val, and now any
changes in one would be automatically reflected in the other as they both
represent the same memory location.

User defined Data Types :


• 1. Class
• A Class is the building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its
own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for
an object.
2. Structure
A Structure is a user-defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Syntax
struct structurename
{
char varname[size];
int varname;
};
3. Union
Like Structures , Union a user-defined data type. In union, all members share the
same memory location. For example in the following C program, both x and y share
the same location. If we change x, we can see the changes being reflected in y.
Union_Name
{
// Declaration of data members
}; union_variables;

4. Enumeration
Enumeration (or enum) is a user-defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and
maintain.
Syntax
enum nameOfEnum
{
varName1 = 1, varName2 = 0
};
Eg:
enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };
int main()
{
enum week day;
day = Wed;
cout << day;
return 0;
}

Output: 2
5. Typedef

C++ allows you to define explicitly new data type names by using the
keyword typedef. Using typedef does not create a new data class, rather it
defines a name for an existing type. This can increase the portability(the ability
of a program to be used across different types of machines.
Syntax
typedef typeName;

Constants in C++
The const keyword (which stands for constant) is used to specify that the value
of a variable cannot be changed anywhere in the program, either intentionally or
accidentally. For example,
const double PI = 3.14; // makes PI a constant
Note: The standard naming convention for constants is that they must all be in
uppercase letters. For example,

const int MAGIC_NUMBER = 42;


Errors in C++
• Error is an illegal operation performed by the user which results in abnormal
working of the program.
• Programming errors often remain undetected until the program is compiled or
executed. Some of the errors inhibit the program from getting compiled or
executed. Thus errors should be removed before compiling and executing.
• The most common errors can be broadly classified as follows.
1.Syntax errors:
Errors that occur when you violate the rules of writing C++ syntax are
known as syntax errors.
This compiler error indicates something that must be fixed before the code can
be compiled.
All these errors are detected by compiler and thus are known as compile-time
errors.
Most frequent syntax errors are:
1. Missing Parenthesis (})
2. Printing the value of variable without declaring it
3. Missing semicolon like this:
// C++ program to illustrate
// syntax error

#include <iostream>
using namespace std;

void main()
{
int x = 10;
int y = 15;

cout << " "<< (x, y) // semicolon missed


}

error: expected ';' before '}' token


2. Run-time Errors :
• Errors which occur during program execution(run-time) after successful compilation
are called run-time errors.
• One of the most common run-time error is division by zero also known as Division
error.
• These types of error are hard to find as the compiler doesn’t point to the line at
Which the error occurs.
// C++ program to illustrate run-time error
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
cout << "result = "<< div;
}
warning: division by zero [-Wdiv-by-zero] div = n/0;
In the given example, there is Division by zero error. This is an example of run-
time error i.e errors occurring while running the program.
3. Linker Errors:
• These error occurs when after compilation we link the different object files with
main’s object using Ctrl+F9 key(RUN).
• These are errors generated when the executable of the program cannot be
generated.
• This may be due to wrong function prototyping, incorrect header files.
• One of the most common linker error is writing Main() instead of main().

// C++ program to illustrate // linker error

#include <bits/stdc++.h>
using namespace std;

void Main() // Here Main() should be main()


{
int a = 10;
cout << " "<< a;
}

(.text+0x20): undefined reference to `main'


4. Logical Errors
• On compilation and execution of a program, desired output is not obtained when
certain input values are given.
• These types of errors which provide incorrect output but appears to be error free
are called logical errors.
• These are one of the most common errors done by beginners of programming.
• These errors solely depend on the logical thinking of the programmer and are
easy to detect if we follow the line of execution and determine why the program
takes that path of execution.

// C++ program to illustrate // logical error

int main()
{
int i = 0;

// logical error : a semicolon after for loop


for(i = 0; i < 3; i++);
{
cout << "loop ";
continue;
}
return 0;
}

No output
5. Semantic errors
This error occurs when the statements written in the program are not meaningful to
the compiler.

C++ program to illustrate // semantic error

int main()
{
int a, b, c;
a + b = c; //semantic error
}

error: lvalue required as left operand of assignment a + b = c; //semantic error


1.8 OPERATORS

Types of Operators in C++

1) Arithmetic Operators

• These operators are used to perform arithmetic or mathematical operations on


the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is
used for multiplication, etc.

• Arithmetic Operators can be classified into 2 Types:

• Unary Operator

• Binary Operator
a) Unary Operator
• Unary arithmetic operator in C++ is used only with one operand to perform the
arithmetic operations.
• The increment operators are used to increment the value of a variable by 1, and
decrement operators are used to decrement the value of a variable by 1.
• Pre-increment or pre-decrement operators first manipulate the value and then
get assigned to the variables, whereas post-increment or post-decrement
operators first get assigned to the variable, and then the value gets
manipulated.

a)Unary Operators
#include <iostream>
using namespace std;
int main()
{
int x;
int a = 5;
x = a++; // post increment
cout << "value of x is " << x << ", value of a is " << a << endl;
x = ++a; // pre increment
cout << "value of x is " << x << ", value of a is " << a << endl;
x = a--; // post decrement
cout << "value of x is " << x << ", value of a is " << a << endl;
x = --a; // pre decrement
cout << "value of x is " << x << ", value of a is " << a << endl;
return 0;
}
Output:
value of x is 5, value of a is 6
value of x is 7, value of a is 7
value of x is 7, value of a is 6
value of x is 5, value of a is 5
b) Binary Operator
The binary arithmetic operators are the ones that are used with 2 operands
to perform the arithmetic operations.
Example Program :
#include <iostream>
using namespace std;
int main()
{ OUTPUT:
int a = 8, b = 3;
// Addition operator a + b = 11
cout << "a + b = " << (a + b) << endl; a-b=5
// Subtraction operator a * b = 24
cout << "a - b = " << (a - b) << endl; a/b=2
// Multiplication operator a%b=2
cout << "a * b = " << (a * b) << endl;
// Division operator
cout << "a / b = " << (a / b) << endl;
// Modulo operator
cout << "a % b = " << (a % b) << endl;
return 0;
}

2. Relational operators
Relational operators are mainly used to check for specific conditions. These are always
binary operators because 2 operands are needed to evaluate the condition. If the
condition is true, it will return 1, else if the condition is false, it will return 0.
Example Program :
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;
cout << "a == b is " << (a == b) << endl; // Equal to operator
cout << "a > b is " << (a > b) << endl; // Greater than operator
cout << "a >= b is " << (a >= b) << endl; // Greater than or Equal to operator
cout << "a < b is " << (a < b) << endl; // Lesser than operator
cout << "a <= b is " << (a <= b) << endl; // Lesser than or Equal to operator
cout << "a != b is " << (a != b) << endl; // true
return 0;
}

Output:

a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1

Here, 0 denotes false and 1 denotes true


3. Logical operators
• Logical operators are used to check logical conditions.
• They return the 1 when the result is true and 0 when the result is false.
• There are three logical operators in C++:
1. And operator
2. Or operator
3. Not operator
Example Program :
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;
// Logical AND operator
cout << "a && b is " << (a && b) << endl;
// Logical OR operator
cout << "a || b is " << (a || b) << endl;
// Logical NOT operator
cout << "!b is " << (!b) << endl;
return 0;
}

Output:

a && b is 1
a ! b is 1
!b is 0
4. Bitwise operators
• Bitwise operators are fundamental to systems programming, enabling
manipulation of data at the bit level, which can lead to more efficient code.
These operators are used to perform operations on binary representations of
numbers, where the operations are carried out bit by bit.

Bitwise AND:
• Suppose if there are two bits, bit 1 and bit 2, Two-Bits are there then:
1. If bit 1 and bit 2 both are 0 then bit 1 & bit 2 will also be 0.
2. If bit 1 is 1 and bit 2 is 0 then bit 1 & bit 2 will be 0.
3. If bit 1 is 0 and bit 2 is 1 then bit 1 & bit 2 will be 0.
4. If bit 1 and bit 2 both are 1 then only bit 1 & bit 2 will be 1.
Bitwise OR:

• Here we can see in the table that Bit 1 | Bit 2 will be 1 if any one of the bits is
1. And Bit 1 | Bit 2 will be 0 if both the bits are 0.

Bitwise XOR [ Exclusive OR]

• Then, if both the bits are different then only Bit 1 ^ Bit 2 will be 1. If Bit
1 and Bit 2 are the same then Bit 1 ^ Bit 2 will be 0.
• The other bit must be 0 or if one bit is 0 then the other bit must be 1
then only Bit 1 ^ Bit 2 will be 1.

Bitwise NOT
• NOT is a unary operation that means an operation with only one operand.
In this operation,
• Here you can see that the NOT inverts the bits of its operant. If the bit is
1 then NOT will be 0 and if the bit is 0 then NOT will be 1.

Bitwise Left Shift and Right Shift


int x = 5, y;
y = x << 1;
We want to store the result of the left shift of x by 1 in the y variable. We
know the value of x is 5, then in binary will be:

In the Left shift, we have to shift all the bits to the left-hand side by the value
given by the user. In this case, we will shift all the bits by one to the left-hand
side as:

We will perform x >> 1 as:

• If we write x >> i (i is some number here) then x will be divided by 2i. Now
it will be 2 in decimal form. Let’s see these all operations in code.
• Note: Binary left shift shifts the bits to the left side as the number of times you
specified. Mainly it will do multiplication.
• Binary Right Shift shifts the bits to the Right side as the number of times you
specified. Mainly it will do division.

• Example Program :
• #include<iostream>
using namespace std;
int main ()
{
int a = 10, b = 13;
cout << "Bitwise AND: \t" << (a & b) << endl;
cout << "Bitwise OR: \t" << (a | b) << endl;
cout << "Bitwise X-OR: \t" << (a ^ b) << endl;
cout << "Bitwise NOt A: \t" << ~a << endl;
cout << "Bitwise Not B: \t" << ~b << endl;
a = a << 2;
cout << "Bitwise leftshift of a:\t" << a << endl;
b = b >> 2;
cout << "Bitwise Rightshift of b:\t" << b << endl;
return 0;
}
OUTPUT :
Assignment Operators
• These operators are used to assign value to a variable. For example: num = 6
will assign the value 6 to the variable num.
• The left side operand of the assignment operator is a variable and the right
side operand of the assignment operator is a value.
• The value on the right side must be of the same data type as the variable on
the left side otherwise the compiler will raise an error.
Ternary operator or Conditional operator :

• The ternary operator in c++, often denoted as "? :", is a concise way to express
conditional logic in many programming languages. It takes three operands:
(condition) ? Expression1 or value1: Expression2 or value2
Here's how it works:
• The condition (condition) is verified first.
• If the condition is true, the value of Expression1 is returned.
• If the condition is false, the value of Expression2 is returned.

Example Program :

#include<iostream>
using namespace std;
int main()
{
int num=10;
string result;
result=(num>5)? “Greater than 5” :” less than or equal to 5 “;
cout<<result;
Output:Greater than 5
return 0;

1.9 Expression in C++

• An expression is a combination of operators, constants and variables. An


expression may consist of one or more operands, and zero or more operators to
produce a value.
Example:
• a+b
• c
• s-1/7*f
1. Constant expressions: Constant Expressions consists of only constant
values. A constant value is one that doesn’t change.
Examples:
• 5, 10 + 5 / 6.0, ‘x’

2. Integral expressions: Integral Expressions are those which produce integer


results after implementing all the automatic and explicit type conversions.
Examples:
• x, x * y, x + int( 5.0)
• where x and y are integer variables.
3. Floating expressions: Float Expressions are which produce floating point
results after implementing all the automatic and explicit type conversions.
Examples:
• x + y, 10.75
• where x and y are floating point variables.
4. Relational expressions: Relational Expressions yield results of type bool which
takes a value true or false. When arithmetic expressions are used on either side of
a relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
• x <= y, x + y > 2
5. Logical expressions: Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples:
• x > y && x == 10, x == 10 || y == 5
6. Pointer expressions: Pointer Expressions produce address values.
Examples:
• &x, ptr, ptr++
• where x is a variable and ptr is a pointer.
7.Bitwise expressions:
Bitwise Expressions are used to manipulate data at bit level. They are basically used
for testing or shifting bits.
Examples:
• x << 3
• shifts three bit position to left
• y >> 1
• shifts one bit position to right.
• Shift operators are often used for multiplication and division by powers of two.
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
 An expression is a combination of constants, variables and operators.
 Consider the expression, a + b * c, has higher precedence.
 Hence (b*c) will be evaluated first. This result will then be added to a.
 In order to override the precedence, parentheses can be used.
 Associativity refers to the order in which the operators with the same
precedence are evaluated in expression.

 It is also called as grouping.


 The operators in an expression are evaluated either from left-to-right or
right-to-left.
 In case of nested parentheses, the innermost parentheses are evaluated
first.
Example: x = 9/2 + a-b;
Precedence of Operators
1.10 Type Conversions

A type cast is basically a conversion from one type to another. There are two
types of type conversion:

1. Implicit Type Conversion


2. Explicit Type Conversion

1. Implicit Type Conversion


Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to avoid
lose of data.
All the data types of the variables are upgraded to the data type of the variable
with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
Program :
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float OUTPUT:
float z = x + 1.0;
x = 107
cout << "x = " << x << endl y=a
<< "y = " << y << endl z = 108

<< "z = " << z << endl;


return 0;
}
Explicit Type Conversion:

• This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type.
• Converting by assignment: This is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful
casting.
• Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example Program :
#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1; OUTPUT:

Sum = 2
cout << "Sum = " << sum;

return 0;
}
1.11Control-Flow Statements - Conditional Statements

Conditional statements in programming are used to control the flow of a program based
on certain conditions.
These statements allow the execution of different code blocks depending on whether a
specified condition evaluates to true or false, providing a fundamental mechanism
for decision-making in algorithms.
If Statements
Simple if conditional
statements
The if statement is the most basic form of conditional statement. It checks if a condition is
true. If it is, the program executes a block of code.
Syntax of If Conditional Statement:
if (condition)
{
// code to execute if condition is true
}

if condition is true, the if code block executes. If false, the execution moves to the next
block to check.
Example Program :

#include <iostream>
using namespace std;
int main()
{
int x = 10;
if (x > 0) OUTPUT:
{
cout<<"x is positive"; x is positive
}
return 0;
}
if .. else statement

If the test condition is evaluated to true, statements inside the body of if are
executed.
If the test condition is evaluated to false, statements inside the body of else
are executed.

Syntax of If-else conditional statement

if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}
Example program for if-else statement
#include <iostream>
using namespace std;
int main()
{
int x = -10;
if (x > 0)
{
cout << "x is positive";
}
else
{
cout << "x is not positive";
}
return 0;
}
Nested if.. else
One if ..else statement is available , either in if block or else block , is termed as
Nested if-else statement.

Syntax
if(condition1)
{
// Code to be executed
if(condition2)
{
// Code to be executed
}
else
{
// Code to be executed
}
}
else
{
// code to be executed
}
//program for nested ..if else
#include <iostream>
using namespace std;
int main()
{
int x = 0;
if (x > 0)
{
cout << "x is positive"; OUTPUT:
} x is zero
else if (x < 0)
{
cout << "x is not positive";
}
else {
cout << "x is zero";
}
return 0;
}

else if ladder:
When a series of many conditions have to be checked use the else if ladder
statement, which takes the following general form.

if (condition1)
statement1;

else if (condition2)
statement2;

else if (condition3)
statement3;

else if (condition-n)
statement n;

else
default statement;
Example:
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter Day Number: ";
cin >> day;
cout << "Day is ";
if (day == 1)
cout << "Sunday" << endl;
else if (day == 2)
cout << "Monday" << endl;
else if (day == 3)
cout << "Tuesday" << endl;
else if (day == 4)
cout << "Wednesday" << endl;
else if (day == 5)
cout << "Thursday" << endl;
else if (day == 6)
cout << "Friday" << endl;
else
cout << "Saturday" << endl;
return 0;
}

Output:
Enter Day Number : 5
Thursday
Switch Statement
⮚ It is a multi-way branch statement.
⮚ It requires only one argument of any data type, which is checked with number
of case option.
⮚ switch() statement evaluates expression and then for values among the case
constants.
⮚ If the value matches with case constant, the particular case statement is
executed, if not default is executed.
⮚ switch, case and default are reserved keywords.
⮚ Every case statement terminates with ':'.
⮚ The break statement is used to exit from the current case structure.
Syntax:
switch (expression or value)
{
case value-1:
block-1;
break;
case value-2;
block-2;
break;
.
.
.
default:
default-block;
}
⮚ The expression is an integer expression or character.
⮚ value-1, value-2 is constants or constant expressions and is known as case
labels.
⮚ These values should be unique within a switch statement.
⮚ block-1, block-2… are statement lists.
When the switch is executed, the value of the expression is successively compared
against the values value-1, value-2…
If a case is found, whose value matches with the value of the expression, and then
the block of statements that follows the case is executed.
The break statement, transfers the control to the statement-x following the switch.
Default is an optional case.
example of a switch case statement

#include <iostream>;
using namespace std;
int main()
{
int x = 2;
switch (x) { OUTPUT:
case 1:
cout << "x is one";
x is two
break;
case 2:
cout << "x is two";
break;
default:
cout << "x is neither one nor two";
}
return 0;
}
1.12 Iterative Statements / Looping statements :

In Programming, sometimes there is a need to perform some operation more than


once or (say) n number of times. Loops come into use when we need to repeatedly
execute a block of statements.

There are mainly two types of loops:


1. Entry Controlled loops: In this type of loop, the test condition is tested before
entering the loop body. For Loop and While Loop is entry-controlled loops.
2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated
at the end of the loop body. Therefore, the loop body will execute at least once,
irrespective of whether the test condition is true or false. the do-while loop is exit
controlled loop.

For Loop
• A For loop is a repetition control structure that allows us to write a loop that is
executed a specific number of times. The loop enables us to perform n number
of steps together in one line.
Syntax:

for (initialization expr; test expr; update expr)


{
// body of the loop
// statements we want to execute
}
// C++ program to Demonstrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << "Hello World”<<endl;
}

return 0;
}
Output

Hello World
Hello World
Hello World
Hello World
Hello World

While loop
• While loop is a type of the entry controlled loop which initially checks the
condition and if the condition is true, then execute the loop body. It is basically
used when the count of iterations is not fixed.
Syntax

The C++ language provides the following syntax for the while loop:

while (test expression)


{

// piece of code or loop body

update expression;
}
• The various parts of the While loop are:
1. Test Expression: In this expression, we have to test the condition. If the
condition evaluates to true then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the while loop.
2. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.
3.Body: This is a group of statements that include variables, functions, and so on.
With the while loop, code, and simple names can be printed, complex algorithms
can be executed, or functional operations can be performed.

// Basic C++ program to demonstrate while loop


#include <iostream>
using namespace std;
int main()
{
// initializing the loop variable
Output
int s = 1;
Programming in C++
// test expression
Programming in C++
while (s <= 4) Programming in C++
{ Programming in C++

cout << “Programming in C++“<<endl;


// update expression
s++;
}
return 0;
}
do While Loop
• The do while loop is an exit control statement used to iterate a block of code for a
specified number of times according to the given condition.
• The condition is checked before the block of code gets executed in while and for
loops, whereas in do-while loops, it first executes the block of code and then
checks the condition at the end of the loop.
• In simple words, while and for loop are controlled at the entry of the loop(also
called entry-controlled loops), whereas the do-while loop is controlled at the end
of the loop(also called an end-controlled loop).
• Hence, even if the condition returns false in the very beginning itself still, the loop
will be executed once.
• do while loop executes the block of code at least a single time without even
checking the condition.
Syntax
• The syntax for do-while loop in C++:
do
{
// code to be executed(body);
update_expression;
}
while (test_expression);

• According to the syntax, the body will be executed first at least once without
checking whether it is true or false.
#include <iostream>
using namespace std;
int main() {
int num = 1; // Initializing variable num.
do {
// Body of the loop. Output:
cout << "Scaler Topics" << endl;
Scaler Topics
num++; // Update_expression. Scaler Topics
}
while (num < 3); // test_expression.
return 0;
}
1.13 Unconditional control statements
Unconditional control statements in C++ are used to transfer control from one
part of the program to another without any conditions.
Here are the main types:
1. goto Statement: This statement directs the program control to a labeled
statement within the same function. It's generally advised to avoid using `goto` as
it can make the code harder to read and maintain.
goto label;
// some code
label:
// code to execute
#include <iostream>
using namespace std;
int main() {
int num = 0; // Initializing num variable.
start: // Defining the label.
cout << num << endl;
num++; // Incrementing num variable.
// Checking condition.
if (num < 10) {
// If true, execute the goto statement, and move to label "start".
goto start;
}
cout << "End Reached"; // Finally printing
return 0;
}

Output:

0
1
2
3
4
5
6
7
8
9
End Reached

2. break Statement: This statement is used to exit from a loop or switch


statement prematurely.

for (int i = 0; i < 10; i++)


{
if (i == 5)
{
break; // exit the loop when i is 5
}
cout << i << endl;
}
#include <iostream>
using namespace std;
int main()
{
// Loop statement start.
for (int i = 0; i < 10; i++)
{
// If the condition is met.
if (i == 5) {
// When a break statement is encountered, the program will exit the loop.
break;
}
cout << i << endl; // Printing the i's value.
}
return 0;
}

Output:

0
1
2
3
4

3. continue Statement: When encountered, it just skips that particular iteration,


which means we are telling the compiler that as soon as you see the continue
statement, forget everything written below it for that iteration, and start with the
next iteration.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue; // skip the rest of the loop when i is 5
}
cout << i << endl;
}
#include <iostream>
using namespace std;
int main() {
// Loop statement start.
for (int i = 0; i < 10; i++) {
// If the condition is met.
if (i == 5) {
// When continue statement will be encountered,
// the program will skip that iteration.
continue;
}
cout << i << endl; // Printing the i's value.
}

return 0;
}

Output :

0
1
2
3
4
6
7
8
9
1.14 Arrays
Arrays – Introduction, Declaration, Initialization, Input, Output
Introduction
An array is a group (or collection) of same data types. For example an int array holds the
elements of int types while a float array holds the elements of float types.
Consider a scenario where you need to find out the average of 100 integer numbers
entered by user. There are two ways to do this:
1)Define 100 variables with int data type and then perform 100 scanf() operations to
store the entered values in the variables and then at last calculate the average of them.

2) Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
Which solution is better? Obviously the second solution, it is convenient to store same
data types in one single variable and later access them using array index.

1.16 Single Dimensional Array :


datatype arrayname[size];
Arrays should also be declared before they are used in the program. The general syntax
for declaring array is:
int a[5]; //under the name a - 5 integers

26 89 15 39 57

a[0] a[1] a[2] a[3] a[4]


Array subscript (or index) is used to access any element stored in array. Subscript starts
with 0, which means a[0] represents the first element in the array a.
In general a[n-1] can be used to access nth element of an array. where n is any integer
number.

If the number of values provided is less than the number of Elements in the array, the
un-assigned elements are filled with zeros.
Types of array :
• 1. one dimensional array
Syntax : datatype arraymane[size]; eg: int a[10];
• 2.Two dimensional array - to store the matrix inputs.(table of values having rows and
columns)

syntax :
datatype arrayname[size1][size2];
int a[2][3]; - 6 nos - 2 rows & 3 columns
• 3.Multi dimensional array :
datatype arrayname[size1][size2].....[sizen];
Input data into the Single dimensional array
Here we are iterating the array from 0 to 3 because the size of the array is 4.
Inside the loop we are displaying a message to the user to enter the values. All the
input values are stored in the corresponding array elements using scanf function.
for (i=0; i<4;i++)
{
cin>>num[i];
}
Printing data from Single dimensional array
Suppose, if we want to display the elements of the array then we can use the for
loop like this.
for (i=0; i<4;i++)
{
cout<<num[i];
}
Single Dimensional Array:
Example Program:
#include<stdio.h>
void main ( )
{
int a[5],i;
cout<<“enter 5 elements”; for
( i=0; i<5; i++)
cin>>a[i];
cout<<"elements of the array are";
for (i=0; i<5; i++)

cout<<a[i];
}
Output
The output is as follows −
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Various ways to initialize a single dimensional array
In the above example, we have just declared the array and later we
initialized it with the values input by user. However you can also initialize the array
during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


int arr[] = {1, 2, 3, 4, 5};
Un-initialized array always contain garbage values.
C Array – Memory representation
Array Index: a[0] a[1] a[2] a[3] a[4]
Array Elements: 10 20 30 40 50
Memory Location: 1000 1002 1004 1006 1008
All the array elements occupy contiguous space in memory. There is a
difference of 2 among the addresses of subsequent neighbours, this is because this
array is of integer type and an integer holds 2 bytes of memory.

1.15 Two Dimensional Arrays (2D Arrays)

2D array – We can have multidimensional arrays like 2D and 3D array. However the
most popular and frequently used array is 2D – two dimensional array. We will see
how to declare, read and write data in 2D array along with various other features of
it.
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};

int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, the first method is more readable,
because you can visualize the rows and columns of 2d array in this method.
We know that, when we initialize a normal array (one dimensional array) during
declaration, we need not to specify the size of it. However that’s not the case with 2D
array, you must always specify the second dimension even if you are specifying
elements during the declaration.
Example:

/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }

/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }

/* Invalid declaration – you must specify second dimension*/ int abc[][] = {1, 2, 3
,4 }

/* Invalid declaration – you must specify second dimension*/ int abc[2][] = {1, 2,
3 ,4 }

Two dimensional (2D) Array Example


This program demonstrates how to store the elements entered by user in a 2D array and
how to display the elements of a two dimensional array.
#include<stdio.h>
int main()
{
int disp[2][3]; int i, j;
cout<<“Enter the Array elements”;
for(i=0; i<2; i++)

{
for(j=0;j<3;j++)
{
cin>>disp[i][j];

}
}
cout<<"Two Dimensional array elements:\n";

for(i=0; i<2; i++)


{
for(j=0;j<3;j++)
{
cout<< disp[i][j];
if(j==2)
{
cout<<endl;
}
}
}
return 0;
}
Output:
Enter the Array Elements :
123456
Two Dimensional array elements:

1 23
4 56

Number of elements in a 2D Array


We can calculate how many elements a two dimensional array can have by using
this formula:
The array arr[n1][n2] can have n1*n2 elements.
The array that we have in the example below is having the dimensions 5 and 4.
These dimensions are known as subscripts. So this array has first subscript value as
5 and second subscript value as 4. So the array abc[5][4] can have 5*4 = 20
elements.
• Matrix Operations (Addition, Subtraction)
Matrix addition in C language to add two matrices, i.e., compute their sum and
print it. A user inputs their orders (number of rows and columns) and the matrices.
For example, if the order is 2, 2, i.e., two rows and two columns and The matrices
are:
First matrix:
1 2
3 4
Second matrix: The output is: 4 5
-1 5 2 9
5 7
Matrix Addition Program:
#include <iostream>
using namespace std;
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
cin>>m>>n;
cout<<"Enter the elements of first matrix\n";
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
cin>>first[c][d];
cout<<"Enter the elements of second matrix\n";
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
cin>>second[c][d];
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
}
}
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
cout<<sum[c][d]<<"\t";
} cout<<endl;
}
return 0; }
Output :
Enter the number of rows and columns of a matrix : 2 2
Enter the elements of first matrix :1 2 3 4
Enter the elements of second matrix : 5 6 7 8
Sum of entered matrices : 6 8 10 12

Program for Matrix Multiplication :


#include <iostream>
using namespace std;
int main()
{
int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
// If column of first matrix in not equal to row of second matrix,
if (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.matrix"<<endl;
cout<<"Matrix Multiplication cannot be done"<<endl;
exit(0);
}
// Storing elements of first matrix.
cout << endl << "Enter elements of matrix 1:" << endl;
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c1; ++j)
{
cin >> a[i][j];
}
}
// Storing elements of second matrix.
cout << endl << "Enter elements of matrix 2:" << endl;
for(i = 0; i < r2; ++i)
for(j = 0; j < c2; ++j)
{

cin >> b[i][j];


}
// Initializing elements of matrix mult to 0.
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
mult[i][j]=0;
}
// Multiplying matrix a and b and storing in array mult.
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
for(k = 0; k < c1; ++k)
{
mult[i][j] += a[i][k] * b[k][j];
}
// Displaying the multiplication of two matrix.
cout << endl << "Output Matrix: " << endl;
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c2; ++j)
{
cout << " " << mult[i][j];
}
cout<<endl;
}
return 0;
}
Output:
Enter rows and columns for first matrix: 2 2
Enter rows and columns for second matrix: 2 2

Enter elements of matrix 1:


1234

Enter elements of matrix 2:


1111

Output Matrix:
33
77

Program for sorting of an array ( Using ID Array)

#include <iostream>
using namespace std;
int main(){
int i, j, size, temp;
int arr[25];
cout << "Enter the total no. of elements: ";
cin >> size;

// Enter the elements for an array


cout << "Enter the elements of the array: " << endl;
for (i = 0; i < size; i++){
cin >> arr[i];
}
// Sorting elements in ascending order
for (i = 0; i < size; i++){
for (j = i; j < size; j++){
if (arr[i] > arr[j+1]){
temp = arr[i];
arr[i] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Displaying output
cout << "Elements sorted in the ascending order are: " << endl;
for (i = 1; i <= size; i++){
cout << arr[i] << endl;
}
return 0;
}

Output:
Enter the total no. of elements: 5
Enter the elements of the array:
52714
Elements sorted in the ascending order are:
1
2
4
5
7
1.16 String
A string is a one-dimensional array of characters terminated by
a NULL ('\0') character. It can be read as a single entity, unlike other types of
arrays.

Strings in C++
A string is a collection of characters. There are two types of strings commonly
used in C++ :
 Strings that are objects of string class (The Standard C++ Library String
Class)
 C-strings (C-style Strings)

Ways to Define a String in C++

Strings can be defined in several ways in C++. Strings in C++ can be defined
either using the std::string class or the C-style character arrays.

A string in C++ can be represented :

 Using String keyword

 Using C-style strings

Differences between string and character Array

String Character Array

Strings define objects that can be The null character terminates a character
represented as string streams. array of characters.

A string class provides numerous functions Character arrays offers few inbuilt
for manipulating strings. functions to manipulate strings.

The size of the character array has to be


Memory is allocated dynamically.
allocated statically.
C Style Strings

These strings are stored as the plain old array of characters terminated by a null
character ‘\0’. They are the type of strings that C++ inherited from C language.

Syntax:

char str[] = "GeeksforGeeks";

// C++ Program to demonstrate strings


#include <iostream>
using namespace std;
int main()
{
char s[] = "GeeksforGeeks";
cout << s << endl;
return 0;
}

Output:
GeeksforGeeks
Using C-style strings

Using C-style string libraries functions such as strcpy(), strcmp(), and strcat() to
define strings. This method is more complex and not as widely used as the other
two, but it can be useful when dealing with legacy code or when you need
performance.

char s[] = {'g', 'f', 'g', '\0'};


char s[4] = {'g', 'f', 'g', '\0'};
char s[4] = "gfg";
char s[] = "gfg";
/ C++ Program to demonstrate C-style string declaration
#include <iostream>
using namespace std;
int main()
{
char s1[] = { 'h', 'a', 'i', '\0' };
char s2[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
char s3[8] = "welcome";
char s4[] = "Programming in C++";
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;
return 0;
}
Output:

s1 = hai

s2 = hello

s3 = welcome

s4 = Programming in C++
Finding the length of a string without using string Library function:
#include <iostream>
using namespace std;
int main() {
char ch[20];
int i = 0;
cout << "Enter a string : ";
cin >> ch;
cout << "The entered string is : " << ch << "\n";
while (ch[i] != '\0’)
{
i++;
}
cout << "The length of the string " << ch << " is : " << i <<"\n";
return 0;
}

Output:

Enter a string : Learning

The entered string is : Learning

The length of the string Learning is : 8

strlen() and strcpy() in built functions:


The function strlen() is used to find the length of a given string. This function
returns only integer data (or) numeric data.

It stops counting characters when NULL character is found.


Because, NULL character indicates the end of the string in C++.

The syntax of strlen() is

integer_variable = strlen(string);
Here string is a group of characters, strlen() function finds the length of the string
and finally integer value will be stored in the integer_variable.

The function strcpy() is used to copy one string into another string including
the NULL character (terminator char ‘\0’).

The syntax of strcpy( ) is

strcpy(string1, string2);

Where string1, string2 are two strings and the string2 is copied into string1. In this
case the copied string is available in string1 and both strings contain the same data.

If length of string1 is less than the length of string2, then the entire string2 value
will not be copied into string1.

For example, consider that the length of string1 is 20 and that of string2 is 30.
Then, only 20 characters from string2 will be copied into string1, the
remaining 10 characters will not be copied and will be truncated.

strcat() and strcmp():

The function strcat() is used to concatenate two strings into one string.
The syntax of strcat() is

strcat(string1, string2);,

where string1, string2 are two different strings. Here string2 is concatenated
with string1, and finally the resultant concatenated string is stored in string1.
In strcat() operation, NULL character of string1 is overwritten by first
character of string2 and NULL character is added at the end of new string1 which is
created after strcat() operation.

The function strcmp() is used for comparison of two strings and it always returns
numeric data.
integer variable = strcmp (string1, string2);

where string1, string2 are two strings and variable is of the type integer.

The comparison of two strings is dependent on the alphabets and not on the
size of the strings.

If the function strcmp() returns zero, both strings are equal.


If the function returns less than zero, string2 is higher than string1.
If the function returns greater than zero, string1 is higher than string2.

Program for finding length of a String :

#include <iostream>

using namespace std;

#include<string.h>

int main()

char s1[50];

cout<<"Enter a string"<<endl;

cin>>s1;

cout<<"string Length=";

int len=strlen(s1);

cout<<len;

return 0;

Output:

Enter a string

Hello

string Length=5
Program for demonstration of stacat(), strcmp(), strcpy(), strlen()
#include <iostream>
#include <string.h>
using namespace std;
int main () {
char a[20], b[20], c[20];
int length;
cout << "Enter a string :";
cin >> a;
length = strlen(a);
cout << "The length of the string " << a <<" is "<< length <<"\n";
strcpy(b, a);
cout << "The copied string = " << b << "\n";
cout << "Enter the second string :";
cin >> c;
strcat(a, c);
cout << "The concatenated string = " << a << "\n";
int i=strcmp(b, c);
if(i == 0) {
cout << "The given two strings are equal" << "\n";
} else if(i > 0) {
cout << "The string " << b << " is higher than the string
" << c << "\n";
} else {
cout << "The string " << c << " is higher than the string "
<< b << "\n";
}
Enter the second string :Morning
}
The concatenated string =
Output :
GoodMorning
Enter a string :Good
The string Morning is higher than the
The length of the string Good is 4 string Good

The copied string = Good


C++ program that takes the string from the user and prints the reversed string.
#include <iostream>
#include <string.h>
using namespace std;
// function definition of the reverse()
void reverse(char *str1) {
// declare variable
int i, len, temp;
len = strlen(str1);
// use strlen() to get the length of str string
for(i = 0;i < len/2;i++)
{
//temp variable use to temporary hold the string
temp = str1[i];
str1[i] = str1[len - i - 1];
str1[len - i - 1] = temp;
}
}
int main()
{
char str[50] = "welcome";
cout << "Before reversing the string: " << str;
reverse(str);
cout<< "\nAfter reversing the string: " << str;
return 0;
}
Output:
Before reversing the string: welcome
After reversing the string: emoclew
string Class

These are the new types of strings that are introduced in C++ as string class defined
inside <string> header file. This provides many advantages over conventional C-style
strings such as dynamic size, member functions, etc.
Declaration and initialization of a string :

string str("GeeksforGeeks");

or

string str=”GeeksforGeeks”;

// C++ Program to demonstrate the use of string keyword

#include <iostream>
using namespace std;
int main()
{

string s = "GeeksforGeeks"; // initializing a string method1

string str("programming in c++"); // initializing a string method2

cout << "s = " << s << endl;

cout << "str = " << str << endl;

return 0;

Output :
s = GeeksforGeeks
str = programming in c++
How to Take String Input in C++

String input means accepting a string from a user. In C++. We have different types of taking
input from the user which depend on the string. The most common way is to take input
with cin keyword with the extraction operator (>>) in C++. Methods to take a string as
input are:

 cin
 getline
1. Using Cin

The simplest way to take string input is to use the cin command along with the
stream extraction operator (>>).
Syntax:
cin>>s;
Example:
// C++ Program to demonstrate string input using cin
#include <iostream>
using namespace std;
int main()
{
string s;
cout<<"Enter String"<<endl;
cin>>s;
cout<<"String is: "<<s<<endl;
return 0;
}

Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks

2 Reading a string using getline() function.

The getline() function in C++ is used to read a string from an input stream. It is
declared in the <string> header file.

It is a member function of the istream class and it is involved with


an istream object cin.

The syntax of getline() is:


cin.getline(char *, size);
Let us consider an example:

char ch[20];

cin.getline(ch, 20);

Here ch is an array of type char, cin.getline() is used to read a line of text from the
input stream and it is terminated as soon as either a new line character (\n) is
encountered or maximum size of characters are read.
By reading characters using getline(), one character in size is reserved
for null character '\0’.

Program :
#include <iostream>
using namespace std;
int main()
{
Output:
char ch[20];
Enter a string :
cout << "Enter a string : "<<endl;
welcome
cin.getline(ch,20);
The given text is..welcome
cout<<"The given text is.."<<ch<<endl;
return 0;
}
Program :
#include<iostream>
using namespace std;
int main()
{
string str1 = "apple";
string str2 = "banana";
if (str1==str2)
cout<<"Both Strings are equal";
else
cout<<"Both strings are not equal";
return 0; }
1.17C++ String Functions

C++ ome inbuilt functions which are used for string manipulation, such as the
strcpy() and strcat() functions for copying and concatenating strings. Some of
them are:

Function Description

length() This function returns the length of the string.

swap() This function is used to swap the values of 2 strings.

size() Used to find the size of string

This function is used to resize the length of the string up to the


resize()
given number of characters.

find() Used to find the string which is passed in parameters

This function is used to push the passed character at the end of


push_back()
the string

pop_back() This function is used to pop the last character from the string

clear() This function is used to remove all the elements of the string.

This function compares at most the first num bytes of both passed
strncmp()
strings.

This function is similar to strcpy() function, except that at most n


strncpy()
bytes of src are copied

This function locates the last occurrence of a character in the


strrchr()
string.

This function appends a copy of the source string to the end of the
strcat()
destination string
This function is used to search for a certain substring inside a string
find()
and returns the position of the first character of the substring.

This function is used to replace each element in the range [first,


replace()
last) that is equal to old value with new value.

substr() This function is used to create a substring from a given string.

This function is used to compare two strings and returns the result
compare()
in the form of an integer.

erase() This function is used to remove a certain part of a string.

Explanation:
1. String Length – length() or size()
We can find the length of the string (number of characters) using either length()
or size() function of the std::string class.
Syntax
string_object.size()
or
string_object.length()
Parameters
 This function does not take any parameter.
Return Value
 This function returns the number of characters in the string object.
Example
std::string text = "geeksforGeeks";
int length = text.length();
//or
int length = text.size();
It will return the length of the string text which is 13.
2. Accessing Characters – at()

Generally, we can access the character of a string using the [] array subscript
operator and indexing. But std::string also has a function named at() which
can be used to access the characters of the string.
Syntax
string_object.at(index);
Parameters
 index: It represents the position of the character in the string.
Return Value
 This function returns the character present at the index.
Example
std::string str = "GEEKSFORGEEKS";
std::cout << str.at(3);
The std::cout will print K on the console as it is the character present at index 3.
3. Concatenating Strings – append() or + Operator
We can concatenate string in C++ using two methods:
(i) + Operator
The + operator is overloaded in the std::string class to perform string
concatenation.
Syntax
string_object1 + string_object2
Example
std::string firstName = "Geeks";
std::string lastName = "forGeeks";
std::string fullName = firstName + " " + lastName;
+ operator is used to concatenate two strings. The string fullName will be
“GeeksforGeeks”.
(ii). append()
The append() function is another member function to concatenate two strings.
Syntax
string_object1.append(string2)
Parameters
 string2: This function takes the string to be appended as a parameter. It can
be both C or C++ Style string.
Return Value
 Reference to the final string.
std::string base = "Hey! Geeks";
base.append(" Welcome to GeeksforGeeks!"); // Append a string
The append() function adds one string to the end of another.
4. String Comparison – compare() or == Operator
Just like the concatenation, we can do the string comparison using two methods:
(i). == Operator
The equality operator can be used to compare the two strings as it is overloaded for
this operation in the std::string class.
Syntax
string_object1 == string_object2
This will return true if both the strings are equal, otherwise returns false.
Example
std::string str1 = "apple";
std::string str2 = "banana";
if (str1 == str2) {
std::cout << "Strings are equal";
}
else {
std::cout << "Strings are not equal";
}
Here, “Strings are not equal” will be printed as the == operator will return false.
(ii). compare()
The compare() function is a member function of std::string class which can be
used to compare two strings.
Syntax
str1.compare(str2);
Parameters
 str2: It is the string to be compared. It can be both C or C++ style string.
Return Value
 If the strings are equal, return zero.
 If str1 is greater than str2, return value >0
 If str2 is greater than str1, return value <0
Example
string str1 = "Geeks";
string str2: = "Geeksfor";
int result = str1.compare(str2);
The result will contain a value less than zero as str2 is greater than str1.
We can also compare the substring of str2 using the compare function():
str1.compare(position, length, str2);
where,
 position: position of the first character substring.
 length: length of the substring.
 str2: String object to be compared.
5. Searching – find()
We can use the find() function of the std::string class to check whether a given
character or a substring is present in the string or a part of string.
Syntax of find()
str1.find(var);
Parameters
 var: It can be a C style string, C++ style string, or a character that is to be
searched in the string.
Return Value
 It returns the pointer to the first occurrence of the character or a substring
in the string.
Example
std::string text = "C++ Programming";
int position = text.find("Programming"); // Find the position of a substring
The position variable will contain 4 which is the start of the first occurrence of the
string “Programming” in string text.
6. Generate Substring – substr()
We can use the substr() function to generate a part of the string as a new
string object. It is a member function of the std::string class.
Syntax of substr() in C
str1.substr(start, end);
Parameters
 start: Starting position of the substring to be generated.
 end: Ending of the substring to be generated.
Return Type
 It returns the newly created string object.
Example
std::string text = "Hello, World!";
std::string sub = text.substr(7, 5); // Extract "World"
In the above example. the sub string will contain the “World”.
Modifying Strings
The following function allows us to modify the current string.
1. insert()
The insert() function not only allows us to add a string but also allows us to add it
at the specified position. It is also a member function of the std::string class.
Syntax
str1.insert(index, str2);
Parameters
 str2: string to be inserted.
 index: position of where to insert the new string
Return Type
 Reference to the str1.
Example
string text = "I have a cat.";
text.insert(9, " black"); // Insert " black" at position 9
2. replace()

The replace() function replaces the part of the string with the given other string.
Unlike insert, the characters in the part where the new string is to be inserted are
removed.
Syntax
str1.replace(index, size, str2);
Parameters
 index: Index of where to start replacing the new string.
 size: length of the part of the string that is to be replaced.
 str2: new string that is to be inserted.
Return Type
 Reference to the str1.
Example
std::string text = "I like dogs.";
text.replace(7, 4, "cats"); // Replace "dogs" with "cats"
3. erase()
The erase() function is a member function of std::string class that is used to remove
a character or a part of the string.
Syntax
str1.erase(start, end);
Parameters
 start: Starting position.
 end: Ending position.
Return Type
 Reference to the str1.
Example
string text = "This is an example.";
text.erase(5, 3); // Erase "is “
Example of String Functions in C++
The below code demonstrate the use of the above specified string functions:
// C++ Code to demostrate various functions available in String class
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Creating and initializing strings
string greeting = "Hello, World!";
cout << greeting << endl;
string name;
// Input from the user
cout << "Enter your name: ";
cin >> name;
cout << name << endl;
// String length
int len = name.length();
cout <<"Length of the string"<<len<< endl;
// Accessing characters
char firstChar = greeting[0];
char secondChar = greeting.at(1);
cout << firstChar << " " << secondChar << endl;
// Appending and concatenating strings
string firstName = "Geek";
string lastName = "Geeks";
string fullName = firstName + " " + lastName;
cout << fullName << endl;
string base = "Hello";
cout << base << endl;
base.append(" World!");
cout << base << endl;
// String comparison
string str1 = "apple";
string str2 = "banana";
if (str1 == str2) {
cout << "Strings are equal" << endl;
}
else {
cout << "Strings are not equal" << endl;
}
int result = str1.compare(str2);
if (result == 0) {
cout << "Strings are equal" << endl;
}
else if (result < 0) {
cout << "str1 comes before str2" << endl;
}
else {
cout << "str1 comes after str2" << endl;
}
// Substrings
string text = "Hello, World!";
cout << text << endl;
string sub = text.substr(7, 5);
cout << sub << endl;
// Searching
string searchIn = "C++ Programming";
size_t position = searchIn.find("Programming");
if (position != string::npos) {
cout << "Found at position " << position << endl;
}
else { Output:

cout << "Not found" << endl; Hello, World!

} Enter your name: Kumar

// Modifying strings Kumar

string modify = "I like dogs."; Length of the string5

modify.replace(7, 4, "cats"); He

cout << modify << endl; Geek Geeks

modify.insert(6, " black"); Hello

cout << modify << endl; Hello World!

modify.erase(6, 6); Strings are not equal

cout << modify << endl; str1 comes before str2

// Conversion Hello, World!

string str = "C++"; World

const char* cstr = str.c_str(); Found at position 4

cout << cstr << endl; I like cats.

return 0; I like black cats.

} I like cats.
C++
1.18 Array Of Strings :

An array of strings is a two-dimensional character array.

The size of the first index (rows) determines the number of strings and the size
of the second index (columns) determines maximum length of each string.

The syntax of declaring an array of strings is:

char array_name[row_size][column_size];

Let us consider an example:

char str[4][7] = {"First", "Second", "Third", "Four" };

In the above statement str is an array name which refers 4 strings and each
string of maximum length is 7.
The memory allocation to the array str is looks like as:

F i r s t \0

S e c o n d \0

T h i r d \0

F o u r \0

It is very easy to access an individual string, by just specifying the first index
as str[0] we can access the first string.
Program :
#include<iostream>
using namespace std;
int main()
{
char str[4][10]={"India","China","England","Russia"};
cout<<"The First Nation is .."<<str[0]<<endl;
cout<<"The Last nation is.."<<str[3];
return 0;
}
Output:

The First Nation is ..India

The Last nation is..Russia

Program for sorting names in Alphabetical order


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char names[7][10], temp[10]; //creating two character arrays, one for
storing and one for interchanging
int i, j;
cout<<"Enter any 5 names : ";
for(i=0; i<5; i++)
{
cin>>names[i];
}
for(i=4; i>=0; i--) //bubble sort begins to sort the data
{
for(j=0; j<=i; j++)
{
if(strcmp(names[j], names[j+1])>0) //comparing only the ASCII
equivalent of the entire word and interchanging if greater
{
strcpy(temp, names[j]);
strcpy(names[j], names[j+1]);
strcpy(names[j+1], temp);
}
}
}
cout<<"Names rearranged in alphabetical order : \n";
for(i=0; i<5; i++)

{
cout<<names[i]<<"\n";

return 0;
}

Output:
Enter any 5 names : kumar mani yaswanth akhil sundar

Names rearranged in alphabetical order :


akhil

kumar

mani
sundar

Yaswanth
10. Assignment Questions

Write programs for the given problems


S.No. K- COs
Level
You are tasked with creating a simple budgeting program. A
user will input their initial monthly budget, the amount they
1. spent on two different categories, and then an additional
expense they need to account for. Your program should:
 Subtract the sum of the two expenses from the initial
budget.
 Add the additional expense to the remaining budget.
K1 CO1
 Output the final adjusted budget.
Input Format:
The input consists of four integer numbers in a single line
separated by spaces:
 The initial monthly budget.
 The amount spent on the first category.
 The amount spent on the second category.
 The additional expense.
The Inputs are
500 100 50 25
The Output Should be : 375

In a city, Jaya, a data analyst with a penchant for discovery, K2 CO1


embarked on a quest to unravel the secrets within her array
2. of n elements. Inspired by the transformative power of
cubing, she crafted a tool that would calculate the cubes of
each element in her array.

Write the code that Jaya used to craft the tool that calculates
the cube of each element in an array.
Write programs for the given problems
S.No. K-Level COs

C++ Program to check if two Arrays are Equal or not K3 CO1


Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {5, 4, 3, 2, 1}
Output : Equal
3 Explanation: As both the arrays contain same elements.
Input: arr1[] = {1, 5, 2, 7, 3, 8}, arr2[] = {8, 2, 3, 5, 7, 1}
Output : Equal
Neha is engaged in a game with her friends. The game K4 CO1
involves N friends, each contributing a word. In the end,
4 Neha needs to combine all the words into a single word and
declare it loudly. Could you assist in implementing a
program to concatenate all the words spoken by her friends
and help Neha?
The input is
3 app le s
Output Should be : apples
The students of a class are asked to write a program to add K5 CO1
5 'ing' at the end of a given string. If the given string already
ends with 'ing' then add 'ly' instead. If the length of the
given string is less than 3, leave it unchanged.
11. Part A
Question &
Answer
PART - A
1.What are the features of C++ ?

2.Define Object-Oriented Programming

Object-oriented programming can be defined as a programming model which is


based upon the concept of objects. Objects contain data in the form of attributes
and code in the form of methods. In object-oriented programming, computer
programs are designed using the concept of objects that interact with the real
world. Object-oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also
determine their types.

3.List out the differences between procedural and object-oriented


programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program In object-oriented programming, the


is divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

Adding new data and functions is not easy. Adding new data and function is easy.
4.What are types of Programming Languages ?

1.Low Level Languages

1.a Machine Level Language

1.b Machine Level Language

2. High Level Languages

2.a Procedure Oriented languages

2.b. Object oriented languages

5.What are the steps in Program Life cycle :

• Every C Program that is in text form goes through a series of transformations


to obtain the final executable.

• The various Phases of this transformation are as follows:

• Preprocessing

• Assembling

• Compiling

• Linking

• Loading to main memory

6.Define Keywords :

The keywords are the reserved words for specific purposes.

Eg : if , for , else, switch , break…


7.What are the types of Number system?

8.What are the data types available in C++ ?

9.What is meant by a constant variable ?

A variable whose declaration preceded along with const keyword, these variables
are called as read only variables , we can’t alter the value of that constant variables

const int a=10 ;

a=a+10; // this alteration is not permitted


10.What are the types of Errors in C++ ?

Syntax Error
Run time Error
Linker error
Logical Error
Semantic Error

11. Define the rules for naming an Identifier?


Identifiers contain letters and digits
The first character should be a letter or underscore.
Underscore is the only special character that is allowed in an Identifier.
Keywords should not be used as an identifier.
Identifiers are case sensitive.

12. List different datatypes in c++?


Primitive/ basic Derived

User defined

13.what are the primitive datatype?


int , float , char , double, bool, void

∙14.If a=50,b=10 and c=20 evaluate the following expression.


c=(a>0&&a<=10)?++a:a/b
c=(50>0&&50<=10)?++50:50/10 Ans
:C=5

15.List out the Operators in C++?


Arithmetic Operators
Relational operators
Assignment Operators
Logical operators Bitwise
Operators
Conditional or Ternary Operators Increment and
Decrement operators
16.Write Syntax of the Conditional operator with example.
Syntax : (condition) ? expression1 or value1: expression2 or value2
Example

x = (a>b) ? a : b
17.What are the Types of Operators?

18.What are the unary operators available in C++?


 ++ increment operator
 -- decrement operator
 ! Logical NOT
 ~ 1’s complement
19. Write a C++ Program for biggest of 2 numbers using
ternary operator?
#include<iostream>
using namespace std;
int main()
{
int a=14 ,b=8;
(a>b)?cout<<a<<"is big":cout<<b<<" is big";
return 0;
}
Output :
14 is big
20.Define type casting?
The explicit type conversion is called type casting.
This is done by explicitly defining the required type in front of the expression in
parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression

21.What are the conditional statements in C++ ?


 simple if
 If else
 Nested if else
 If else ladder
 Switch

22.What are the looping statements in C++ ?


for loop

while loop
do…while loop

23.C++ program to check a number is odd or even using switch


statement.
#include<iostream>
using namespace std;
int main()
{ output : odd
int a=43;
switch(a%2)
{
case 0:
cout<<"even";
case 1:
cout<<"odd";
} return 0; }
24.What are the differences between entry controlled loop
and exit controlled loop ?
ENTRY CONTROLLED EXIT CONTROLLED
Basis
LOOP LOOP

Execution Flow A loop in which the A loop in which the


given condition is loop body is
checked first, before executed first and
entering the loop then after the given
body condition is checked

Condition Evaluation The loop body would The loop body would
be executed, only if be executed at least
the given condition is once, even if the
true given condition is
evaluated as false

Example For Loop and While Do While Loop is an


Loop are examples of example of exit
this type of loop controlled loop

Use It is used when It is used when one


condition evaluation requires to iterate
is mandatory before through loop body at
executing loop body least once before
condition evaluation

25.C++ Program for biggest of 3 numbers using nested if else


#include <iostream>
using namespace std;
int main()
{
int n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2)
{
if (n1 >= n3)
cout << "Largest number: " << n1; }
else
cout << "Largest number: " << n3;
}
// else, n2 is greater than n1
else {

if (n2 >= n3)


cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
}
return 0;
}
Output :
Enter three numbers: 34 67 59
Largest number: 67

26.C++ program for sum of digits of a given number?


#include<iostream>
using namespace std;
int main()
{
int number, reminder, digitSum = 0;
cout << "Please Enter the Number to calculate Sum of Digits = ";
cin >> number;
while (number > 0)
{
reminder = number % 10;
digitSum += reminder;
number = number / 10;
}
cout << "\nThe Sum of all Digits in a given Number = " << digitSum;
return 0;
}
Output:
Please Enter the Number to calculate Sum of Digits = 473
The Sum of all Digits in a given Number = 14

27.C++ Program for checking a number is Armstrong or not.


#include <iostream>
using namespace std;
int main()
{
int num, originalNum, remainder, result = 0;
cout << "Enter a three-digit integer: ";
cin >> num;
originalNum = num;
while (originalNum != 0)
{
// remainder contains the last digit
remainder = originalNum % 10;
result += remainder * remainder * remainder;
// removing last digit from the original number
originalNum /= 10;
}

if (result == num)
cout << num << " is an Armstrong number.";
else
cout << num << " is not an Armstrong number.";
return 0;
}
Output:
Enter a three-digit integer: 153
153 is an Armstrong number.

28.What are the unconditional control statements?


goto , break , continue

29.List out the differences between break and continue.

Basis for
break continue
Comparison
Task It terminates the It terminates only
execution of the current
remaining iteration iteration of the
of the loop. loop.
Control after 'break' resumes the 'continue' resumes
break/continue control of the the control of the
program to the end program to the
of loop enclosing next iteration of
that 'break'. that loop enclosing
'continue'.
Causes It causes early It causes early
termination of loop. execution of the
next iteration.
Continuation 'break' stops the 'continue' do not
continuation of stops the
loop. continuation of
loop, it only stops
the current
iteration.
Other uses 'break' can be used 'continue' can not
with 'switch', be executed with
'label'. 'switch' and 'labels'.
30.What do you mean by an Array? List Advantages and
disadvantages of Array?
• Array is a set of similar data type.
• Arrays objects store multiple variables with the same type.
• It can hold primitive types and object references.
•Arrays are always fixed
Advantages:
• We can put in place other data structures like stacks, queues, linked lists, trees,
graphs, etc. in Array.
• Arrays can sort multiple elements at a time.
•We can access an element of Array by using an index.
Disadvantages:
• We have to declare Size of an array in advance. However, we may not know
what size we need at the time of array declaration.
• The array is static structure. It means array size is always fixed, so we cannot
increase or decrease memory allocation

31. What are the main elements of an array declaration?


o Array name
o Type and
o Size
32.How to initialize an array?
we can initialize an array in C++ either one by one or using a single
statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
33.Give an example of 2D array initialization.
int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
Or int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
34.C++ Program for finding the mean(average) of a set of
numbers?
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
cout<<"Enter the Array elements"<<endl;
for(i = 0; i < n; ++i)
{
cin >> num[i];
}
for(i = 0; i < n; ++i)
{
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
Output:
Enter the numbers of data: 5
Enter the Array elements
10 20 30 40 50
Average = 30

35.C++ program for checking a string is palindrome or not


#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char string1[20];
int i, length;
int flag = 0;
cout << "Enter a string: "; cin >> string1;
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1; Output :
Enter a string :MADAM
break;
MADAM is a palindrome
}
}
if (flag==1) {
cout << string1 << " is not a palindrome" << endl;
}
else {
cout << string1 << " is a palindrome" << endl;
}
return 0; }
12.PART – B Questions
1. Describe the various types of operators with example supported by C++
2. Describe the features of primitive data types and user defined data types in C++
3. Explain the data types and constants supported by C++.
4. Define Array. Explain the types of Array.
5. Write a C++ Program for arranging the elements into ascending order.
6. Write and explain the conditional statements in C++
7. Explain the looping statements in detail
8. Write a C++ program for finding a number is palindrome or not.
9. Write a C++ program to find the Armstrong numbers from 1 to 1000.
10. Write a C++ Program for to find the sum of digits of a number.
11. Write a C++ Program for sum of even numbers from 1 to 100.
12. Write a C++ program for finding the transpose of a matrix.
13. Explain the built in functions of String in C++.
14. Write a C++ program for checking a matrix is symmetric or not.
14.Write a C++ program for Linear search.
13. Supportive online courses
❖ C++ Basics: Selection and Iteration – Coursera

❖ Complete Modern C++ Programming – Udemy

❖ An Introduction to Programming Through C++ - NPTEL

❖ Programming in C++ - NPTEL

❖ Programming in Modern C++ - NPTEL

❖ C++ Programming Course - Infosys Springboard

❖ C++ Programming - Advanced - Infosys Springboard

❖ Learn C++ Programming - Udemy

❖ Programming in C++: A Hands-on Introduction Specialization – Coursera

❖ C++ Programming for Unreal Game Development Specialization - Coursera

External Links for additional resources

❖ https://swayam.gov.in

❖ https://www.coursera.org

❖ https://www.udemy.com

❖ https://www.sololearn.com

❖ https://www.tutorialspoint.com/cplusplus
❖ https://www.geeksforgeeks.org/courses/cpp-programming-basic-
to-advanced

❖ https://www.geeksforgeeks.org/c-plus-plus
14. Real Time Applications
15. Content beyond syllabus
Namespace in C++

 Namespace provide the space where we can define or declare identifier


i.e. variable, method, classes.
 Using namespace, you can define the space or context in which
identifiers are defined i.e. variable, method, classes. In essence, a
namespace defines a scope.

Different ways to access namespace:

In C++, there are two ways of accessing namespace variables and functions.
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace namespace_name

{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)

}
 It is to be noted that, there is no semicolon (;) after the closing brace.
 To call the namespace-enabled version of either function or variable,
prepend the namespace name as follows:
 Namespace name: :code; // code could be variable , function or class.
Program:
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
} } }
using namespace first_space::second_space;
int main () Output:
{
Inside second_space
// This calls function from second name space.
func();

return 0;
}
//C++ program to demonstrate accessing of variables
// in normal way, i.e., using "::“
#include <iostream>
using namespace std;
namespace geek
{
int rel = 300;
} Output :
300
int main()
{
// variable ‘rel’ accessed
// using scope resolution operator
cout << geek::rel << "\n"; // prints 300
return 0;
}
C++ program to demonstrate accessing of variables
// in normal way, i.e., using "using" directive
#include <iostream>
using namespace std;
namespace geek
{
int rel = 300;
}
// use of ‘using’ directive
using namespace geek;
int main()
{
// variable ‘rel’ accessed
// without using scope resolution variable
cout << rel << "\n"; //prints 300
return 0;
}
16. Assessment Schedule

As per Academic Calendar


17. Text books & References

Text Books:

1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015.
2. E Balagurusamy,” Object Oriented Programming with C++”, 4th Edition, Tata
McGraw- Hill Education, 2008.

Reference Books:

1. Karl Beecher,” Computational Thinking: A beginner's guide to problem-solving


and programming”, BCS Learning & Development Ltd, 2017. (Unit 1)
2. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th
Edition, Jones and Barklett Publishers, 2010.
3. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
4. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
5. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata
McGraw- Hill Publishing Company Ltd., 2007.
6. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
7. Paul Deitel, Harvey Deitel, “C++ How to Program”, 10th Edition, Pearson
Education Inc. 2017.
8. https://infyspringboard.onwingspan.com/web/en/app/toc/
lex_auth_01297200240671948837_shared/overview
18. Mini Project Suggestions

1. Student Record Management System

By building this project, you will comprehend the basics of the input and
output course. Furthermore, this C++ project structure will help you in knowing
about the system of file management. The program designed by you will be ready
to accumulate all the students’ data and information correctly. This data can be any
information related to the student, their personal information, academic records,
roll number, etc. This project will teach you how to tackle wrong inputs. ( K1, CO1)

2.Bank Management System in C++


This is a very common project and can make you a project in C++,

all you have to do is

 Open an account

 Show account details

 Deposit

 Withdraw

 Search and exit.

This project will let you understand the fundamentals of banking apps. In a
nutshell, you can say that this primary C++ project is going to familiarize you with
data adjustment, how to add, modify or delete any filed record ( K2, CO1)
3. Bookshop Management System Using C++

To build an application that will let its customers add and display
books. Furthermore, it will help the customers to change their books by
implementing modifications to them or adding or deleting pages. Create an
application that will be user-friendly and effortless to access and use. It also lets
users check and buy their favourite books anytime, anywhere with one click. (
K3,CO1)

5. Credit Card Validator

In this digital world where e-commerce is ruling, credit cards are a


must-have. Most payment gateways utilize some kind of validation mechanism
for credit card data before they proceed with the payment. The validation
operates differently for different cards, so deciding what type of card it is and
then inspecting if the number entered is a valid credit card number or not is the
way to go. (K4,CO1)

5.Digital Calculator
This project is particularly GUI-driven, making it easy to execute.
This project will be a menu-driven program in which the outputs will be given by
the user. It assists to strengthen some of the fundamental concepts of C++,
particularly relating data types and decision-making statements.
The project requires validation for the inputs so that the calculation only takes
place if the inserted data is numerical by nature. (K5, CO1)
Thank
you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contentsof this information is strictly prohibited.

You might also like