0% found this document useful (0 votes)
3 views832 pages

C++ Programming Notes

C++ is a multi-paradigm programming language developed as an extension of C, supporting procedural, object-oriented, and generic programming. It is widely used in various applications such as operating systems, game development, and embedded systems due to its efficiency and performance. Key features include simplicity, object-oriented capabilities, rich library support, and reusability, making it a foundational language for learning other programming languages.

Uploaded by

Satya Yedla
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)
3 views832 pages

C++ Programming Notes

C++ is a multi-paradigm programming language developed as an extension of C, supporting procedural, object-oriented, and generic programming. It is widely used in various applications such as operating systems, game development, and embedded systems due to its efficiency and performance. Key features include simplicity, object-oriented capabilities, rich library support, and reusability, making it a foundational language for learning other programming languages.

Uploaded by

Satya Yedla
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

C++ Programming

C++ Programming

Evolution Timeline
• 1979 – “C with Classes”
• 1983 – Named C++
• 1998 – C++98 (Standardized)
• 2011 onwards – Modern C++ (C++11, C++14, C++17, C++20)

Usage
C++ is used in:
• Operating systems
• Game development
• Embedded systems
• Compilers
• High-performance applications
C++ Programming

What Makes C++ Special?


Definition
C++ is a multi-paradigm language that supports:
• Procedural programming
• Object-oriented programming
• Generic programming

Why Learn C++


• Very fast and efficient
• Close to hardware
• Used in real-world systems
• Base language for learning Java, Python, etc.
C++ Programming

Properties (Features) of C++


1. Simple
• Extension of C
• Familiar syntax
• Easy transition from C to C++

2. Object-Oriented
Supports:
• Classes
• Objects
• Encapsulation
• Inheritance
• Polymorphism

3. Fast and Efficient


• Uses compiled code
• Direct memory access using pointers
• Suitable for performance-critical applications
C++ Programming

Development of C++
Definition
C++ is a general-purpose programming language developed as an extension of the C language, adding
object-oriented and modern programming features.

Who Developed C++


• Developed by Bjarne Stroustrup
• Developed at Bell Laboratories
• Year: 1979–1983

Why C++ Was Created


• C language was powerful but:
• No support for Object-Oriented Programming
• Hard to manage large and complex programs
• Goal:
Combine C’s speed with OOP concepts
C++ Programming

4. Platform Independent (Partially)


• Programs can run on multiple platforms
• Needs recompilation for each OS

5. Rich Library Support


• STL (Standard Template Library)
• Predefined functions and data structures

6. Reusability
• Code reuse using:
• Functions
• Classes
• Inheritance
C++ Programming

Example Showing Simplicity of C++


Explanation
•#include <iostream> → Input/Output library
•using namespace std; → Avoid writing std:: again and
again
•main() → Program execution starts here
•cout → Output statement
C++ Programming

Practice Program
Problem
Write a C++ program to display:
I am learning C++
C++ Programming

Common Mistakes
• Forgetting semicolon ;
• Missing #include <iostream>
• Writing cout without using namespace std;
• Wrong case (Main instead of main)
Tip: C++ is case-sensitive
C++ Programming

Pro Tips for Students


• Start with basic syntax
• Practice small programs daily
• Understand why, not just how
• Learn C++ concepts → OOP → STL
• Use online compilers for practice
C++ Programming

Quick Summary
• C++ is an extension of C
• Developed by Bjarne Stroustrup
• Supports both procedural & OOP
• Fast, powerful, and widely used
• Foundation for advanced programming
Object-Oriented Programming
C++ Programming

Definition
Object-Oriented Programming (OOP) is a programming approach
that organizes a program using objects and classes, making code
more modular, reusable, and easy to manage.

Why OOP?
• Real-world problems are complex
• Procedural programming becomes hard to manage for large
programs
• OOP helps by dividing problems into smaller objects
C++ Programming

Real-World Analogy of OOP


Real World Example
Car
• Properties → color, brand, speed
• Actions → start(), stop(), accelerate()
In OOP:
• Car → Class
• MyCar → Object
C++ Programming

Key Concepts of OOP


Four Pillars of OOP
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
(First learn Class & Object → then pillars)
C++ Programming

Class
Definition
A class is a blueprint or template used to create objects.

Usage
• Defines data (variables) and functions
• Does not occupy memory until an object is created

Syntax
class ClassName {
access_specifier:
data_members;
member_functions;
};
C++ Programming

Example
class Student {
public:
int roll;
void show() {
cout << "Student class";
}
};
C++ Programming

Object
Definition
An object is a real instance of a class.

Usage
• Represents real-world entities
• Occupies memory

Syntax
ClassName objectName;

Example
Student s1;
[Link] = 10;
[Link]();
C++ Programming

Sample Program (Class & Object)


C++ Programming

Encapsulation
Definition
Encapsulation is the process of wrapping data and functions
together and protecting data from outside access.

Usage
• Improves security
• Prevents accidental data modification
C++ Programming
C++ Programming

Inheritance
Definition
Inheritance allows one class to acquire properties of another class.

Usage
• Code reuse
• Faster development

Syntax
class Child : public Parent {
};
C++ Programming
C++ Programming

Polymorphism
• Definition
• Polymorphism means one function name, multiple behaviors.

• Types
• Compile-time (Function Overloading)
• Run-time (Function Overriding)
C++ Programming
C++ Programming

Abstraction
Definition
Abstraction means hiding internal details and showing only essential
features.

Usage
• Reduces complexity
• Improves readability
C++ Programming

Practice Program
• Problem
• Create a class Rectangle with:
• length, breadth
• function to calculate area
C++ Programming
C++ Programming

Common Mistakes
• Forgetting public: keyword
• Accessing private data directly
• Missing semicolon after class
• Confusing class and object
C++ Programming

• Always design class first, then object


• Keep data private
• Use meaningful class names
• Practice real-world examples
• OOP = thinking in objects, not lines of code
C++ Programming

Quick Summary
• OOP models real-world problems
• Class → Blueprint
• Object → Instance
• Four pillars make code:
• Secure
• Reusable
• Maintainable
• Scalable
Developing C++
C++ Programming
C++ Programming
C++ Programming

Definition – What is a C++ Program?


Definition
A C++ program is a collection of functions.
• Some functions belong to classes (member functions)
• Some are global functions (not part of any class)
Every function performs a specific task and can call other functions.
The most important function is main(), which acts as the
starting point of the program.
C++ Programming

Usage – Why main() Is Mandatory


Usage
• Program execution always starts from main()
• Without main(), a C++ program cannot run
• main() controls the overall flow of the program
Think of main() as the entry gate of a C++ program.
C++ Programming

Preprocessor Directive – #include


Definition
Lines starting with # are handled by the preprocessor before
compilation.
Usage
#include copies the contents of a header file into the program.
Syntax
#include <header_name>
Example
#include <iostream>
iostream provides input and output stream functionality.
C++ Programming

Streams and iostream


Definition
A stream is a flow of data from a source to a destination.
Usage
• iostream supports:
• Input (keyboard → program)
• Output (program → screen)
Common stream objects:
• cin → input
• cout → output
C++ Programming

Structure of main() Function


Syntax
int main()
{
statements;
return 0;
}
Explanation
• int → return type
• main → fixed function name
• {} → function body
• return 0; → program ended successfully
C++ Programming

Output Statement – cout


Syntax
cout << "Text" << endl;
Explanation
• cout → console output object
• << → insertion operator (pushes data to output)
• endl → moves cursor to next line
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
The Type bool in C++
C++ Programming

The Type bool in C++


Definition
bool is a built-in data type in C++ used to store logical values.
It can have only two possible values:
• true → logical 1
• false → logical 0
C++ Programming

Usage
The bool type is mainly used to:
• Make decisions using if, else, switch
• Control loops (while, for)
• Store results of comparisons (>, <, ==)
• Represent conditions (yes/no, on/off, valid/invalid)
Almost every decision-making program uses bool.
C++ Programming

Syntax
bool variable_name;
Initialization
bool isPassed = true;
bool isEmpty = false;
Using expressions
bool result = (10 > 5);
Any relational or logical expression evaluates to a bool.
C++ Programming

Sample Program
C++ Programming

Another Example (Comparison Result)


C++ Programming

Practice Program
Problem
Write a program to check whether a number is even using bool.
C++ Programming

Common Mistakes
Using quotes:
bool flag = "true"; // WRONG
Using assignment instead of comparison:
if (x = 5) // WRONG
Correct:
if (x == 5)
Assuming bool stores text
It stores only 0 or 1 internally.
C++ Programming

Pro Tips
Use meaningful names:
bool isLoggedIn;
bool hasPermission;
Prefer bool instead of int for conditions
Combine with logical operators:
if (isAdult && hasID)
Use boolalpha to print true/false:
cout << boolalpha << isAdult;
C++ Programming

Quick Summary Slide


• bool stores true / false
• Internally → 1 / 0
• Used in conditions, loops, comparisons
• Makes code clear and readable
The char and wchar_t Types
in C++
C++ Programming

1. The char Type


Definition
char is a basic data type in C++ used to store a single character such as a letter,
digit, or symbol.
• Size: 1 byte (8 bits)
• Stores characters using ASCII values

Usage
The char type is used to:
• Store letters ('A', 'b')
• Store digits as characters ('5')
• Store special symbols ('@', '#')
• Work with text, passwords, grades, menu choices
C++ Programming

Syntax
char variable_name;
Initialization
char grade = 'A';
char symbol = '#';
Characters must be enclosed in single quotes ' '
C++ Programming

Sample Program
C++ Programming

Character as ASCII Value


C++ Programming

Common Mistakes (char)


Using double quotes:
char ch = "A"; // WRONG
Storing multiple characters:
char ch = 'AB'; // WRONG
Correct:
char ch = 'A';
C++ Programming

Pro Tips (char)


Use char for single characters only
Use string for words or sentences
ASCII knowledge helps in encryption & logic problems
C++ Programming

2. The wchar_t Type


Definition
wchar_t is a wide character data type used to store large character
sets, such as:
• Unicode characters
• Non-English languages (Hindi, Chinese, Arabic, etc.)
C++ Programming

Usage
Use wchar_t when:
• Working with international languages
• Handling Unicode characters
• Programs require multilingual support

Size
• Usually 2 or 4 bytes (depends on compiler & OS)
• Can store thousands of characters
C++ Programming

Syntax
wchar_t variable_name;
Initialization
wchar_t letter = L'A';
Prefix L is mandatory for wide characters.
C++ Programming

Sample Program
C++ Programming

Key Differences: char vs wchar_t

Feature char wchar_t


Size 1 byte 2 or 4 bytes
Character set ASCII Unicode
Language support English only Multi-language
Prefix 'A' L'A'
Output cout wcout
C++ Programming

Practice Program
Problem
Store and display:
[Link] English character using char
2.A Greek or Indian character using wchar_t
C++ Programming

Common Mistakes (wchar_t)


Forgetting L prefix
Using cout instead of wcout
Assuming char supports all languages

Pro Tips
Use char for simple English text
Use wchar_t for Unicode / multilingual programs
For real-world applications, prefer string and wstring
C++ Programming

Quick Summary Slide


• char → single ASCII character (1 byte)
• wchar_t → wide Unicode character
• char → 'A'
• wchar_t → L'Ω'
The Type int (Integer Data
Type in C++)
C++ Programming

Definition
• int is a built-in data type in C++ used to store whole numbers.
• It can store positive numbers, negative numbers, and zero.
• Examples: -25, 0, 42, 1000
C++ Programming

Usage
• Used when values do not contain decimals
• Commonly used for:
• Counting (loops, counters)
• Indexing arrays
• Storing ages, marks, quantities
• Mathematical calculations without fractions
C++ Programming

Syntax
int variableName;
int variableName = value;
Explanation:
• int → data type
• variableName → identifier (name you choose)
• value → integer value assigned to the variable
C++ Programming

Size & Range (Important Concept)


• Size of int is usually 4 bytes (32 bits)
• Typical range:
• −2,147,483,648 to 2,147,483,647
Exact size may vary depending on compiler/system.
C++ Programming

Sample Program
C++ Programming

Arithmetic with int


int a = 10, b = 3;
int sum = a + b;
int division = a / b;
Result:
• sum = 13
• division = 3 (decimal part is lost!)
Integer division removes decimal values.
C++ Programming

Practice Program
Problem:
Write a program to calculate the sum and average of two integers.
C++ Programming

Common Mistakes
Using decimal values with int
int x = 10.5; // Wrong
Expecting decimal result from division
int result = 5 / 2; // Result = 2, not 2.5
Forgetting to initialize
int x;
cout << x; // Garbage value
C++ Programming

Pro Tips
• Use int only for whole numbers
Use float or double for decimal calculations
Initialize variables when declaring
For large numbers, consider long int or long long
Modifiers
C++ Programming

Definition
• Modifiers are keywords used with data types to change the range
of values they can store.
• signed and unsigned are modifiers mainly used with integer
types.
C++ Programming

What is signed?
• signed allows both positive and negative values.
• It is the default behavior for int.
signed int x; // same as int x;
Example values: -10, 0, 25
C++ Programming

What is unsigned?
• unsigned allows only non-negative values (0 and positive).
• Cannot store negative numbers.
• Gives double the positive range compared to signed.
unsigned int y;
Example values: 0, 5, 100
C++ Programming

Why Use Signed & Unsigned?


• Use signed when:
• Values can be negative (temperature, profit/loss)
• Use unsigned when:
• Values are never negative (age, count, roll number)
• You want larger positive range
C++ Programming

Syntax
signed int a;
unsigned int b;
Other valid forms:
unsigned x; // unsigned int
signed short s;
unsigned long n;
C++ Programming

• Size & Range (Typical 4-byte int)


Type Range
signed int −2,147,483,648 to 2,147,483,647
unsigned int 0 to 4,294,967,295

• Size depends on compiler, but range concept remains same.


C++ Programming

Sample Program
C++ Programming

Important Observation
unsigned int x = -5;
cout << x;
Output will be a very large number, not -5.
Reason:
• unsigned cannot store negative values
• Value wraps around using binary representation
C++ Programming

Practice Program
Problem:
Store and display student age and temperature difference.
C++ Programming

Common Mistakes
Using unsigned for values that can be negative
Assigning negative numbers to unsigned variables
Mixing signed and unsigned in comparisons
if (unsignedVal > signedVal) // risky comparison

Pro Tips
int is signed by default
Prefer unsigned only when negatives are impossible
Be careful with arithmetic involving signed & unsigned
For beginners, use int unless range matters
C++ Programming

Quick Summary
• signed → positive + negative numbers
• unsigned → only zero & positive numbers
• unsigned gives larger positive range
• Wrong usage can lead to unexpected results
Short Data Type
C++ Programming

short Data Type in C++


Definition
short is an integer data type used to store small whole numbers using less memory
than int.

Usage
• Used when values are small and memory efficiency is important
• Common in embedded systems and arrays with many elements

Size & Range


• Size: 2 bytes (16 bits)
• Range (signed): −32,768 to 32,767
• Unsigned range: 0 to 65,535
C++ Programming

Syntax
short int a;
short b;
unsigned short c;
C++ Programming

Sample Program
C++ Programming

Practice Program
Store the age of 100 students using an appropriate data type.
short age = 15;
C++ Programming

Common Mistakes
• Assigning very large values
• Assuming size is always same on all systems

Pro Tips
• Use short only when memory matters
• Otherwise, prefer int for simplicity
Long Data Type in C++
C++ Programming

long Data Type in C++


Definition
long is an integer data type used to store large whole numbers.
C++ Programming

Usage
• Used for large counts, IDs, population, distance, etc.
• Useful when int range is not enough
C++ Programming

Size & Range


• Size: 4 or 8 bytes (depends on system)
• Typical range (signed 32-bit):
−2,147,483,648 to 2,147,483,647
C++ Programming

Syntax
long int a;
long b;
unsigned long c;
C++ Programming

Sample Program
C++ Programming

Practice Program
Store the distance between planets in kilometers.
long distance = 778000000;
C++ Programming

Common Mistakes
• Confusing long with long long
• Forgetting system-dependent size

Pro Tips
• Use long long for very large values
• Use sizeof(long) to check size on your system
C++ Programming

Quick Comparison Slide


Data Type Size Range (Signed) Use Case
short 2 bytes −32K to 32K Small numbers
int 4 bytes −2B to 2B General use
long 4/8 bytes Larger values Big numbers
Floating-Point Types (C++)
C++ Programming

Definition
• Floating-point types are data types used to store numbers with
decimal points.
• They are used when values require fractional precision.
Examples: 3.14, -0.5, 12.75, 0.001

Why “Floating” Point?


• The decimal point can move (float) depending on the value.
• Allows representation of very small and very large numbers.
C++ Programming

• Floating-Point Types in C++


Type Typical Size Precision
float 4 bytes ~6–7 decimal digits
double 8 bytes ~15 decimal digits
long double 8–16 bytes Higher than double

• Exact size depends on compiler.


C++ Programming

Usage
• Used when calculations involve:
• Measurements (length, weight, temperature)
• Scientific values
• Financial calculations (with care)
• Average, percentage, division results
C++ Programming

Syntax
float x;
double y;
long double z;
With initialization:
float pi = 3.14f;
double gravity = 9.81;
Note:
• f is used to tell compiler the value is float
C++ Programming

Sample Program
C++ Programming

Floating-Point Division
int a = 5, b = 2;
double result = (double)a / b;
Output:
2.5
Casting ensures decimal result, not integer division.
C++ Programming
C++ Programming

Common Mistakes
Forgetting f in float literals
Comparing floating values using ==
if (a == b) // risky
Assuming floating-point values are exact
C++ Programming

Pro Tips
Use double by default (better precision)
Use float when memory is critical
Avoid equality comparison → use tolerance
if (abs(a - b) < 0.0001)
C++ Programming

Quick Summary
• Floating-point types store decimal numbers
• float → less precision
• double → more precision (recommended)
• Decimal arithmetic may have round-off errors
The sizeof Operator (C++)
C++ Programming

Definition
• sizeof is a compile-time operator in C++.
• It is used to find the memory size (in bytes) of a data type or a
variable.
It helps us understand how much memory a program uses.
C++ Programming

Why Use sizeof?


• To know memory requirements of variables
• To write portable programs
• To calculate array sizes
• To understand differences between data types
C++ Programming

Syntax
sizeof(type)
sizeof(variable)
Both forms are valid.

Basic Examples
sizeof(int)
sizeof(double)
sizeof(char)
int x;
sizeof(x)
Result is always in bytes
C++ Programming
C++ Programming

Using sizeof with Arrays


int arr[5];

int totalSize = sizeof(arr);


int elementSize = sizeof(arr[0]);
int length = totalSize / elementSize;
This gives the number of elements in the array.
C++ Programming

Important Points
• sizeof does not execute at runtime
• It works without initializing variables
• Parentheses are optional for variables
sizeof x; // valid
sizeof(x); // also valid
C++ Programming

Practice Program
Problem:
Write a program to find the number of elements in an integer array
using sizeof.
C++ Programming

Common Mistakes
Assuming same size on all systems
Using sizeof on pointer instead of array
int *p;
sizeof(p); // gives pointer size, not array size
Forgetting that output is in bytes

Pro Tips
Use sizeof for array length in same scope
Prefer sizeof(variable) for readability
Combine with arrays for safer loops
Helps in memory-efficient programming
C++ Programming

Quick Summary
• sizeof → returns memory size in bytes
• Works on data types and variables
• Evaluated at compile time
• Extremely useful for arrays and portability
C++ Programming
CONSTANTS (C++)
C++ Programming

Definition
• A constant is a value that cannot be changed during program
execution.
• Once defined, its value remains fixed throughout the program.
Example: PI = 3.14, MAX = 100
C++ Programming

Why Use Constants?


• Prevents accidental changes
• Improves readability
• Makes programs easy to modify
• Helps write safe and reliable code
C++ Programming

Types of Constants in C++


C++ supports two major types of constants:
[Link] Constants
[Link] Constants
C++ Programming

1. Literal Constants
Definition
• Fixed values written directly in the program
• Value cannot be changed
C++ Programming

• Types of Literal Constants


Type Example
Integer 10, -5, 100
Floating 3.14, -0.5
Character 'A', '9'
String "Hello"
Boolean true, false
C++ Programming

Example
int x = 10;
char grade = 'A';
float pi = 3.14f;
C++ Programming

2. Symbolic Constants
Definition
• Constants defined using names
• More meaningful than literals
C++ Programming

Ways to Create Symbolic Constants


(a) Using const Keyword (Recommended)
const int MAX = 100;
const float PI = 3.14f;
Value cannot be modified
MAX = 200; // Error

(b) Using #define Preprocessor


#define PI 3.14
No type checking
Not recommended for beginners
C++ Programming
Sample Program
#include <iostream>
using namespace std;

int main() {
const float PI = 3.14f;
int radius = 5;

float area = PI * radius * radius;

cout << "Area of circle = " << area << endl;


return 0;
}
Output:
Area of circle = 78.5
C++ Programming

Practice Program
Problem:
Create a constant for GST rate (18%) and calculate final price.
C++ Programming

Common Mistakes
Trying to modify a constant
Using #define instead of const
Forgetting to initialize const variable
const int x; // Error
C++ Programming

Pro Tips
Use const for safety
Write constant names in UPPERCASE
Declare constants near the top
Improves debugging and maintenance
C++ Programming

Quick Summary
• Constants store fixed values
• Two types: literal & symbolic
• const keyword is preferred
• Constants improve program quality
Escape Sequences in C++
C++ Programming

Definition
An escape sequence in C++ is a special character combination that
starts with a backslash (\) and is used inside string literals to
represent characters that cannot be typed directly or have special
meaning.
C++ Programming

Usage (Why Escape Sequences Are Needed)


Escape sequences are used to:
• Move the cursor to a new line or tab space
• Print special characters like quotes (") and backslash (\)
• Format output neatly on the screen
• Control text appearance in console output
Commonly used with cout
C++ Programming

Syntax
"\escape_character"
Explanation:
• \ → escape character (backslash)
• escape_character → tells the compiler what special action to
perform
C++ Programming

Common Escape Sequences Table


Escape Sequence Meaning
\n New line
\t Horizontal tab
\\ Backslash
\" Double quote
\' Single quote
\b Backspace
\r Carriage return
\a Alert (beep sound)
\0 Null character
C++ Programming
C++ Programming

Practice Program
Write a program to print the following output using escape
sequences:
Name: Satya
Course: C++ Programming
Quote: "Practice makes perfect"
C++ Programming

Common Mistakes
Forgetting to use \ before special characters
Always escape quotes: \"
Using /n instead of \n
Escape sequences always start with backslash
Expecting escape sequences to work outside strings
They work only inside " " or ' '
C++ Programming

Pro Tips
Use \n instead of multiple endl for faster output
Combine multiple escape sequences in one string
Learn \\ early—it’s very common in file paths
Visualize \t as a column spacer
C++ Programming

Quick Memory Trick


• n → new line
• t → tab
• " → quote
• \ → print backslash
C++ Programming
C++ Programming
C++ Programming
Keywords in C++
C++ Programming

Keywords in C++
Definition:
Keywords in C++ are reserved words that have predefined
meanings in the language.
They are used to perform specific tasks like defining data types,
control flow, or program structure.
Important:
• Keywords cannot be used as variable names, function names, or
identifiers.
Examples:
int, if, return, while, class
C++ Programming

Why Keywords Are Important (Usage)


Usage of Keywords:
• To declare data types (int, float, double)
• To control program flow (if, else, for, while)
• To define functions and return values (void, return)
• To support Object-Oriented Programming (class, public,
private)
• To handle memory and logic (new, delete, const)
Every C++ program uses keywords.
C++ Programming

Properties of Keywords
Key Properties:
• Fixed meaning (cannot be changed)
• Written in lowercase (C++ is case-sensitive)
• Cannot be redefined
• Cannot be used as identifiers
Invalid examples:
int class; // ERROR
float return; // ERROR
C++ Programming
Commonly Used C++ Keywords (Beginner
Level)
Category Keywords
Data Types int, float, double, char, bool, void
Control Statements if, else, switch, case
Loops for, while, do
Jump Statements break, continue, return
OOP class, public, private, protected
C++ Programming

Syntax – How Keywords Are Used


General Syntax Example:
keyword identifier;
Explanation:
• keyword → reserved word (like int)
• identifier → user-defined name
Example:
int age;
float salary;
Here:
• int, float → keywords
• age, salary → identifiers
C++ Programming

Sample Program – Using Keywords

Keywords Used:
int, if, return, using, namespace
C++ Programming

Practice Program
Problem:
Write a C++ program to check whether a number is even or odd
using keywords.
C++ Programming

Common Mistakes Students Make


Using keywords as variable names
int for; // ERROR
Changing keyword case
Int a; // ERROR (should be int)
Assuming keywords can be modified
int int = 5; // ERROR
Fix:
Always choose meaningful variable names different from
keywords.
C++ Programming

Pro Tips for Students


Memorize frequently used keywords first
Practice identifying keywords in programs
Use IDE auto-highlighting to spot keywords
Remember:
If the compiler knows the word already → it’s probably a keyword
Tip for teaching:
Ask students to circle keywords in every new program.
C++ Programming

Summary
• Keywords are reserved words in C++
• They have fixed meaning
• They form the building blocks of programs
• Cannot be used as identifiers
Without keywords → no C++ program can run
C++ Programming
C++ Programming

C++ Keywords – Simple Meanings


asm – Allows writing low-level assembly code inside C++ (rarely used).
auto – Compiler automatically figures out the variable’s data type.
bool – Data type that stores true or false.
break – Immediately exits a loop or switch block.
case – Represents one option inside a switch statement.
catch – Handles errors (exceptions) thrown by throw.
char – Data type used to store a single character like 'A'.
class – Blueprint for creating objects (used in OOP).
const – Makes a variable value fixed (cannot be changed).
const_cast – Removes or adds const from a variable (advanced use).
continue – Skips current loop iteration and moves to the next one.
default – Runs when no case matches in a switch.
delete – Frees memory allocated using new.
C++ Programming

do – Loop that runs at least once before checking condition.


double – Data type for decimal numbers with high precision.
dynamic_cast – Converts object types safely during runtime.
else – Runs when if condition is false.
enum – Creates a set of named constant values.
explicit – Prevents automatic type conversion in constructors.
extern – Declares a variable defined in another file.
false – Boolean value meaning “not true”.
float – Data type for decimal numbers.
for – Loop with initialization, condition, and update.
friend – Allows another class/function to access private data.
goto – Jumps to another part of code (not recommended).
if – Executes code when a condition is true.
C++ Programming

inline – Suggests compiler to replace function call with code itself.


int – Data type for whole numbers.
long – Used for storing larger integers.
mutable – Allows changing a variable even inside const objects.
namespace – Groups related code and avoids name conflicts.
new – Allocates memory dynamically.
operator – Used to overload operators like +, ==.
private – Class members accessible only inside the class.
protected – Class members accessible in derived classes.
public – Class members accessible from anywhere.
register – Suggests storing variable in CPU register (obsolete).
reinterpret_cast – Converts one data type into another (unsafe).
return – Sends value back from a function.
C++ Programming

short – Used for smaller integer values.


signed – Allows both positive and negative values.
sizeof – Gives size of a data type or variable (in bytes).
static – Keeps variable value throughout program execution.
static_cast – Converts one data type into another safely.
struct – Like class, but members are public by default.
switch – Selects execution based on value.
template – Used to create generic functions or classes.
this – Refers to the current object.
throw – Sends an error (exception) to be handled.
true – Boolean value meaning correct.
try – Wraps code that may cause an error.
typedef – Creates an alias (new name) for a data type.
C++ Programming

typeid – Gets type information of a variable at runtime.


typename – Tells compiler a name is a type (used in templates).
union – Allows multiple variables to share same memory.
unsigned – Stores only non-negative values.
using – Creates shortcuts for namespaces or types.
virtual – Enables runtime polymorphism (method overriding).
void – Represents “no value” or “no return type”.
volatile – Tells compiler variable can change anytime.
wchar_t – Stores wide characters (Unicode).
while – Loop that runs while condition is true.
C++ Programming

Teach “Must-Know” Keywords First (Core Set)


These are essential and unavoidable:
• int, float, double, char, bool
• if, else, switch
• for, while, do
• break, continue, return
• cin, cout (not keywords, but essential)
• const
• void
Goal: Students should write simple programs confidently.
C++ Programming

Concept-Driven Keywords
Concept Keywords
OOP class, public, private, protected, this
Memory new, delete
Inheritance virtual
Arrays & size sizeof
Enums enum
Namespacing namespace, using
C++ Programming

Advanced Keywords
Just expose the names, no deep explanation:
• template
• friend
• mutable
• volatile
• reinterpret_cast
• typeid
• asm
• register
• goto
C++ Programming

• “You don’t learn C++ by memorizing keywords.


You learn C++ by solving problems, and keywords come
automatically.”
Names in C++ ( Identifiers)
C++ Programming

Names in C++ (Identifiers)


Definition
In C++, a name (also called an identifier) is used to identify
variables, functions, arrays, objects, classes, etc.
C++ Programming

Valid Names (Identifiers) in C++


Definition
A valid name in C++ must follow specific rules defined by the language.
Rules for Valid Names
[Link] start with a letter (a–z, A–Z) or underscore (_)
[Link] contain:
1. Letters
2. Digits (0–9)
3. Underscore (_)
[Link] start with a digit
[Link] spaces allowed
[Link] special symbols like @, #, $, %, &
[Link] not be a C++ keyword
7.C++ names are case-sensitive
C++ Programming

Examples of Valid Names


Valid Identifiers
int age;
float totalMarks;
double _salary;
int count1;
int student_name;
Why Valid?
• Start with letter or underscore
• No spaces or special symbols
• Not keywords
C++ Programming

Invalid Names (Errors)


Invalid Identifiers
int 1number; // starts with digit
float total marks; // space not allowed
double @rate; // special character
int class; // keyword
Why Invalid?
• Breaks naming rules
• Compiler will throw errors
C++ Programming

Keywords Cannot Be Used as Names


Definition
Keywords are reserved words in C++ with predefined meaning.
Examples of Keywords
int, float, double, if, else, while, for,
return, class
Invalid
int int;
float while;
C++ Programming

Case Sensitivity in Names


Concept
C++ treats uppercase and lowercase letters as different.
Example
int age = 10;
int Age = 20;
Both are valid
But they represent different variables
C++ Programming

Naming Conventions in C++


Definition
Naming conventions are recommended styles to name identifiers for
readability and clarity.
Conventions are not rules, but best practices
C++ Programming

Common Naming Conventions


1. camelCase (Most Common)
int totalMarks;
float averageScore;
2. snake_case
int total_marks;
float average_score;
3. PascalCase (Mostly for Classes)
class StudentDetails;
class BankAccount;
C++ Programming

Good vs Bad Naming


Bad Names
int x;
int a1;
float t;
Good Names
int studentCount;
int totalStudents;
float temperature;
Self-explanatory
Easy to understand later
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
Create a program to store and display:
• Employee name count
• Monthly salary
Use meaningful variable names.
C++ Programming

Common Mistakes
Mistakes
• Using keywords as names
• Starting names with digits
• Using spaces or symbols
• Using unclear variable names
How to Avoid
Follow identifier rules
Use meaningful names
Stick to one naming style
C++ Programming

Pro Tips
Use camelCase for variables and functions
Use PascalCase for class names
Avoid single-letter names (except loop counters)
Be consistent throughout the program
Write names that explain purpose, not type
Variables (C++)
C++ Programming

Definition
• A variable is a named memory location used to store data that can
change during program execution.
• Each variable has a data type, name, and value.
C++ Programming

Usage
• Used to store inputs, intermediate results, and outputs.
• Makes programs readable, reusable, and easy to debug.
• Essential for calculations, conditions, and loops.
C++ Programming

Syntax
data_type variable_name;
data_type variable_name = value;
Explanation
• data_type → Type of data (int, float, char, bool, etc.)
• variable_name → Programmer-defined name
• value → Initial value (optional)
Examples
int age;
float salary = 45000.50;
char grade = 'A';
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
• Declare two integers, find their sum and product, and display the
results.
C++ Programming

Common Mistakes
• Using variable without declaring it
Always declare before use
• Using wrong data type
Match type with value
• Starting variable name with a number
Use letters or _ first
C++ Programming

Pro Tips
• Use meaningful names (totalMarks instead of tm)
• Follow camelCase for readability
• Initialize variables to avoid garbage values
• Keep variable scope as small as possible
Local and Global Variables in
C++
C++ Programming

Local and Global Variables (C++)


Definition
• Local Variable: A variable declared inside a function or block. It can
be used only within that block.
• Global Variable: A variable declared outside all functions, usually at
the top of the program. It can be accessed by all functions.
C++ Programming

Usage
• Local Variables
• Used for temporary calculations
• Safer and easier to debug
• Preferred in most programs
• Global Variables
• Used when multiple functions need the same data
• Helpful in small programs or shared settings
• Should be used carefully
C++ Programming

Syntax
Local Variable
void functionName() {
int x; // local variable
}
Global Variable
int x; // global variable

void functionName() {
// x can be used here
}
C++ Programming

Key Differences
Feature Local Variable Global Variable
Declared Inside function/block Outside all functions
Scope Only within block Entire program
Lifetime During function execution Entire program run
Safety More safe Risky if misused
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
• Create a global variable count
• Increment it inside a function and display the result
• [Link]
Programs/blob/main/Variables/[Link]
C++ Programming

Common Mistakes
• Using global variable when local is enough
Prefer local variables
• Same name for local and global (confusing)
Use unique, meaningful names
• Forgetting scope rules
Remember: block {} defines scope
C++ Programming

Pro Tips
• Use local variables by default
• Use global variables sparingly
• For same names, local variable gets priority
• Avoid globals in large programs (hard to debug)
Keywords in C++: const and
volatile
C++ Programming

Definition
const is a keyword used to make a variable, object, or value read-
only, meaning its value cannot be changed after initialization.
C++ Programming

Usage (Why & Where)


• To protect data from accidental modification
• To define fixed values like PI, gravity, limits
• To improve program safety and clarity
• Commonly used with:
• Variables
• Function parameters
• Pointers
• Objects
C++ Programming

Syntax
const data_type variable_name = value;
Explanation:
• const → makes the variable unchangeable
• data_type → int, float, double, etc.
• variable_name → identifier
• value → assigned only once
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem:
Declare a constant PI = 3.14 and calculate the area of a circle
for radius = 5.
C++ Programming

Common Mistakes
• Trying to modify a const variable
PI = 3.14159;
• Forgetting to initialize a const variable
• Confusing const int *p vs int * const p
C++ Programming

Pro Tips
• Use const wherever values should not change
• Makes code self-documenting
• Helps compiler catch errors early
C++ Programming

Keyword: volatile
Definition
volatile tells the compiler that a variable’s value can change
unexpectedly, so it should not optimize access to it.
C++ Programming

Usage (Why & Where)


Used when variables can change outside the program’s control, such
as:
• Hardware registers
• Interrupt service routines
• Multi-threading
• Embedded systems
C++ Programming

Syntax
volatile data_type variable_name;
Explanation:
• volatile → value may change anytime
• Compiler always reads from memory, not cache
C++ Programming

Sample Program
C++ Programming

Common Mistakes
• Using volatile instead of const
• Thinking volatile provides thread safety
• Overusing volatile in normal programs
C++ Programming

Pro Tips
• Use volatile only when required
• Mostly used in embedded & low-level programming
• volatile ≠ const (they solve different problems)
C++ Programming

Quick Comparison Slide


Feature const volatile
Value Change Not allowed Can change
Compiler Optimization Allowed Not allowed
Purpose Safety Hardware / external changes
Common Use Constants Sensors, flags
C++ Programming
C++ Programming
C++ Programming
Chapter 3
C++ Programming
C++ Programming

Functions and Classes


Definition
In this chapter, we learn how to use existing (standard) functions
and classes provided by C++, without creating our own yet.
What You Will Learn
• How to declare and call standard functions
• How to use standard classes
• How to include and use standard header files
• How to work with string variables for the first time
Important Note
We will only use built-in functions and classes in this chapter.
User-defined functions and classes will be introduced later.
C++ Programming

What Are Standard Functions?


Definition
A standard function is a predefined function provided by C++ that performs a
specific task.
Usage
Standard functions help us:
• Perform calculations
• Work with characters and strings
• Handle input and output
• Save time and avoid rewriting common logic
Examples of Standard Functions
• sqrt() – square root
• pow() – power
• abs() – absolute value
C++ Programming

Using Standard Functions in C++


Syntax
function_name(arguments);
Explanation
• function_name → name of the standard function
• arguments → values passed to the function
Example
sqrt(25);
This calculates the square root of 25
C++ Programming

Sample Program – Using a Standard Function Program


C++ Programming

What Are Header Files?


Definition
A header file contains declarations of functions and classes.
Usage
To use standard functions or classes, we must include the correct
header file.
Common Header Files
Header File Purpose
<iostream> Input and output
<cmath> Mathematical functions
<string> String class
C++ Programming

What Are Standard Classes?


Definition
A class is a blueprint that defines data and operations together.
Standard Classes
C++ provides ready-made classes such as:
• string
• fstream
• stringstream
Why Use Classes?
• Organize data neatly
• Make programs easier to read
• Provide powerful built-in operations
C++ Programming

The string Class


Definition
string is a standard class used to store and manipulate text.
Usage
Use string when:
• Working with names
• Handling sentences
• Managing text input/output
Header File
#include <string>
C++ Programming

Using string Variables


Syntax
string variable_name;
Example
string name;
Assigning Values
name = "C++ Programming";
C++ Programming

Sample Program – Using string


C++ Programming

Practice Program
Problem
Write a C++ program to:
• Read a string
• Display its length
Hint
Use:
length()
C++ Programming
C++ Programming

Common Mistakes
Mistake 1
Forgetting header files
Always include required headers
Mistake 2
Using string without <string>
Include <string>
Mistake 3
Confusing functions and classes
Functions perform actions, classes store data + actions
C++ Programming

Pro Tips
• Always check which header file a function or class belongs to
• Prefer string over character arrays
• Use standard functions to write shorter and cleaner code
• Read compiler errors carefully—they often point to missing
headers
DECLARING FUNCTIONS
C++ Programming

What Is a Function?
Definition
A function is a named block of code that performs a specific task and can
be reused.
Usage
Functions help to:
• Break a program into smaller parts
• Avoid repeating code
• Improve readability and debugging
Types of Functions
• Standard (Library) functions → already provided by C++
• User-defined functions → written by programmers (later chapters)
C++ Programming

Function Declaration (Prototype)


Definition
A function prototype tells the compiler:
• Function name
• Return type
• Number and type of parameters
Why Declaration Is Needed
• Compiler must know about the function before it is called
• Enables type checking
C++ Programming

Example of a Function Prototype


Syntax
return_type function_name(parameter_list);
Example
int add(int, int);
Explanation
• int → return type
• add → function name
• (int, int) → parameters
No function body here — only declaration
C++ Programming

Mathematical Standard Functions


Definition
C++ provides built-in mathematical functions to perform common
calculations.
Header File
#include <cmath>
C++ Programming

Mathematical Standard Functions – Declarations


• Common Functions
Function Description
sqrt(x) Square root
pow(x,y) x raised to power y
abs(x) Absolute value
ceil(x) Smallest integer ≥ x
floor(x) Largest integer ≤ x
C++ Programming

FUNCTION CALLS
Definition
A function call executes the function by passing required values.
Syntax
function_name(arguments);
Example
sqrt(25);
C++ Programming

Function Call – With Assignment


Example
double result = sqrt(36);
Explanation
• Function executes first
• Returned value is stored in result
C++ Programming

Sample Program – Function Calls


C++ Programming

TYPE void FOR FUNCTIONS


Definition
A function with return type void does not return any value.
Usage
Use void when:
• Function performs an action only
• No result is needed
C++ Programming

Functions Without Return Value


Syntax
void function_name(parameters);
Example
void greet();
C++ Programming

Sample Program – void Function


C++ Programming

Functions Without Arguments


Definition
A function that does not take any input values.
Syntax
return_type function_name();
Example
int getNumber();
C++ Programming

Sample Program – No Arguments


C++ Programming

Usage of rand() and srand()


Definition
• rand() → generates random numbers
• srand() → sets the starting point (seed)
Header File
#include <cstdlib>
#include <ctime>
C++ Programming

Why srand() Is Needed


Explanation
Without srand():
• rand() produces same sequence every time
With srand(time(0)):
• Generates different random values on each run
C++ Programming

Sample Program – rand() and srand()


/*
Program Name : [Link]
Concept : rand and srand
Input : None
Output : Random number
Logic : Seed with current time
*/

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
srand(time(0));
cout << rand();
return 0;
}
C++ Programming

Random Number in a Range


Example
rand() % 10; // Generates 0 to 9
C++ Programming

Common Mistakes
• Forgetting to include <cmath>
• Calling function before declaration
• Expecting value from void function
• Using rand() without srand()
C++ Programming

Common Mistakes
• Always declare functions before main()
• Use void for action-only functions
• Seed random numbers once per program
• Use meaningful function names
HEADER FILES
C++ Programming

Definition:
Definition:
A Header File in C++ is a file that contains declarations of functions,
classes, variables, and macros that can be shared across multiple source
files.
Header files usually have the extension:
.h
or
.hpp
Common examples:
<iostream>
<cmath>
<string>
C++ Programming

Usage
Why Header Files Are Used:
• To use standard library functions
• To use standard classes
• To organize large programs
• To avoid rewriting common code
Where They Are Used:
• Input/Output → <iostream>
• Mathematical functions → <cmath>
• String operations → <string>
• Random numbers → <cstdlib>
Without including the required header file, the compiler does not
recognize the function or class.
C++ Programming

Syntax
Standard Syntax:
#include <header_name>
OR
#include "header_name"
Explanation:
• #include → Preprocessor directive
• < > → Used for standard library header files
• " " → Used for user-defined header files
Example:
#include <iostream> // Standard library
#include "myfile.h" // User-defined file
C++ Programming

Using Header Files


To use features from a header file:
1. Include it at the top of your program
2. Use its functions or classes
Example:
#include <iostream>
using namespace std;

int main() {
cout << "Hello World";
return 0;
}
Here:
• <iostream> defines cout
• Without it → compilation error
C++ Programming

Searching for Header Files


1️⃣ If < > is used
→ Compiler searches in standard system directories
2️⃣ If " " is used
→ Compiler searches:
• Current folder first
• Then system directories
Example:
#include <cmath> // System search path
#include "myfile.h" // Current directory first
C++ Programming

Standard Class Definitions


Some header files define classes, not just functions.
Example:
Header File Class Provided
<string> string
<fstream> ifstream, ofstream
<iostream> cin, cout objects
C++ Programming

Example using string class:


#include <iostream>
#include <string>
using namespace std;

int main() {
string name = "Satya";
cout << name;
return 0;
}
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem:
Write a C++ program that:
• Takes a number from user
• Finds its power (square)
• Displays the result
(Hint: Use <cmath> and pow())
C++ Programming
C++ Programming

Common Mistakes
Forgetting to include required header file
Always check which header defines the function
Using "iostream" instead of <iostream>
Use angle brackets for standard libraries
Misspelling header name
Example: #include <iostrem>
Not using using namespace std; (if required)
Or use std::cout
C++ Programming

Pro Tips
Always include only required headers
(Improves compilation speed)
Prefer <cmath> instead of old C header <math.h>
Keep all #include statements at top
For large projects, create custom header files for reusable code
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
C++ Programming
Chapter 4 Input and Output
with Streams
C++ Programming
C++ Programming

Definition
A stream in C++ is a flow of data between a program and an
input/output device.
• Input Stream → Data flows into the program (keyboard, file).
• Output Stream → Data flows out of the program (screen, file).
C++ uses the iostream library to handle streams.
C++ Programming

Usage
Streams are used to:
• Accept user input from keyboard.
• Display output on the screen.
• Read data from files.
• Write data to files.
• Handle formatted and unformatted data.
In C++, streams replace traditional C functions like scanf() and
printf() with safer and more flexible alternatives.
C++ Programming

Syntax
1️⃣ Including Stream Library
#include <iostream>
2️⃣ Using Standard Namespace
using namespace std;
C++ Programming

3️⃣ Standard Stream Objects

Stream Purpose
cin Standard input (keyboard)
cout Standard output (screen)
cerr Standard error output
clog Buffered error output
C++ Programming

4️⃣ Basic Stream Operators


• << → Insertion Operator (Output)
• >> → Extraction Operator (Input)
Example:
cout << "Hello";
cin >> x;
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem:
Write a C++ program that takes two numbers from the user and
displays their sum.
C++ Programming
C++ Programming

Common Mistakes
Forgetting #include <iostream>
Always include the header file.
Not using std:: or using namespace std;
Either use std::cout or declare namespace.
Using << instead of >> for input
Remember:
• << → Output
• >> → Input
Forgetting return 0; in main
Always end main properly.
Not giving space between inputs
For multiple inputs, separate values with space or Enter key.
C++ Programming

Streams are type-safe (no format specifiers like %d).


You can chain outputs:
cout << "A = " << a << " B = " << b;
Always prompt the user before taking input.
Use endl to insert newline:
cout << "Hello" << endl;
Prefer streams over C-style I/O in modern C++.
C++ Programming

Concept Summary (Quick Revision Slide)


• Stream = Flow of data
• cin → Input
• cout → Output
• << → Insert data
• >> → Extract data
• Part of <iostream>
FORMATTING IN C++
STREAMS
C++ Programming

Definition
Formatting in C++ means controlling how output appears on the
screen.
It allows us to:
• Set width of output
• Control decimal places
• Align text
• Display numbers in different formats (hex, octal, etc.)
Formatting is done using manipulators from the <iomanip>
library.
C++ Programming

Usage
Formatting is used when:
• Printing tables
• Displaying currency values
• Showing fixed decimal precision
• Aligning output neatly
• Creating professional console output
Very important in:
• Reports
• Billing software
• Data display systems
• Competitive programming output formatting
C++ Programming

Required Header
• #include <iomanip>
C++ Programming

Common Formatting Manipulators


Manipulator Purpose
setw(n) Set width
setprecision(n) Set decimal precision
fixed Fixed decimal format
scientific Scientific notation
left Left alignment
right Right alignment
setfill(ch) Fill empty space with character
showpoint Always show decimal point
showpos Show + sign for positive numbers
hex Hexadecimal output
oct Octal output
C++ Programming

1️⃣ setw() – Set Width


Syntax
setw(width)
• Applies only to next output
• Aligns right by default
C++ Programming
C++ Programming

2️⃣ setprecision() + fixed


Syntax
setprecision(n)
fixed
• Without fixed → total significant digits
• With fixed → digits after decimal
C++ Programming
C++ Programming

Left and Right Alignment


C++ Programming
C++ Programming

setfill()
In C++, setfill is used to specify the character used to fill empty
spaces when formatting output with setw().
It works with the <iomanip> library.
C++ Programming

Syntax
#include <iomanip>

std::cout << std::setfill(ch);


• ch → the character used for filling (like '*', '0', '-', etc.)
C++ Programming

Important Points
• setfill() alone does nothing.
• It works together with setw().
• setw(n) sets the total width of output.
• If the value printed is smaller than n, remaining spaces are filled
using setfill().
C++ Programming

Example 1: Default Behavior (Without setfill)


#include <iostream>
#include <iomanip>
using namespace std;

int main() {
cout << setw(5) << 25;
}
Output:
25
(Default fill character is space)
C++ Programming

Example 2: Using setfill


#include <iostream>
#include <iomanip>
using namespace std;

int main() {
cout << setfill('*') << setw(5) << 25;
}
Output:
***25
Now * fills the empty spaces instead of space.
C++ Programming

Example 3: Formatting Numbers (Zero Padding)


#include <iostream>
#include <iomanip>
using namespace std;

int main() {
cout << setfill('0') << setw(5) << 42;
}
Output:
00042
C++ Programming

This is commonly used for:


• Invoice numbers
• ID numbers
• Formatting dates
C++ Programming

Alignment with setfill


You can combine it with:
• left
• right
• internal
Example:
cout << left << setfill('-') << setw(6) << 12;
Output:
12----
C++ Programming

Key Notes
setfill() remains active until changed
setw() works only for the next output
Must include <iomanip>
C++ Programming

Number Base Formatting in C++


C++ allows you to display integers in different number bases using
stream manipulators from <iostream> and <iomanip>.
You can print numbers in:
• Decimal (Base 10)
• Octal (Base 8)
• Hexadecimal (Base 16)
C++ Programming

1️⃣ Decimal (Default)


#include <iostream>
using namespace std;

int main() {
int n = 100;
cout << dec << n;
}
Output:
100
dec is the default format.
C++ Programming

2️⃣ Octal (Base 8)


#include <iostream>
using namespace std;
int main() {
int n = 100;
cout << oct << n;
}
Output:
144
Explanation:
100 (base 10) = 144 (base 8)
C++ Programming

3️⃣ Hexadecimal (Base 16)


#include <iostream>
using namespace std;
int main() {
int n = 100;
cout << hex << n;
}
Output:
64
Explanation:
100 (base 10) = 64 (base 16)
C++ Programming

Uppercase Hexadecimal
cout << uppercase << hex << 255;
Output:
FF
Without uppercase:
ff
C++ Programming

Practice Program
Problem:
Create a formatted bill that shows:
• Item name
• Quantity
• Price (2 decimal places)
• Total aligned properly
C++ Programming
C++ Programming

Common Mistakes
Forgetting #include <iomanip>
Always include it for formatting.
Thinking setw() applies permanently
It applies only to the next output.
Using setprecision() without fixed
Understand the difference clearly.
Not resetting format after hex or oct
Use dec to return to decimal.
C++ Programming

Pro Tips
Use formatting for clean tables.
Always combine fixed with setprecision for money
values.
Use setfill() for decorative borders.
Reset number base using:
cout << dec;
Formatting makes your programs look professional.
C++ Programming

Quick Summary Slide


• Formatting controls output appearance.
• <iomanip> is required.
• setw() → Width
• setprecision() → Decimal control
• fixed → Fixed decimal
• left / right → Alignment
• hex, oct, dec → Number systems
FORMATTED INPUT
C++ Programming

Definition
Formatted Input means reading data from the input stream (cin) in
a structured and type-safe manner using formatting rules.
C++ automatically converts input data to the correct data type
using the extraction operator (>>).
C++ Programming

Usage
Formatted input is used when:
• Taking integers, floats, characters, strings
• Reading multiple values at once
• Skipping whitespace automatically
• Ensuring correct type conversion
It is safer and cleaner than C-style scanf().
C++ Programming

Syntax
cin >> variable;
Explanation:
• cin → Standard input stream
• >> → Extraction operator
• variable → Variable where input is stored
Multiple inputs:
cin >> a >> b >> c;
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem:
Accept student name and marks, then display them.
C++ Programming
C++ Programming

Common Mistakes
Entering characters instead of numbers
Causes cin to fail.
Not clearing error state
Use [Link]() and [Link]() if needed.

Pro Tips
Always validate numeric input in real applications.
Use setprecision() to format numeric output.
C++ Programming

UNFORMATTED INPUT / OUTPUT


Definition
Unformatted I/O reads and writes data exactly as it is, without
automatic formatting or skipping rules.
Used when precise control is required.
C++ Programming

Common Unformatted Functions


Input:
• [Link]()
• [Link]()
• [Link]()
Output:
• [Link]()
C++ Programming

1️⃣ [Link]()
[Link]() in C++
[Link]() is used to read a single character from the input stream
(std::cin).
It is defined in the <iostream> library.
C++ Programming

1️⃣ Basic Syntax


[Link]();
OR
char ch;
[Link](ch);
C++ Programming

What Does It Do?


• Reads one character at a time
• Reads whitespace characters (space, tab, newline)
• Does not skip whitespace (unlike cin >> ch)
C++ Programming

Example 1: Reading a Character


#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character: ";
[Link](ch);
cout << "You entered: " << ch;
return 0;
}
Input:
A
Output:
You entered: A
C++ Programming

Example 2: Difference Between cin >> ch and [Link](ch)


char ch;
cin >> ch; // Skips whitespace
[Link](ch); // Reads whitespace
If input is:
A
• cin >> ch → Reads A
• [Link](ch) → Reads the space ' '
C++ Programming

Example 3: Reading a Full Line


char name[50];
[Link](name, 50);
This:
• Reads up to 49 characters
• Stops at newline
• Adds null character \0
C++ Programming

2️⃣ [Link]()
[Link]() in C++
[Link]() is used to read an entire line of text (including
spaces) from the input stream.
It is part of the <iostream> library.
C++ Programming

Basic Syntax
[Link](array_name, size);
OR
[Link](array_name, size, delimiter);
C++ Programming

How It Works
• Reads characters until:
• size - 1 characters are read
• OR newline (\n) is found
• OR specified delimiter is found
• Automatically adds null character (\0)
• Removes newline from buffer
C++ Programming

Example 1: Reading Full Name


#include <iostream>
using namespace std;
int main() {
char name[50];
cout << "Enter your full name: ";
[Link](name, 50);
cout << "Hello " << name;
return 0;
}
Input:
Satya Narayana
Output:
Hello Satya Narayana
Unlike cin >> name, this reads spaces.
C++ Programming

Example 2: Using Delimiter


char text[100];
[Link](text, 100, '#');
If input:
Hello World#Programming
Output stored:
Hello World
C++ Programming

• Important Difference: [Link]() vs [Link]()

Feature [Link]() [Link]()


Reads single character
Reads full line (needs array version)
Stops at newline Yes Yes
Removes newline No Yes
C++ Programming

Very Important (Common Exam Question)


Problem:
int age;
char name[50];

cin >> age;


[Link](name, 50); // Skips input!
Why?
Because after cin >> age, the newline (\n) remains in the buffer.
So getline() reads that leftover newline immediately.
C++ Programming

Solution:
cin >> age;
[Link](); // Clear buffer
[Link](name, 50);
OR
cin >> age;
[Link](1000, '\n');
[Link](name, 50);
C++ Programming

When to Use [Link]()


Reading full names
Reading addresses
Reading sentences
Any input containing spaces
C++ Programming

Modern C++ Alternative (Recommended)


Instead of character arrays:
#include <string>

string name;
getline(cin, name);
More flexible and safer.
C++ Programming

Practice Program
Problem:
Read a full name including spaces and print each character on a new
line.
Possible Idea:
Use [Link]() and loop through characters.
C++ Programming

Common Mistakes
Mixing cin >> and getline() without clearing buffer
Use [Link]() before getline().
Forgetting array size in getline()
Always specify maximum size.
C++ Programming

Pro Tips
Use getline() for full sentences.
Use unformatted I/O when exact character reading is required.
Combine formatted and unformatted carefully.
Chapter 5 Operators for
Fundamental Types 81
C++ Programming
C++ Programming
C++ Programming

Definition
Binary Arithmetic Operators are operators that perform
mathematical operations on two operands (values/variables).
In C++, these operators are used to perform basic mathematical
calculations such as addition, subtraction, multiplication, division,
and modulus.
C++ Programming

Usage
These operators are used:
• To perform mathematical calculations
• In expressions and formulas
• In scientific computations
• In financial applications
• In loop counters and increment logic
• In competitive programming and problem solving
They are fundamental in almost every C++ program.
C++ Programming

Types of Binary Arithmetic Operators

Operator Meaning Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b
C++ Programming

Syntax
operand1 operator operand2;
Explanation:
• operand1 → First value (variable/constant)
• operator → Arithmetic operator (+, -, *, /, %)
• operand2 → Second value
• The result is returned as a value
Example:
int result = a + b;
C++ Programming

Note: Integer division gives only the quotient (10 / 3 = 3)


C++ Programming

Practice Program
Problem:
Write a program to:
• Take two integers from the user
• Print their:
• Sum
• Difference
• Product
• Quotient
• Remainder
C++ Programming
C++ Programming

Common Mistakes
Dividing by zero
Always check if denominator is 0
Using % with float values
% works only with integers
Expecting decimal output from integer division
Use double or float if decimal result is required
Example:
double result = 10.0 / 3;
C++ Programming

Pro Tips
Use parentheses to control order of operations
int result = (a + b) * c;
Remember operator precedence:
1.*, /, %
2.+, -
Use double when accuracy is important
Avoid unnecessary calculations — store intermediate results if
reused
Unary Arithmetic Operators 84
C++ Programming

Definition
Unary Arithmetic Operators are operators that work on only one
operand (one variable).
They are mainly used to:
• Increase a value
• Decrease a value
• Change the sign of a number
In C++, the most common unary arithmetic operators are:
• ++ (Increment)
• -- (Decrement)
• + (Unary plus)
• - (Unary minus)
C++ Programming

Usage
Unary arithmetic operators are used when:
• You want to increase or decrease a variable by 1.
• You want to reverse the sign of a number.
• You are writing loops (for, while).
• You are counting iterations.
Very common in:
• Counters
• Loop control variables
• Mathematical operations
C++ Programming

Syntax
1️⃣ Increment Operator (++)
++variable; // Pre-increment
variable++; // Post-increment
Increases value by 1.
Increment Operator ( ++ )
in C++
C++ Programming

Increment Operator ( ++ ) in C++


The increment operator (++) is a unary arithmetic operator used to
increase the value of a variable by 1.
C++ Programming

1️⃣ Types of Increment Operator


There are two types:
1. Pre-Increment (++a)
Value is increased before it is used.
int a = 5;
int b = ++a;

cout << "a = " << a << endl; // 6


cout << "b = " << b << endl; // 6
Steps:
• a becomes 6 first
• Then assigned to b
C++ Programming

2. Post-Increment (a++)
Value is used first, then increased.
int a = 5;
int b = a++;

cout << "a = " << a << endl; // 6


cout << "b = " << b << endl; // 5
Steps:
• Old value (5) assigned to b
• Then a becomes 6
C++ Programming

• 2️⃣ Comparison Table


When Increment
Type Syntax Final Value Stored
Happens
Pre-increment ++a Before use New value
Post-increment a++ After use Old value
C++ Programming

3️⃣ Example in Loop


for(int i = 0; i < 5; i++)
{
cout << i << " ";
}
Output:
0 1 2 3 4
Here:
• i++ increases i after each iteration.
C++ Programming

4️⃣ Important Notes


Works only with variables (not constants)
int a = 5;
++a; // valid
// ++5; // invalid
Avoid using multiple increments in one expression:
int x = 5;
int y = x++ + ++x; // Confusing & unsafe
C++ Programming

Simple Concept Rule


• Pre (++a) → Change first, then use
• Post (a++) → Use first, then change
2️⃣ Decrement Operator (--)
C++ Programming

2️⃣ Decrement Operator (--)


--variable; // Pre-decrement
variable--; // Post-decrement
Decreases value by 1.
C++ Programming

Decrement Operator (--) in C++


The decrement operator (--) is a unary arithmetic operator used
to decrease the value of a variable by 1.
C++ Programming

1️⃣ Types of Decrement Operator


There are two types:

1. Pre-Decrement (--a)
The value is decreased before it is used.
int a = 5;
int b = --a;
cout << "a = " << a << endl; // 4
cout << "b = " << b << endl; // 4
Steps:
• a becomes 4 first
• Then assigned to b
C++ Programming

2. Post-Decrement (a--)
The value is used first, then decreased.
int a = 5;
int b = a--;

cout << "a = " << a << endl; // 4


cout << "b = " << b << endl; // 5
Steps:
• Old value (5) assigned to b
• Then a becomes 4
C++ Programming

• 2️⃣ Comparison Table


When Decrement
Type Syntax Final Value Stored
Happens
Pre-decrement --a Before use New value
Post-decrement a-- After use Old value
C++ Programming

3️⃣ Example in Loop


for(int i = 5; i > 0; i--)
{
cout << i << " ";
}
Output:
5 4 3 2 1
Here:
• i-- decreases i after each iteration.
C++ Programming

4️⃣ Important Notes


Works only with variables
int a = 5;
--a; // valid
// --5; // invalid
Avoid confusing expressions:
int x = 5;
int y = x-- + --x; // Not recommended
C++ Programming

Easy Memory Rule


• Pre (--a) → Change first, then use
• Post (a--) → Use first, then change
3️⃣ Unary Minus (-)
C++ Programming

3️⃣ Unary Minus (-)


-variable;
Changes the sign of the value.
C++ Programming

Unary Minus Operator (-) in C++


The Unary Minus (-) operator is a unary arithmetic operator that
changes the sign of a number.
It converts:
• Positive → Negative
• Negative → Positive
C++ Programming

1️⃣ Basic Example


int a = 5;
int b = -a;

cout << "a = " << a << endl; // 5


cout << "b = " << b << endl; // -5
Here:
• a remains 5
• -a produces -5
It does not change a unless assigned back.
C++ Programming

2️⃣ Changing the Variable Value


int a = 5;
a = -a;

cout << a; // -5
Now the value is actually changed.
C++ Programming

3️⃣ With Negative Numbers


int x = -10;
int y = -x;

cout << y; // 10
Minus of minus becomes plus.
C++ Programming

• 4️⃣ Unary Minus vs Subtraction


Unary Minus Binary Subtraction
Uses one operand Uses two operands
Changes sign Finds difference
Example: -a Example: a - b
C++ Programming

Example:
int a = 5, b = 3;

cout << -a << endl; // -5 (Unary minus)


cout << a - b << endl; // 2 (Subtraction)
C++ Programming

5️⃣ Important Notes


Works with numeric types (int, float, double)
Does not permanently change value unless assigned
Very useful in mathematical calculations
C++ Programming

Simple Concept Rule


Unary minus simply means:
“Give me the opposite sign of this number.”
4️⃣ Unary Plus (+)
C++ Programming

Unary Plus Operator (+) in C++


The Unary Plus (+) is a unary arithmetic operator that indicates a
positive value.
It does not change the value of a variable.
It simply returns the value as it is.
C++ Programming

1️⃣ Basic Example


int a = 5;
int b = +a;

cout << "a = " << a << endl; // 5


cout << "b = " << b << endl; // 5
Here:
• +a returns the same value (5)
• No change happens
C++ Programming

2️⃣ With Negative Numbers


int x = -10;
int y = +x;

cout << y; // -10


Unary plus does not remove the negative sign
It simply keeps the value unchanged
C++ Programming

3️⃣ Why Does Unary Plus Exist?


It is mostly used:
• For symmetry with unary minus
• In generic programming
• When explicitly showing a number is positive
Example:
int a = 5;
cout << +a << endl; // 5
C++ Programming

• 4️⃣ Unary Plus vs Binary Addition

Unary Plus Binary Addition


Uses one operand Uses two operands
No change in value Adds two values
Example: +a Example: a + b
C++ Programming

Example:
int a = 5, b = 3;

cout << +a << endl; // 5


cout << a + b << endl; // 8
C++ Programming

5️⃣ Important Notes


Works with numeric data types
Does not modify the variable
Rarely used explicitly in beginner programs
C++ Programming

Simple Concept Rule


Unary plus simply means:
“Keep the value exactly as it is.”
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
Write a program to:
• Take an integer input
• Decrease it by 1 using decrement operator
• Print the updated value
C++ Programming
C++ Programming

Common Mistakes
Confusing pre and post increment
Remember:
• ++a → change first
• a++ → use first
Using increment on constants
5++; // ERROR
Only variables can be incremented.
Overusing increment inside complex expressions
int x = a++ + ++a; // Confusing and risky
Avoid complex increments in one statement.
C++ Programming

Pro Tips
Use pre-increment (++a) when possible — slightly more
efficient in some cases.
Avoid writing too many increments in one line.
Use increment mainly in loops.
Keep expressions simple and readable.
Assignment Operators in
C++
C++ Programming

Definition
Assignment operators are used to assign values to variables.
They store the result of an expression into a variable.
The most common assignment operator is:
=
C++ also provides compound assignment operators that combine
arithmetic and assignment in one step.
C++ Programming

Usage
Assignment operators are used when:
• Initializing variables
• Updating values
• Performing calculations and storing results
• Writing loops and counters
• Modifying existing variable values
Very common in:
• Mathematical programs
• Counters
• Accumulators
• Financial calculations
C++ Programming

Types of Assignment Operators


Operator Meaning Example Equivalent To
= Assign a = 5 Store 5 in a
+= Add and assign a += 3 a = a + 3
-= Subtract and assign a -= 2 a = a - 2
*= Multiply and assign a *= 4 a = a * 4
/= Divide and assign a /= 2 a = a / 2
%= Modulus and assign a %= 3 a = a % 3
C++ Programming

Syntax
1️⃣ Simple Assignment
variable = expression;
Explanation:
• Left side → variable (must be declared)
• Right side → value or expression
• = → assigns right value to left variable
C++ Programming

2️⃣ Compound Assignment


variable += value;
variable -= value;
variable *= value;
variable /= value;
variable %= value;
These reduce code length and improve readability.
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
Write a program that:
• Takes two numbers as input
• Adds the second number to the first using +=
• Multiplies the result by 2 using *=
• Displays the final value
C++ Programming
C++ Programming

Common Mistakes
Confusing = with ==
• = → Assignment
• == → Comparison
Writing expression on left side
5 = a; // ERROR
Left side must be a variable.
Forgetting variable declaration
a = 10; // ERROR if a not declared
C++ Programming

Pro Tips
Use compound operators to make code shorter and cleaner.
Always initialize variables before using them.
Keep expressions simple and readable.
Remember: Assignment operator returns a value, so chaining
is possible:
int a, b, c;
a = b = c = 5;
All three variables become 5.
Relational Operators in
C++
C++ Programming

Definition
Relational operators are used to compare two values or expressions.
They return a boolean result:
• true (1)
• false (0)
These operators are mainly used in:
• Decision making
• Conditions
• Loops
• Comparisons
C++ Programming

Usage
Relational operators are used when:
• Checking if two values are equal
• Comparing numbers (greater/smaller)
• Writing if conditions
• Writing while and for loops
• Validating user input
They help the program make decisions.
C++ Programming

• List of Relational Operators


Operator Meaning Example Result
== Equal to a == b true if equal
!= Not equal to a != b true if not equal
> Greater than a > b true if a is greater
< Less than a < b true if a is smaller
>= Greater than or equal a >= b true if greater or equal
<= Less than or equal a <= b true if smaller or equal
C++ Programming

Syntax
expression1 relational_operator expression2;
Example:
a > b
x == y
num != 0
Explanation:
• Left side → first value
• Operator → comparison
• Right side → second value
• Result → true (1) or false (0)
C++ Programming

Sample Program
C++ Programming

Practice Program
Problem
Write a program that:
• Takes a student’s marks as input
• Checks whether the student passed (marks ≥ 40)
• Prints "Pass" or "Fail"
C++ Programming
C++ Programming

Common Mistakes
Confusing = and ==
if (a = 5) // WRONG
Correct:
if (a == 5)
C++ Programming

Forgetting parentheses in conditions


Always write:
if (a > b)

Comparing floating-point numbers directly


if (x == 0.1) // May cause precision issues
Use tolerance for decimals.
C++ Programming

Pro Tips
Use parentheses for clarity:
cout << (a > b);
Remember:
• Relational operators return boolean values.
• Boolean values are printed as 0 or 1 (unless formatted).
Combine with logical operators for complex conditions.
Logical Operators in C++
C++ Programming

Definition
Logical operators are used to combine two or more conditions.
They return a boolean result:
• true (1)
• false (0)
Logical operators are mainly used in:
• if statements
• while loops
• Decision making
• Validating multiple conditions
C++ Programming

Usage
Logical operators are used when:
• You want multiple conditions to be checked together
• You want at least one condition to be true
• You want to reverse a condition
Example situations:
• Checking age AND eligibility
• Checking username OR email match
• Checking if a number is NOT negative
C++ Programming

Types of Logical Operators


Operator Meaning Example Condition
&& Logical AND a > 0 && b > 0 Both must be true
|| ` Logical OR
! Logical NOT !(a > 0) Reverses result
C++ Programming

Syntax
1️⃣ Logical AND (&&)
condition1 && condition2
True only if both conditions are true.
C++ Programming

2️⃣ Logical OR (||)


condition1 || condition2
True if at least one condition is true.
C++ Programming

3️⃣ Logical NOT (!)


!condition
Reverses the result.
C++ Programming

Truth Table (Important for Exams)


• AND (&&)
A B A && B
0 0 0
0 1 0
1 0 0
1 1 1
C++ Programming

• OR (||)
A B A || B
0 0 0
0 1 1
1 0 1
1 1 1
C++ Programming

• NOT (!)
A !A
0 1
1 0
C++ Programming

Sample Program
C++ Programming

Example of OR Operator
if (marks < 40 || attendance < 75)
cout << "Not Allowed for Exam";
Student is not allowed if any one condition fails.
C++ Programming

Example of NOT Operator


if (!(age >= 18))
cout << "Minor";
If age is NOT greater than or equal to 18.
C++ Programming

Practice Program
Problem
Write a program that:
• Takes a number as input
• Checks whether it is between 10 and 50 (inclusive)
• Prints "Valid" if true, otherwise "Invalid"
C++ Programming
C++ Programming

Common Mistakes
Confusing & with &&
• && → Logical AND
• & → Bitwise AND
Forgetting parentheses in complex conditions
Correct:
if ((a > b) && (b > c))
Using assignment inside condition
if (a = 5) // WRONG
Use:
if (a == 5)
C++ Programming

Pro Tips
Use logical operators to make conditions clean and readable.
Combine relational + logical operators carefully.
Use parentheses for clarity in complex expressions.
Remember short-circuit behavior:
• In &&, if first condition is false → second is NOT checked.
• In ||, if first condition is true → second is NOT checked.
Exercises – Operators in C++
( Covers: Unary, Assignment,
Relational, Logical Operators )
C++ Programming

Section 1: Basic Concept Check (Very Easy)


1️⃣ Identify the Output
int a = 5;
cout << ++a;
What will be printed?
C++ Programming

2️⃣ Identify the Output


int a = 5;
cout << a++;
What will be printed?
C++ Programming

3️⃣ True or False?


int a = 10;
a += 5;
After execution, value of a is 15.
C++ Programming

4️⃣ What is the result?


cout << (10 > 5);
C++ Programming

5️⃣ What is the result?


cout << (10 < 5);
C++ Programming

Section 2: Output Prediction (Medium Level)


6️⃣
int x = 10;
int y = 5;
cout << (x > y && y > 0);
C++ Programming

7️⃣
int a = 4;
int b = 4;
cout << (a == b || b > 10);
C++ Programming

8️⃣
int p = 3;
cout << !(p > 2);
C++ Programming

int a = 5;
int b = a++;
cout << a << " " << b;
C++ Programming

Section 3: Debug the Code


1️⃣ Find the error
if (a = 5)
cout << "Hello";
C++ Programming

2️⃣ Find the error


int x;
x += 5;
C++ Programming

3️⃣ Find the mistake


if (x > 5 && < 10)
cout << "Valid";
C++ Programming

Section 4: Programming Practice (Important for Exams)

14️⃣ Even or Odd


Write a program to check whether a number is even or odd using
relational and logical operators.
C++ Programming

15️⃣ Largest of Two Numbers


Write a program to input two numbers and print the greater one.
C++ Programming

6️⃣ Pass with Distinction


Write a program to:
• Input marks
• Print:
• "Distinction" if marks ≥ 75
• "Pass" if marks ≥ 40
• "Fail" otherwise
C++ Programming

17️⃣ Valid Login


Write a program that:
• Accepts a PIN number
• Prints "Access Granted" if PIN is 1234
• Otherwise prints "Access Denied"
C++ Programming

18️⃣ Number in Range


Write a program to check whether a number lies between 1 and
100.
C++ Programming

• Section 5: Challenge Questions


19️⃣ Complex Expression
Predict the output:
int a = 2, b = 3;
cout << (a > 1 && b < 5 || a == 0);
Chapter 6 Control Flow 95
Control Flow in C++
C++ Programming
C++ Programming

Definition
Control Flow refers to the order in which program statements are
executed.
By default, a C++ program executes statements sequentially from
top to bottom.
Control flow statements allow programmers to change the normal
execution order based on conditions, repetitions, or jumps.
In simple terms:
Control flow decides which statement runs next in a program.
C++ Programming
C++ Programming

Usage
Control flow is used when a program must:
• Make decisions (e.g., check if a number is positive or negative)
• Repeat tasks multiple times (e.g., print numbers 1–10)
• Skip or redirect execution based on conditions
• Implement real-world logic such as grading systems, login
validation, or menu selection
C++ Programming
Control flow structures are mainly divided into three categories:
[Link] Statements (Decision Making)
[Link]
[Link]-else
[Link] if
[Link]
[Link] Statements (Loops)
[Link]
[Link]
[Link]-while
[Link] Statements
[Link]
[Link]
[Link]
[Link]
C++ Programming

Syntax
1. Sequential Flow (Default Execution)
statement1;
statement2;
statement3;
Execution moves line by line from top to bottom.
C++ Programming

2. Selection Control (Example: if)


if(condition)
{
statements;
}
Explanation
Part Meaning
if decision keyword
condition logical test (true/false)
statements executed only if condition is true
C++ Programming

3. Iteration Control (Example: while)


while(condition)
{
statements;
}
Explanation

Part Meaning
while loop keyword
condition loop continues while condition is true
statements repeated execution
The while Statement (C++)
C++ Programming

The while Statement (C++)


1. Definition
The while statement is a looping control structure that repeatedly
executes a block of code as long as a specified condition (expression)
remains true.
• The condition is evaluated before each iteration.
• If the condition becomes false, the loop stops and the program
continues with the next statement.
Key idea:
Check condition → If true → Execute statements →
Check again
So the loop may execute 0 or more times.
C++ Programming
2. Usage
The while loop is used when:
• The number of repetitions is not known in advance
• Input is processed until a condition changes
• Data is read until the end of input
Typical real-world examples:
• Reading numbers until the user stops
• Processing file data until EOF
• Repeating menu operations until the user exits
Example scenarios:
• Calculating the average of numbers
• Validating input
• Game loops
C++ Programming
3. Syntax
while (expression)
statement;
Explanation
while
• Keyword that starts the loop.
expression
• A condition that evaluates to true (non-zero) or false (0).
statement
• The loop body executed repeatedly while the condition is true.
With Multiple Statements
while (expression)
{
statement1;
statement2;
statement3;
}
Curly braces { } are used when the loop body contains multiple statements.
C++ Programming
C++ Programming

6. Common Mistakes
1. Infinite Loop
Forgetting to update the loop variable.
Incorrect
int i = 1;
while(i <= 10)
{
cout << i;
}
This runs forever.
Correct
i++;
C++ Programming

2. Missing Braces
while(i < 5)
cout << i;
i++;
Only the first statement belongs to the loop.
Correct version:
while(i < 5)
{
cout << i;
i++;
}
C++ Programming

3. Wrong Condition
while(i = 5) // assignment instead of
comparison
Correct:
while(i == 5)
C++ Programming

7. Pro Tips
1. Always Update Loop Variables
Ensure variables in the condition change inside the loop.

2. Use while(true) for Infinite Loops


while(true)
{
// program logic
}
Exit using break.
C++ Programming

3. Use while When Iterations Are Unknown


Good example:
while(cin >> number)
Processing input until user stops.

4. Prefer Indentation
Readable code example:
while(condition)
{
statements;
}
Mini-Projects
C++ Programming

1. Number Guessing Game


Concept
Use a while loop to repeatedly ask the user to guess a number
until they guess correctly.
Learning Focus
• while loop condition
• user input
• comparison
C++ Programming
C++ Programming

2. Multiplication Table Generator


Generate multiplication tables using a loop.
C++ Programming
C++ Programming

3. Password Authentication System Concept


Allow only 3 login attempts.
Learning Focus
• counter
• security logic
• while condition
C++ Programming
C++ Programming

4. ATM Simulation (Medium → Hard)


Concept
Simulate simple ATM operations.
Menu repeats until the user exits.
Features
• Check balance
• Deposit
• Withdraw
• Exit
C++ Programming
The for Statement (C++)
C++ Programming

Definition
The for statement is a loop control structure used to execute a
block of code a specific number of times.
It is commonly used when the number of iterations is known in
advance.
The for loop combines initialization, condition checking, and
updating in a single statement, making it compact and easy to
read.
C++ Programming

Usage
The for loop is used when:
• The number of repetitions is known beforehand.
• You want to iterate through numbers, arrays, or sequences.
• Tasks require count-controlled repetition.
Typical applications:
• Printing numbers from 1 to 10
• Iterating through arrays
• Generating multiplication tables
• Running simulations or repeated calculations
C++ Programming

Syntax
for(initialization; condition; update)
{
// statements
}
Part Meaning
Declares and initializes the loop variable. Executed
Initialization
once at the beginning.
Checked before every iteration. If true, the loop
Condition
continues.
Changes the loop variable after each iteration
Update
(increment/decrement).
Loop Body The statements executed repeatedly.
C++ Programming

Flow of Execution
[Link] executes.
[Link] is checked.
[Link] true, loop body runs.
[Link] statement executes.
[Link] is checked again.
[Link] stops when condition becomes false.
C++ Programming

Sample Program
Program Statement
Print numbers from 1 to 5 using a for loop.
C++ Programming
C++ Programming

Practice Program
Problem
Write a program that prints the multiplication table of a number
entered by the user (1–10).
C++ Programming
C++ Programming

Common Mistakes
1️⃣ Missing Semicolon in Loop Header
Incorrect
for(int i = 0 i < 5; i++)
Correct
for(int i = 0; i < 5; i++)
C++ Programming

2️⃣ Infinite Loop


If update statement is missing.

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

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


C++ Programming

3️⃣ Wrong Condition

for(int i = 1; i >= 10; i++)


Loop never runs.
C++ Programming

4️⃣ Changing Loop Variable Inside Body


Avoid modifying loop counter inside the loop body unnecessarily.
C++ Programming

Pro Tips
Use i++ for counting loops (most common).
Use -- for reverse loops.
Example:
for(int i = 10; i >= 1; i--)
C++ Programming

You can declare loop variables inside the loop.


for(int i = 0; i < 10; i++)
The variable exists only inside the loop.

Multiple variables can be used.


for(int i=0, j=10; i<j; i++, j--)
C++ Programming

For loops are ideal for:


• Counting
• Iterating arrays
• Generating patterns
The for Statement
C++ Programming
Definition
The for statement is a loop control structure used to repeat a block of
code a specific number of times.
It is most useful when the number of iterations is known in advance.
A for loop combines:
[Link]
[Link] checking
[Link] of loop variable
in a single statement, making it compact and easy to read.
C++ provides three types of loops:
• while
• do-while
• for
The for loop is ideal for counter-controlled loops.
C++ Programming

Usage
The for loop is commonly used when:
• The number of repetitions is predetermined
• Iterating through arrays or lists
• Generating tables or sequences
• Performing mathematical computations
• Controlling loops with a counter variable
Example real uses:
• Printing numbers 1 to 100
• Multiplication tables
• Iterating through array elements
• Processing repeated calculations
C++ Programming
Syntax
for(initialization; condition; update)
{
// loop body
}
Explanation
1. Initialization
int i = 0;
• Declares and initializes the loop variable.
• Executed only once before the loop starts.
2. Condition
i < 10
• Checked before every iteration.
• If true → loop continues
• If false → loop stops
3. Update
i++
• Executed after each iteration
• Updates the loop variable.
Flow of Execution
Initialization → Condition → Loop Body → Update
↑ ↓
←────────────── Repeat ──────────────
C++ Programming

• Sample Program
C++ Programming

Practice Program
Problem
Write a C++ program that prints the multiplication table of a
number entered by the user.
C++ Programming
C++ Programming

Common Mistakes
1. Missing Semicolons
Incorrect:
for(int i=0 i<10 i++)
Correct:
for(int i=0; i<10; i++)
C++ Programming

2. Infinite Loop
for(int i=0; i<10;)
Update expression missing.

3. Wrong Condition
for(int i=10; i<0; i++)
Loop never runs.
C++ Programming

4. Using = instead of ==
for(int i=0; i=10; i++)
This is an assignment, not a comparison.
C++ Programming

Pro Tips
Keep the loop variable inside the for statement to limit scope.
for(int i = 0; i < 10; i++)
Use ++i instead of i++ when possible (slightly more efficient in
some cases).
Use braces {} even for single statements for better readability.
Use meaningful variable names:
for(int student = 1; student <= totalStudents;
student++)
A for loop can also omit parts:
for( ; ; ) // infinite loop
C++ Programming

1. Sum of First N Natural Numbers


Problem
Write a program to calculate the sum of first N natural numbers.
Example
Input:
N = 5

Output:
Sum = 15
Hint
Use a loop from 1 → N and accumulate the sum.
C++ Programming
Problem
Write a program to calculate the sum of the first N natural numbers.
Example
Input:
N=5
Output:
Sum = 15

Concept
Natural numbers start from 1.
So if 𝑁 = 5:
1 + 2 + 3 + 4 + 5 = 15
We can calculate this using a loop that keeps adding numbers from 1 to N.
C++ Programming

Algorithm
[Link] the value of N.
[Link] a variable sum = 0.
[Link] a loop from 1 to N.
[Link] each number to sum.
[Link] the final sum.
C++ Programming
C++ Program
#include <iostream>
using namespace std;
int main() {
int N;
int sum = 0;
cout << "Enter N: ";
cin >> N;
for(int i = 1; i <= N; i++) {
sum = sum + i;
}
cout << "Sum = " << sum;
return 0;
}
C++ Programming

Time Complexity
𝑂 𝑁
The loop runs N times.

Bonus (Mathematical Formula – Faster Method)


Instead of a loop, we can use the formula:
S = \frac{N(N+1)}{2}
Example for 𝑁 = 5:
5 6
𝑆= = 15
2
Time complexity becomes O(1).
C++ Programming

2. Factorial Calculator
Problem
Write a program to calculate the factorial of a number.
Example
Input:
5

Output:
120
Hint
5! = 5 × 4 × 3 × 2 × 1
Use a loop from 1 → N.
C++ Programming
Problem
Write a program to calculate the factorial of a number.
Example
Input
5
Output
120

Concept
The factorial of a number 𝑁is the product of all positive integers from 1 to N.
𝑁! = 𝑁 × 𝑁 − 1 × 𝑁 − 2 × ⋯ × 1
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
C++ Programming

Algorithm
[Link] the number N.
[Link] factorial = 1.
[Link] a loop from 1 to N.
[Link] factorial by the current number.
[Link] the result.
C++ Programming
C++ Program
#include <iostream>
using namespace std;
int main() {
int N;
long long factorial = 1;
cout << "Enter a number: ";
cin >> N;
for(int i = 1; i <= N; i++) {
factorial = factorial * i;
}
cout << "Factorial = " << factorial;
return 0;
}
C++ Programming

Time Complexity
𝑂 𝑁
The loop runs N times.

Important Note
• 0! = 1
• Factorial grows very fast, so large values of N may overflow normal
integer types.
C++ Programming
3. Count Even and Odd Numbers
Problem
Read N numbers and count:
• number of even numbers
• number of odd numbers.
Example
Input numbers:
2 5 7 8 10
Output:
Even = 3
Odd = 2
Hint
Use:
num % 2 == 0
C++ Programming

Concept
A number is:
• Even if it is divisible by 2
• Odd if it is not divisible by 2
Condition used in programming:
num % 2 == 0 → Even number
num % 2 != 0 → Odd number
The operator % (modulus) gives the remainder after division.
C++ Programming

• Example:
Number num % 2 Type
2 0 Even
5 1 Odd
8 0 Even
C++ Programming

Algorithm
[Link] the value N (how many numbers).
[Link]
[Link] = 0
[Link] = 0
[Link] N times.
[Link] each number.
[Link]:
1. If num % 2 == 0 → increase even
2. Else → increase odd
[Link] both counts.
C++ Programming
C++ Program
#include <iostream>
using namespace std;
int main() {
int N, num;
int even = 0, odd = 0;
cout << "Enter how many numbers: ";
cin >> N;
for(int i = 1; i <= N; i++) {
cin >> num;
if(num % 2 == 0)
even++;
else
odd++;
}
cout << "Even = " << even << endl;
cout << "Odd = " << odd << endl;
return 0;
}
C++ Programming

Time Complexity
𝑂 𝑁
The program checks each number once.
C++ Programming

4. Reverse a Number
Problem
Write a program to reverse a number.
Example
Input:
1234
Output:
4321
Hint
Use:
digit = n % 10
n = n / 10
C++ Programming

4. Reverse a Number
Problem
Write a program to reverse a number.
Example
Input:
1234
Output:
4321
Hint
Use:
digit = n % 10
n = n / 10
C++ Programming

4. Reverse a Number
Problem
Write a program to reverse a number.
Example
Input:
1234
Output:
4321
Hint
Use:
digit = n % 10
n = n / 10
C++ Programming

Concept
To reverse a number, repeatedly extract the last digit and build the
reversed number.
Key operations:
digit = n % 10
n = n / 10
Explanation:
• n % 10 → gives the last digit
• n / 10 → removes the last digit
To build the reversed number:
rev = rev * 10 + digit
C++ Programming

Algorithm
[Link] the number n.
[Link] rev = 0.
[Link] n > 0:
1. Extract last digit → digit = n % 10
2. Add it to reverse → rev = rev * 10 + digit
3. Remove last digit → n = n / 10
[Link] rev.
C++ Programming
C++ Programming

Time Complexity
𝑂 𝑑
Where d = number of digits in the number.
The do-while Statement
(C++)
C++ Programming

Definition
The do-while statement is a loop control structure that executes a
block of code at least once, and then repeats the loop as long as the
condition is true.
It is called an exit-controlled loop because the condition is checked
after executing the loop body.
C++ Programming

Usage
The do-while loop is used when:
• The program must execute the loop body at least once.
• The condition should be checked after execution.
• Common situations include:
• Menu-driven programs
• User input validation
• Repeating tasks until the user chooses to stop
Example real-life scenarios:
• ATM menu system
• Game menu
• Asking the user to re-enter valid input
C++ Programming

Syntax
do
{
// statements
} while(condition);
Explanation
Part Meaning
do Starts the loop block
Contains statements
{ }
to execute
Condition checked
while(condition)
after execution
Mandatory semicolon
;
after while
C++ Programming

Execution Flow
[Link] the loop body
[Link] the condition
[Link] true → repeat loop
[Link] false → exit loop
C++ Programming
C++ Programming

Practice Program
Problem
Write a program that asks the user to enter numbers continuously
and calculates the sum.
Stop when the user enters 0.
C++ Programming
C++ Programming

• Common Mistakes
Mistake Explanation
Missing semicolon while(condition); must end with ;
Infinite loop Forgetting to update variables
Wrong condition Condition may never become false
Loop runs at least once even if condition
Not understanding execution
is false
C++ Programming

Example mistake:
do
{
cout << "Hello";
} while(false);
Output still prints Hello once.
C++ Programming

Pro Tips
Use do-while when one execution is guaranteed
Best for menu-driven programs
Example:
do
{
cout << "1. Add\n2. Delete\n3. Exit\n";
cin >> choice;
}
while(choice != 3);
Avoid do-while if the loop may not need to run at all — use
while instead.
Keep the loop body small and readable.
C++ Programming

• Comparison with Other Loops

Loop Type Condition Check Runs at least once


for Before loop No
while Before loop No
do-while After loop Yes
C++ Programming

Practice Program
Problem:
Create a program that keeps asking the user to enter a number
until they enter 0, then display the sum.
C++ Programming
C++ Programming
C++ Programming
C++ Programming
macro
C++ Programming

Macros in C++
Definition:
A macro is a preprocessor directive defined using #define that
replaces text in the program before compilation.
The preprocessor performs text substitution, not calculation.
General Form
#define name substitutetext
Example
#define PI 3.14159
Every occurrence of PI is replaced with 3.14159
C++ Programming
Where Macros are Used
Macros are used for:
• Defining constants
• Creating shortcuts
• Writing inline calculations
• Improving readability
• Avoiding repeated code
• Conditional compilation
Example
Instead of writing:
3.14159 * r * r
We write:
PI * r * r
Much cleaner and easier to modify.
C++ Programming

Syntax of Macro
#define NAME value
Explanation
Part Meaning
#define Preprocessor directive
NAME Macro name
value Replacement text
C++ Programming

Rules
• No semicolon
• No equals sign
• Usually uppercase naming
• Text replacement only
Example
#define MAX 100
C++ Programming

Symbolic Constants using Macros


#define PI 3.1415926536
#define START 0.0
#define END (2.0 * PI)
#define STEP (PI / 8.0)
Features
• Improves readability
• Easy to modify
• Can use previously defined macros
Example
cout << PI;
Output
3.1415926536
C++ Programming

• Sample Program
C++ Programming

Macros with Parameters


Parameterized Macros
Macros can accept arguments.
Syntax
#define MACRO_NAME(parameter) expression
Example
#define SQUARE(a) ((a)*(a))
Usage
int x = 5;
cout << SQUARE(x);
Output
25
C++ Programming

• Sample Program (Parameterized Macro)


C++ Programming
Multi-line Macros
Use \ to continue macro in next line
Example
#define MESSAGE cout << "Hello" << \
endl << "Welcome";
Sample Program
#include <iostream>
using namespace std;
#define HEADER cout << "*****" << \
endl << "MACRO DEMO" << \
endl << "*****" << endl;
int main()
{
HEADER
return 0;
}
C++ Programming

• Macros vs Functions
Feature Macros Functions
Speed Faster Slower
Memory Larger code Smaller
Type checking No Yes
Debugging Hard Easy
Safety Less safe More safe
C++ Programming

Practice Program
Problem
Create macros to:
• Find cube of number
• Find maximum of two numbers
C++ Programming
C++ Programming

Slide 11 — Common Mistakes


Missing brackets
Wrong
#define SQUARE(x) x*x
Correct
#define SQUARE(x) ((x)*(x))
C++ Programming

Using semicolon
Wrong
#define PI 3.14;
Correct
#define PI 3.14
C++ Programming

Side Effects
SQUARE(++x)
Expands to
(++x)*(++x)
x increments twice.
C++ Programming

Pro Tips
Always use parentheses
Use uppercase naming
Avoid complex macros
Prefer inline functions when possible
Keep macros simple
C++ Programming

Macros with Parameters


Definition:
A Macro with parameters is a macro that accepts arguments and
performs text substitution using those arguments.
These macros work similar to inline functions, but they are
expanded before compilation.
C++ Programming

Usage
Why Use Macros with Parameters?
Macros with parameters are used to:
• Avoid repeated code
• Improve readability
• Improve performance (no function call overhead)
• Perform quick calculations
Example
Instead of writing:
a * a
We write:
SQUARE(a)
C++ Programming

Slide 3 — Syntax
Syntax
#define MACRO_NAME(parameter) expression
Example
#define SQUARE(x) ((x)*(x))
• Explanation
Part Meaning
#define Preprocessor directive
SQUARE Macro name
(x) Parameter
((x)*(x)) Expression
C++ Programming

Macro Definition
#define SQUARE(a) ((a)*(a))
Usage
z = SQUARE(x+1);
Expansion
z = ((x+1)*(x+1));
This happens before compilation
C++ Programming

Wrong Macro
#define SQUARE(a) a*a
Usage
SQUARE(x+1)
Expansion
x+1*x+1
Wrong Result!
Correct Macro
#define SQUARE(a) ((a)*(a))
Correct expansion:
((x+1)*(x+1))
C++ Programming

• Sample Program
Working with the #define
Directive
C++ Programming

Slide 1 — Definition
Working with the #define Directive
The #define directive is used to create macros in C++.
It tells the preprocessor to replace a name with a value before
compilation.
The macro definition must appear before it is used in the program.
It is recommended to place all #define statements at the
beginning of the file for easy modification.
C++ Programming
Why Use #define
#define is used to:
• Create symbolic constants
• Define macros
• Improve readability
• Avoid repeated values
• Share macros across multiple files
If the same macros are used in multiple source files, create a header file and
include it in all files.
Example:
header.h
[Link]
[Link]
[Link]
All files include:
#include "header.h"
C++ Programming

Syntax of #define
1. Symbolic Constant
#define name value
Example:
#define PI 3.14159
2. Macro with Parameters
#define name(parameters) expression
Example:
#define SQUARE(x) ((x)*(x))
C++ Programming
Slide 4 — Sample Program
/*
Program Name : define_constant.cpp
Concept : #define directive
Input : radius
Output : Area of circle
Logic : area = PI * r * r
*/
#include <iostream>
using namespace std;
#define PI 3.14159
int main()
{
float r, area;
cout << "Enter radius: ";
cin >> r;
area = PI * r * r;
cout << "Area = " << area;
return 0;
}
Output
Enter radius: 5
Area = 78.5397
C++ Programming

Practice Program
Problem
Write a program using #define to calculate Simple Interest
Formula:
SI = (P * R * T)/100
C++ Programming
Possible Solution
/*
Program Name : simple_interest.cpp
Concept : #define directive
Input : P, R, T
Output : Simple Interest
Logic : SI = (P*R*T)/100
*/
#include <iostream>
using namespace std;
#define RATE 5
int main()
{
float p, t, si;
cout << "Enter Principal: ";
cin >> p;
cout << "Enter Time: ";
cin >> t;
si = (p * RATE * t) / 100;
cout << "Simple Interest = " << si;
return 0;
}
C++ Programming
Slide 6 — Macros vs Functions
Macro
• Replaced before compilation
• Faster execution
• No type checking
• May cause side effects
Function
• Compiled normally
• Type checking available
• Safer
• Slightly slower
Example Problem:
#define SQUARE(x) ((x)*(x))
SQUARE(++x)
Expands to:
((++x)*(++x))
Here x increments twice → Wrong result
This is called side effect of macros.
C++ Programming

Using Header Files


Creating Header File
header.h
#define PI 3.14
#define MAX 100
[Link]
#include "header.h"
This allows multiple files to share macros.
C++ Programming
Common Mistakes
Forgetting brackets
Wrong:
#define SQUARE(x) x*x
Correct:
#define SQUARE(x) ((x)*(x))

Using semicolon
Wrong:
#define PI 3.14;
Correct:
#define PI 3.14
C++ Programming

Defining after use


Wrong:
cout << PI;
#define PI 3.14
Correct:
#define PI 3.14
cout << PI;
C++ Programming

Slide 9 — Pro Tips


Always use brackets in macros
Place macros at top of file
Use header file for shared macros
Use uppercase macro names
Prefer inline functions when possible
■ CONDITIONAL INCLUSION
C++ Programming

Definition
Conditional Inclusion
Conditional inclusion allows you to compile certain parts of code
only when specific conditions are met.
It is done using preprocessor directives:
• #ifdef
• #ifndef
• #endif
• #else
• #elif
These directives help control compilation of code.
C++ Programming

Usage
Why Use Conditional Inclusion?
Conditional inclusion is used to:
• Avoid multiple header file inclusion
• Enable debugging code
• Platform-dependent compilation
• Enable/disable features
• Large software projects
C++ Programming

Syntax
#ifdef Syntax
#ifdef MACRO_NAME
// code compiled if defined
#endif

#ifndef Syntax
#ifndef MACRO_NAME
// code compiled if not defined
#endif
Functions in C++
C++ Programming

A function is a reusable block of code that performs a specific


task. It divides a program into smaller logical units, improves
readability, and makes code easier to maintain. A function can
accept parameters, execute statements, and optionally return a
value.
• A function Allows you to write a piece of logic once and reuse
it wherever needed in the program.
• This helps keep your code clean, organized, easier to
understand and manage.
Note: C++ also supports advanced features like function
overloading, default arguments, and inline functions, which
give more flexibility compared to C.
C++ Programming
C++ Programming
C++ Programming

Function Syntax
To work with functions in C++, it is important to understand
how they are written, declared, and called. This section covers
function syntax, declaration vs definition, and how to call a function
in a program.
C++ Programming

Function Syntax in C++


A function in C++ follows this general format:
C++ Programming

Each part has a specific role:


• Return type: Specifies what type of value the function returns.
Use void if there is no return value.

• Function name: The name you will use to call the function.

• Parameter list: Inputs that the function accepts. It can be


empty if no inputs are needed.

• Function body: The block of code that runs when the function
is called.
C++ Programming
Function Declaration vs Definition
A function declaration introduces a function to the compiler by
specifying its return type, name, and parameters without the
body, and is used when the function is defined later or in
another file.
// Declaration
int add(int, int);
Function definition contains the actual code that specifies what
the function does when it is called.
//Definition
int add(int a, int b) {
return a + b;
}
C++ Programming
Calling a Function
A function is used by calling its name followed by parentheses,
passing required arguments if any, which executes the code
inside the function.
Default Arguments in Functions
in C++
C++ Programming

Definition
Default arguments are values assigned to function parameters at
the time of function declaration.

If the user does not pass values for those parameters during the
function call, the default values are automatically used.
C++ Programming

Why Default Arguments are Useful


• Reduce the number of overloaded functions
• Make functions flexible and easy to use
• Avoid repeatedly passing the same values
• Improve code readability
Example:
• A function to calculate simple interest may usually use rate = 5%
• Instead of passing 5 every time, we can make it a default value
C++ Programming

Syntax
return_type function_name(parameter1, parameter2
= default_value);
Example Syntax
int add(int a, int b = 10);
Explanation
Part Meaning
int Return type
add Function name
int a Required parameter
int b = 10 Default argument
If b is not supplied, 10 will be used automatically
C++ Programming

Important Rules of Default Arguments


Rule 1: Default arguments are specified only once
Usually written in the function declaration.
Correct
int add(int a, int b = 5);
Wrong
int add(int a = 5, int b = 10);
int add(int a = 2, int b = 3);
C++ Programming

Rule 2: Default arguments must be from right to left


Correct
int display(int a, int b = 5, int c = 10);
Wrong
int display(int a = 5, int b, int c);
Because non-default arguments cannot appear after default
arguments.
C++ Programming

Sample Program 1

#include <iostream>
using namespace std;
int add(int a, int b = 10);
int main()
{
cout << "add(5) = " << add(5) << endl;
cout << "add(5, 20) = " << add(5, 20) << endl;
return 0;
}
int add(int a, int b)
{
return a + b;
}
Output
add(5) = 15
add(5, 20) = 25
C++ Programming

How It Works
Function Call 1
add(5);
Only one value is passed.
So compiler uses:
a = 5
b = 10
Result:
5 + 10 = 15
C++ Programming

Function Call 2
add(5, 20);
Both values are passed.
So:
a = 5
b = 20
Result:
5 + 20 = 25
C++ Programming

Sample Program 2 — Simple Interest


#include <iostream>
using namespace std;
float simpleInterest(float p, float t, float r = 5.0);
int main()
{
cout << simpleInterest(1000, 2) << endl;
cout << simpleInterest(1000, 2, 8) << endl;
return 0;
}
float simpleInterest(float p, float t, float r)
{
return (p * t * r) / 100;
}
Output
100
160
C++ Programming

Practice Program
Problem
Create a function power() to calculate powers.
• If exponent is not provided, use exponent = 2
• Otherwise use given exponent
Example
power(5) → 25
power(5,3) → 125
C++ Programming

Common Mistakes
1. Giving default values in both declaration and definition
Wrong
int add(int a, int b = 5);

int add(int a, int b = 5)


Correct
int add(int a, int b = 5);

int add(int a, int b)


C++ Programming

2. Default argument before normal argument


Wrong
int fun(int a = 10, int b);
Correct
int fun(int a, int b = 10);
C++ Programming

3. Forgetting function prototype


If default arguments are used, declaration should usually appear
before main().
C++ Programming

Pro Tips
Use default arguments when most calls use common values
Default arguments reduce unnecessary function overloading
Keep default values simple and meaningful
Place default values in header files or declarations only
Use them carefully to avoid confusion in large programs
C++ Programming

Real-Life Analogy
Think of ordering coffee:
Coffee(size = Medium)
If you do not specify size, the shop gives a Medium coffee by default.
But you can still order:
Coffee(Large)
Same idea works in default arguments.
C++ Programming

Difference Between Default Arguments and Function Overloading

Default Arguments Function Overloading


One function Multiple functions
Easier for simple cases Better for very different logic
Less code More flexibility
C++ Programming

Why Function Overloading is Useful


Function overloading helps:
• Reuse the same function name for related tasks
• Improve readability
• Reduce confusion from using many different function names
Example:
• add(int, int)
• add(double, double)
• add(int, int, int)
All perform addition, so using the same name makes sense.
Function Overloading in C++
C++ Programming

Definition
Function overloading means creating multiple functions with the
same name but with different parameter lists.
The compiler identifies which function to call based on:
• Number of arguments
• Type of arguments
• Order of arguments
This feature is called Compile-Time Polymorphism in C++.
C++ Programming

Why Function Overloading is Useful


Function overloading helps:
• Reuse the same function name for related tasks
• Improve readability
• Reduce confusion from using many different function names
Example:
• add(int, int)
• add(double, double)
• add(int, int, int)
All perform addition, so using the same name makes sense.
C++ Programming

Syntax
return_type function_name(parameter_list);
Example
int add(int a, int b);

double add(double a, double b);

int add(int a, int b, int c);


C++ Programming

How Function Overloading Works


The compiler checks:
[Link] name
[Link] of parameters
[Link] types of parameters
[Link] of parameters
This process is called Function Signature Matching.
C++ Programming
Sample Program 1 — Overloading by Number of Arguments

#include <iostream>
using namespace std;
int add(int a, int b);
int add(int a, int b, int c);
int main()
{
cout << "Sum = " << add(10, 20) << endl;
cout << "Sum = " << add(10, 20, 30) << endl;
return 0;
}
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}

Output
Sum = 30
Sum = 60
C++ Programming

Explanation
Function Call 1
add(10, 20);
Compiler selects:
int add(int a, int b)

Function Call 2
add(10, 20, 30);
Compiler selects:
int add(int a, int b, int c)
C++ Programming
Sample Program 2 — Overloading by Data Type
#include <iostream>
using namespace std;
int add(int a, int b);
double add(double a, double b);
int main()
{
cout << add(5, 6) << endl;
cout << add(5.5, 2.3) << endl;
return 0;
}
int add(int a, int b)
{
return a + b;
}
double add(double a, double b)
{
return a + b;
}

Output
11
7.8
C++ Programming
Sample Program 3 — Area Calculator
#include <iostream>
using namespace std;
int area(int side);
int area(int length, int breadth);
int main()
{
cout << "Square Area = "
<< area(5) << endl;
cout << "Rectangle Area = "
<< area(5, 10) << endl;
return 0;
}
int area(int side)
{
return side * side;
}
int area(int length, int breadth)
{
return length * breadth;
}

Output
Square Area = 25
Rectangle Area = 50
C++ Programming

Important Rules of Function Overloading


Rule 1: Parameters must differ
Correct
int fun(int a);

int fun(double a);


Wrong
int fun(int a);

float fun(int a);


Return type alone cannot overload functions.
C++ Programming

Rule 2: Function signature must be unique


Function signature includes:
• Function name
• Parameter count
• Parameter types
• Parameter order
C++ Programming

Rule 3: Compiler decides automatically


The compiler chooses the best matching function during
compilation.
C++ Programming

Practice Program
Problem
Create overloaded functions volume() for:
[Link]
[Link]
[Link]
C++ Programming
Possible Solution

#include <iostream>
using namespace std;
int volume(int side);
int volume(int l, int b, int h);
double volume(double r, double h);
int main()
{
cout << volume(5) << endl;
cout << volume(2, 3, 4) << endl;
cout << volume(2.5, 5.0) << endl;
return 0;
}
int volume(int side)
{
return side * side * side;
}
int volume(int l, int b, int h)
{
return l * b * h;
}
double volume(double r, double h)
{
return 3.14 * r * r * h;
}
C++ Programming

Common Mistakes
1. Changing only return type
Wrong
int add(int a, int b);

float add(int a, int b);


Compiler error occurs.
C++ Programming

2. Ambiguous function calls


Example
void fun(int);

void fun(double);

fun(5.5f);
Compiler may get confused.
C++ Programming

3. Using too many similar overloads


Too many overloads can make programs difficult to maintain.
C++ Programming

Pro Tips
Use overloading when functions perform similar tasks
Keep parameter differences meaningful
Prefer readability over excessive overloading
Use different data types carefully
Combine overloading with default arguments wisely
C++ Programming

Real-Life Analogy
Think of a mobile phone:
Call(Mobile Number)
Call(Contact Name)
Call(Video Call)
Same action → "Call"
Different ways to perform it.
That is exactly how function overloading works.
Storage Classes and
Namespaces
Chapter 11
C++ Programming

Definition
Storage classes in C++ define:
• Scope → Where the variable/object can be accessed
• Lifetime → How long the variable exists in memory
• Storage Location → Memory area where it is stored
• Default Initial Value
Storage classes help control how objects behave during program
execution.
C++ Programming

Types of Storage Classes


[Link] Storage Class (auto)
[Link] Storage Class (register)
[Link] Storage Class (static)
[Link] Storage Class (extern)
C++ Programming

1. Automatic Storage Class (auto)


Definition
Variables declared inside a function are automatic variables by
default.
They are created when the function starts and destroyed when the
function ends.

Usage
Used for temporary calculations inside functions.
C++ Programming

Syntax
auto datatype variable_name;
Example:
auto int x = 10;
Usually, auto keyword is omitted because local variables are
automatic by default.
C++ Programming

Sample Program
#include <iostream>
using namespace std;
void show()
{
int x = 10; // automatic variable
cout << "x = " << x << endl;
}
int main()
{
show();
return 0;
}
Output
x = 10
C++ Programming

Practice Program
Write a program that creates two local variables inside different
functions and prints them.
C++ Programming

Common Mistakes
• Trying to access automatic variables outside the function
• Assuming values remain after function ends
C++ Programming

Pro Tips
• Most local variables are automatic variables
• Use local variables whenever possible for safer memory usage
C++ Programming

2. Register Storage Class (register)


Definition
Register variables request the compiler to store the variable in CPU
registers instead of RAM for faster access.

Usage
Used for frequently accessed variables like loop counters.
C++ Programming

Syntax
register datatype variable_name;
Example:
register int i;
C++ Programming

Sample Program
#include <iostream>
using namespace std;
int main()
{
register int i;
for(i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5
C++ Programming

Practice Program
Write a program to calculate the sum of first 100 numbers using a
register loop counter.
C++ Programming

#include <iostream>

int main() {
int sum = 0;

// 'register' hints to the compiler to store 'i' in a CPU register


// for faster access during the loop.
for (register int i = 1; i <= 100; ++i) {
sum += i;
}

std::cout << "The sum of the first 100 numbers is: " << sum << std::endl;

return 0;
}
C++ Programming

Common Mistakes
• Taking address of register variable
register int x;
cout << &x; // Error

Pro Tips
• Modern compilers automatically optimize register usage
• register keyword is rarely used in modern C++
C++ Programming

3. Static Storage Class (static)


Definition
Static variables preserve their values between function calls.
Memory is allocated only once.

Usage
Used when data must retain its value throughout the program
execution.
C++ Programming

Syntax
static datatype variable_name;
Example:
static int count = 0;
C++ Programming

Sample Program
Output
#include <iostream> Count = 1
using namespace std;
Count = 2
void counter() Count = 3
{
static int count = 0;
count++;
cout << "Count = " << count << endl;
}
int main()
{
counter();
counter();
counter();
return 0;
}
C++ Programming

Explanation
Normally local variables are destroyed after function execution.
But static variables:
• Are created only once
• Retain values between calls
C++ Programming

Practice Program
Create a function that counts how many times it is called using a
static variable.
C++ Programming

#include <iostream>

void countCalls() {
// Initialized only once, the first time the function is called
static int callCount = 0;

callCount++;
std::cout << "Function called count: " << callCount << std::endl;
}

int main() {
// Calling the function multiple times to see the static variable in action
countCalls();
countCalls();
countCalls();
countCalls();

return 0;
}
C++ Programming

Common Mistakes
• Expecting static variables to reset automatically
• Using too many static variables causing difficult debugging

Pro Tips
• Static variables are excellent for counters
• Useful in recursion and function tracking
The extern Storage Class in
C++
C++ Programming

Definition
The extern storage class is used to declare a global variable or
function that is defined in another file or another part of the
program.
It tells the compiler:
“This variable already exists somewhere else. Do not create new
memory for it.”
C++ Programming

Why extern is Used


Main Purpose
• Share global variables between multiple source files.
• Avoid creating duplicate copies of variables.
• Help in modular programming.
C++ Programming

Basic Idea
Without extern
Each file creates its own variable.
With extern
All files use the same variable.
C++ Programming

Syntax
extern data_type variable_name;
Example
extern int total;
Meaning
• int → variable type
• total → variable name
• extern → variable is defined elsewhere
C++ Programming

Important Rule
extern only declares the variable.
The actual variable must be defined once somewhere else.
C++ Programming

Example in Single File


#include <iostream>
using namespace std;
int x = 100; // Definition
int main()
{
extern int x; // Declaration
cout << x;
return 0;
}
Output
100
C++ Programming

Memory Concept
int x = 100;
Memory is created.

extern int x;
No memory created.
Only tells compiler:
“Variable exists elsewhere.”
C++ Programming

Multi-File Example (Very Important)


File 1 : [Link]
#include <iostream>
using namespace std;
extern int count; // Declaration
void show();
int main()
{
cout << "Count = " << count << endl;
show();
return 0;
}
C++ Programming

Multi-File Example (Very Important)


File 2 : [Link]
#include <iostream>
using namespace std;
int count = 50; // Definition
void show()
{
cout << "Inside show(): " << count;
}

Output
Count = 50
Inside show(): 50
C++ Programming

Step-by-Step Execution
Step 1
Program starts from main().

Step 2
Compiler sees:
extern int count;
Meaning:
• Variable exists elsewhere
• Do not allocate memory
C++ Programming

Step-by-Step Execution
Step 3
Compiler searches all linked files.
Finds:
int count = 50;
in [Link]
Memory is allocated there.

Step 4
Both files now use the same variable.

Step 5
Output is printed.
C++ Programming

extern with Functions


Functions are external by default.
Example:
#include <iostream>
using namespace std;
void display(); // extern by default
int main()
{
display();
}
void display()
{
cout << "Hello";
}
C++ Programming

Difference Between Global Variable and extern


Feature Global Variable extern Variable
Memory Created Yes No
Scope Global Global
Used Across Files Limited Yes
Declaration Only No Yes
C++ Programming

Common Mistakes
Mistake 1
extern int x = 10;
Wrong usage in declaration.
Why?
Because assigning value creates definition.

Correct:
extern int x;
AND somewhere:
int x = 10;
C++ Programming

Mistake 2
Using extern without actual definition.
extern int x;
but nowhere:
int x;
Linker Error occurs.
C++ Programming

Real-Life Analogy
Imagine:
• One classroom register exists in office.
• All teachers access same register.
extern means:
“The register is in another room — use that one.”
C++ Programming

Practice Program
Task
Create two files:
File 1
Declare variable using extern.
File 2
Define variable and print it.
C++ Programming

Possible Solution
[Link]
#include <iostream>
using namespace std;
extern int marks;
int main()
{
cout << "Marks = " << marks;
}

[Link]
int marks = 95;

Output
Marks = 95
C++ Programming

Pro Tips
Tip 1
Use extern mainly for:
• global constants
• shared configuration variables
C++ Programming

Tip 2
Too many global variables make programs difficult to manage.
Prefer:
• classes
• namespaces
• function parameters
when possible.
C++ Programming

Tip 3
Usually declarations are placed in header files.
Example:
data.h
extern int count;

[Link]
int count = 50;
The Storage Class static
C++ Programming

Definition
The static storage class is used to preserve the value of a variable
between function calls or to restrict visibility of
variables/functions within a file.
Why static is Important
• Retains values between function calls
• Saves memory by creating only one copy
• Controls scope and visibility
• Useful in counters, caches, and shared resources
C++ Programming

Types of static
[Link] Local Variables
[Link] Global Variables
[Link] Member Variables (in classes)
Part 1: Static Local Variables
C++ Programming

Static Local Variable


Definition
A local variable declared with static keeps its value alive
throughout the entire program execution.
Usage
Used when:
• You want a function to remember previous values
• Counting function calls
• Tracking states
C++ Programming

Syntax
static data_type variable_name;
Syntax Explanation
• static → storage class keyword
• data_type → variable type
• variable_name → identifier
C++ Programming

• Normal Local Variable vs Static Variable


Feature Normal Variable Static Variable
Lifetime Created every call Created once
Value Retained No Yes
Memory Allocation Stack Data Segment
Default Value Garbage 0
C++ Programming

Sample Program – Static Local Variable


Program Statement
Write a program to demonstrate how a static variable retains its
value between function calls.
C++ Programming
Sample Program
#include <iostream>
using namespace std;
void counter()
{
static int count = 0;
count++;
cout << "Count = " << count << endl;
}
int main()
{
counter();
counter();
counter();
return 0;
}
Expected Output
Count = 1
Count = 2
Count = 3
C++ Programming
Common Mistakes
Mistake 1
int count = 0;
This resets every function call.
Correct
static int count = 0;

Mistake 2
Forgetting initialization.
Although static variables default to 0:
static int x;
Better practice:
static int x = 0;
C++ Programming

Pro Tips
Tip 1
Use static variables for:
• Counters
• Memoization
• Function state tracking
Tip 2
Avoid excessive use because:
• Makes debugging harder
• Creates hidden dependencies
Tip 3
Static variables consume memory throughout program execution.
Part 2: Static Global Variables
C++ Programming

Slide 9: Static Global Variable


Definition
A global variable declared as static becomes accessible only
within the same file.
Usage
Used for:
• Data hiding
• File-level security
• Preventing external access
Syntax
static int number;
C++ Programming
Sample Program – Static Global Variable
#include <iostream>
using namespace std;
static int number = 100;
void display()
{
cout << number;
}
int main()
{
display();
return 0;
}
Expected Output
100
Part 3: Static Functions
C++ Programming

Definition
A function declared as static can only be used within the same
source file.
Syntax
static void show();
Usage
Used for:
• Internal helper functions
• File-level encapsulation
Part 4: Static Members in
Classes
C++ Programming

Slide 12: Static Data Members


Definition
A static data member belongs to the class rather than individual
objects.
Key Point
Only ONE copy exists for all objects.
C++ Programming
Slide 13: Sample Program – Static Data Member
#include <iostream>
using namespace std;
class Student
{
static int count;
public:
Student()
{
count++;
}
void show()
{
cout << "Count = "
<< count
<< endl;
}
};
int Student::count = 0;
int main()
{
Student s1, s2, s3;
[Link]();
return 0;
}
Expected Output
Count = 3
C++ Programming

Real-Time Applications of static


1. Visitor Counter
Website visit tracking.
2. Bank Transaction Counter
Track total transactions.
3. Game Score System
Maintain score throughout gameplay.
4. Employee ID Generator
Generate unique IDs automatically.
5. Function Call Monitoring
Track debugging statistics.
C++ Programming

static Storage Class Key Points

Feature Description
Lifetime Entire program
Scope Depends on declaration
Default Value 0
Memory Allocated once
Value Retention Yes
The Specifiers auto and
register in C++
Part 1: auto Specifier
C++ Programming
Definition
The auto specifier allows the compiler to automatically detect the data
type of a variable from its assigned value.
Usage
Used when:
• Data type is obvious from initialization
• Writing cleaner code
• Working with complex data types
• STL iterators and templates
Important Note
In modern C++:
• auto means automatic type deduction
• Older C meaning of automatic storage is obsolete
C++ Programming

Syntax of auto
Syntax
auto variable_name = value;
Syntax Explanation
• auto → compiler determines data type
• variable_name → variable identifier
• value → assigned expression
C++ Programming

How Type Deduction Works

Statement Deduced Type


auto x = 10; int
auto y = 3.14; double
auto ch = 'A'; char
auto str = "Hello"; const char*
C++ Programming
Slide 4: Sample Program – auto
Program Statement
Write a program to demonstrate automatic type deduction using auto.
Sample Program
/*
Program Name : auto_specifier.cpp
Concept : auto Specifier
Input : No input
Output : Values and types
Logic :
1. Declare variables using auto.
2. Compiler deduces data types.
3. Display values.
*/
#include <iostream>
using namespace std;
int main()
{
auto a = 10;
auto b = 25.67;
auto c = 'S';
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
return 0;
}
Expected Output
a = 10
b = 25.67
c = S
C++ Programming

Step-by-Step Execution
Compiler Deductions
auto a = 10; → int
auto b = 25.67; → double
auto c = 'S'; → char
Internal Conversion
Compiler internally treats:
int a = 10;
double b = 25.67;
char c = 'S';
C++ Programming

Advantages of auto
Benefits
• Reduces lengthy declarations
• Improves readability
• Useful with STL containers
• Helps avoid type mismatch errors
Example
Without auto
vector<int>::iterator it;
With auto
auto it;
C++ Programming
Practice Program – auto
Problem
Write a program using auto for different data types and print them.
Possible Program
/*
Program Name : auto_practice.cpp
Concept : auto Keyword
Input : No input
Output : Multiple variable values
Logic :
1. Use auto with different values.
2. Print variables.
*/
#include <iostream>
using namespace std;
int main()
{
auto num = 500;
auto price = 99.99;
auto grade = 'A';
cout << num << endl;
cout << price << endl;
cout << grade << endl;
return 0;
}
C++ Programming
Common Mistakes with auto
Mistake 1
Declaring without initialization.
Wrong:
auto x;
Correct:
auto x = 10;

Mistake 2
Unexpected type deduction.
auto x = 5/2;
Result:
2
Because both operands are integers.
Correct:
auto x = 5.0/2;
C++ Programming

Slide 3: How Type Deduction Works

Statement Deduced Type


auto x = 10; int
auto y = 3.14; double
auto ch = 'A'; char
auto str = "Hello"; const char*
C++ Programming

Slide 9: Pro Tips for auto


Tip 1
Use auto when type names are very long.
Tip 2
Avoid overusing auto when readability decreases.
Tip 3
Always initialize auto variables immediately.
Part 2: register Specifier
C++ Programming

Slide 10: Introduction to register


Definition
The register specifier requests the compiler to store a variable in
a CPU register instead of RAM for faster access.
Usage
Used for:
• Frequently accessed variables
• Loop counters
• Performance optimization
Important Note
Modern compilers usually ignore register because they optimize
automatically.
C++ Programming

Slide 11: Syntax of register


Syntax
register data_type variable_name;
Example
register int i;
C++ Programming

• Features of register

Feature Description
Storage Location CPU Register
Speed Faster access
Scope Local only
Default Value Garbage
Address Access Not allowed
C++ Programming
Slide 13: Sample Program – register
Program Statement
Write a program using a register variable inside a loop.
Sample Program
/*
Program Name : register_variable.cpp
Concept : register Specifier
Input : No input
Output : Numbers from 1 to 5
Logic :
1. Use register variable in loop.
2. Print values.
*/
#include <iostream>
using namespace std;
int main()
{
register int i;
for(i = 1; i <= 5; i++)
{
cout << i << " ";
}
return 0;
}
Expected Output
1 2 3 4 5
C++ Programming

Slide 14: Why Address Cannot Be Accessed


Wrong Code
register int x = 10;

cout << &x;


Reason
CPU registers do not have normal memory addresses accessible
through pointers.
C++ Programming
Slide 15: Practice Program – register
Problem
Write a program using a register variable to calculate the sum from 1 to 100.
Possible Program
/*
Program Name : register_sum.cpp
Concept : register Variable
Input : No input
Output : Sum of numbers
Logic :
1. Use register loop variable.
2. Calculate sum.
*/
#include <iostream>
using namespace std;
int main()
{
register int i;
int sum = 0;
for(i = 1; i <= 100; i++)
{
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
Expected Output
Sum = 5050
C++ Programming
Slide 16: Common Mistakes with register
Mistake 1
Trying to access address.
Wrong:
register int x;
cout << &x;

Mistake 2
Using register for large variables.
Wrong:
register double largeArray[1000];
Registers are very limited.
C++ Programming

Slide 17: Pro Tips for register


Tip 1
Modern compilers optimize better than manual register.
Tip 2
Use register mainly for academic understanding.
Tip 3
Loop counters are the most common use case.
Part 3: Comparison of auto
and register
C++ Programming

• Comparison Table

Feature auto register


Purpose Type deduction Faster access
Modern Usage Very common Rare
Memory Location Depends on type CPU register
Initialization Required Yes No
Address Access Allowed Not allowed
C++ Programming
Real-Time Applications
auto
[Link] Iterators
[Link] Programming
[Link] C++ Development
[Link] Expressions
[Link] Type Handling
register
[Link] Counters
[Link] Systems
[Link]-Level Optimization
[Link]-Critical Programs
[Link] Demonstrations
The Storage Classes of
Functions in C++
C++ Programming

Definition
A storage class of a function defines:
• the visibility of the function
• the lifetime
• the scope
• and how the function can be accessed across files
In C++, functions mainly use two storage classes:
[Link] (default)
[Link]
C++ Programming

1. extern Functions
Definition
By default, every function in C++ is treated as an extern function.
This means:
• the function can be used in other files
• it has global linkage
C++ Programming

Usage
Used when:
• programs are divided into multiple files
• functions must be shared between files
• building large projects
C++ Programming

yntax
extern return_type function_name(parameters);
Explanation
Part Meaning
extern Function can be accessed from other files
return_type Type returned by function
function_name Name of function
parameters Inputs to function
C++ Programming
Sample Program
File 1: [Link]
#include <iostream>
using namespace std;
extern int add(int, int);
int main()
{
int a = 10, b = 20;
cout << "Sum = " << add(a, b);
return 0;
}
C++ Programming

File 2: [Link]
#include <iostream>
using namespace std;

int add(int x, int y)


{
return x + y;
}

Output
Sum = 30
C++ Programming
Step-by-Step Execution
Step 1
Compiler sees:
extern int add(int, int);
Meaning:
“The function exists somewhere else.”

Step 2
main() calls:
add(10, 20);

Step 3
Linker searches all files.
Finds:
int add(int x, int y)
inside [Link]
Step 4
Function executes.
10 + 20 = 30
C++ Programming

2. static Functions
Definition
A static function can only be used inside the same source file
where it is defined.
It has:
• internal linkage
• hidden visibility from other files
C++ Programming

Usage
Used when:
• helper functions should remain private
• avoiding name conflicts
• improving program security/modularity
C++ Programming

Syntax
static return_type function_name(parameters);
C++ Programming
Sample Program
File: [Link]
/*
Program Name : Static Function Example
Concept : static storage class of functions
Input : Radius value
Output : Area of circle
Logic :
1. Define static function
2. Call function inside same file
3. Print area
*/
#include <iostream>
using namespace std;
static float area(float r)
{
return 3.14 * r * r;
}
int main()
{
float radius = 5;
cout << "Area = " << area(radius);
return 0;
}

Output
Area = 78.5
C++ Programming

Important Rule
A static function:
Can be called inside same file
Cannot be called from another file
C++ Programming
Example of Error
[Link]
static void show()
{
cout << "Hello";
}
[Link]
extern void show();
int main()
{
show(); // ERROR
}

Why Error Occurs?


Because:
• static hides the function inside [Link]
• [Link] cannot access it
C++ Programming

Comparison: extern vs static Functions

Feature extern Function static Function


Visibility Across files Same file only
Linkage External Internal
Default? Yes No
Used in Multi-file Programs Yes No
Security Less private More private
C++ Programming

Practice Program 1
Problem
Create:
• one file containing a function to calculate square
• another file containing main()
Use extern.
C++ Programming
Possible Program
[Link]
#include <iostream>
using namespace std;
extern int square(int);
int main()
{
cout << square(6);
return 0;
}
[Link]
int square(int x)
{
return x * x;
}
Output
36
C++ Programming

Practice Program 2
Problem
Create a static function to calculate cube of a number.
C++ Programming
Possible Program
#include <iostream>
using namespace std;
static int cube(int x)
{
return x * x * x;
}
int main()
{
cout << cube(3);
return 0;
}

Output
27
C++ Programming

Common Mistakes
1. Using static function in another file
Wrong
extern void show();
when actual function is static.
Fix:
Remove static if cross-file access is needed.
C++ Programming

2. Forgetting Function Declaration


Wrong
cout << add(2,3);
without prototype.
Fix
extern int add(int, int);
C++ Programming

3. Multiple Same Function Names


Without static, same function names in different files may cause
linker conflicts.
Fix:
Use static for private helper functions.
C++ Programming
Tip 3
In modern C++, header files are usually used with function declarations.
Example:
math.h
int add(int, int);

Tip 4
extern is optional for normal function declarations because functions
are extern by default.
These are equivalent:
extern int add(int,int);
int add(int,int);
Namespaces in C++
C++ Programming

Definition
A namespace in C++ is a container that holds identifiers such as
variables, functions, classes, and objects.
It helps avoid name conflicts when different programs or libraries
use the same names.
Example:
• Two libraries may both contain a function named display().
• Namespaces separate them safely.
C++ Programming

Why Namespaces are Needed


Before namespaces:
• Large programs often produced naming collisions.
• Multiple programmers could accidentally create
variables/functions with the same name.
Namespaces solve this problem by grouping related code.
Example:
Math::sum()
Physics::sum()
Both functions can exist without conflict.
C++ Programming

Syntax of Namespace
namespace namespace_name
{
// declarations
}
Explanation
Part Meaning
namespace Keyword used to create namespace
namespace_name User-defined namespace name
{ } Contains variables/functions/classes
C++ Programming
Basic Example
Program
/*
Program Name : namespace_basic.cpp
Concept : Basic Namespace
Input : No input
Output : Display values from namespace
Logic :
1. Create a namespace
2. Declare variable and function
3. Access using scope resolution operator
*/
#include <iostream>
using namespace std;
namespace Student
{
int marks = 95;
void display()
{
cout << "Marks = " << marks;
}
}
int main()
{
Student::display();
return 0;
}
Output
Marks = 95
C++ Programming

Scope Resolution Operator ::


The :: operator is used to access namespace members.
Syntax
namespace_name::member_name
Example:
Student::marks
Student::display()
C++ Programming

Using Namespace
Instead of writing namespace repeatedly:
using namespace namespace_name;
Example:
using namespace Student;
Now members can be accessed directly.
C++ Programming
Example Using using namespace
/*
Program Name : using_namespace.cpp
Concept : Using Namespace
Input : No input
Output : Displays data directly
Logic :
1. Create namespace
2. Use using directive
3. Access members directly
*/
#include <iostream>
using namespace std;
namespace Test
{
int x = 100;
}
using namespace Test;
int main()
{
cout << x;
return 0;
}
Output
100
C++ Programming

Nested Namespace
A namespace inside another namespace is called a nested
namespace.
Syntax
namespace A
{
namespace B
{
// members
}
}
C++ Programming
Example of Nested Namespace
/*
Program Name : nested_namespace.cpp
Concept : Nested Namespace
Input : No input
Output : Display nested namespace value
Logic :
1. Create outer namespace
2. Create inner namespace
3. Access using ::
*/
#include <iostream>
using namespace std;
namespace College
{
namespace Student
{
int roll = 25;
}
}
int main()
{
cout << College::Student::roll;
return 0;
}
Output
25
C++ Programming
Example of Nested Namespace
/*
Program Name : nested_namespace.cpp
Concept : Nested Namespace
Input : No input
Output : Display nested namespace value
Logic :
1. Create outer namespace
2. Create inner namespace
3. Access using ::
*/
#include <iostream>
using namespace std;
namespace College
{
namespace Student
{
int roll = 25;
}
}
int main()
{
cout << College::Student::roll;
return 0;
}
Output
25
C++ Programming

Anonymous Namespace
A namespace without a name is called an anonymous namespace.
Syntax
namespace
{
int x;
}
Purpose
• Limits visibility to current file only
• Similar to static global variables
C++ Programming

Standard Namespace std


C++ standard library uses namespace std.
Example:
std::cout
std::cin
std::endl
Instead of writing std:: repeatedly:
using namespace std;
C++ Programming

• Real-Time Use of Namespaces


Area Usage
Large software projects Avoid naming conflicts
Libraries Separate library functions
Game development Organize modules
Banking software Divide account/customer/payment modules
Operating systems Separate kernel utilities
C++ Programming

Common Mistakes
1. Forgetting Scope Resolution Operator
Wrong:
[Link]();
Correct:
Student::display();
C++ Programming

2. Using Same Names


int x = 10;
namespace Test
{
int x = 20;
}
May create confusion.
C++ Programming

3. Overusing using namespace std


In large projects it may create naming conflicts.
Prefer:
std::cout
std::cin
C++ Programming

Pro Tips
Use namespaces in all large projects
Use meaningful namespace names:
Math
Physics
Graphics
Database
Prefer:
std::cout
instead of:
using namespace std;
in professional software development.
Group related functions logically.
C++ Programming

Practice Program 1
Problem
Create a namespace Math with:
• variable a = 10
• function square()
Display square of the number.
C++ Programming
Possible Solution
#include <iostream>
using namespace std;
namespace Math
{
int a = 10;
void square()
{
cout << "Square = " << a * a;
}
}
int main()
{
Math::square();
return 0;
}
C++ Programming

Practice Program 2
Problem
Create two namespaces:
• India
• USA
Both should contain variable currency.
Display both currencies.
C++ Programming
Possible Solution
#include <iostream>
using namespace std;
namespace India
{
string currency = "Rupee";
}
namespace USA
{
string currency = "Dollar";
}
int main()
{
cout << India::currency << endl;
cout << USA::currency;
return 0;
}
C++ Programming

Execution Flow
Example
Math::square();
Step-by-Step
[Link] searches namespace Math
[Link] function square()
[Link] function
[Link] output
C++ Programming

• Difference Between Class and Namespace


Namespace Class
Used for grouping Used for object creation
No objects needed Objects usually required
Only organizes code Supports OOP concepts
No access specifiers by default Has private/public/protected
The Keyword using in C++
C++ Programming

Definition
The keyword using in C++ is used to:
• bring namespace members into current scope
• avoid repeatedly writing the namespace name
• simplify access to functions, variables, and classes
It is commonly used with the standard namespace std.
C++ Programming

Why using is Needed


Without using:
std::cout << "Hello";
std::cin >> x;
With using:
using namespace std;

cout << "Hello";


cin >> x;
This makes programs shorter and easier to read.
C++ Programming

Syntax of using
1. Using Entire Namespace
using namespace namespace_name;
Example:
using namespace std;
C++ Programming

2. Using Specific Member


using namespace_name::member_name;
Example:
using std::cout;
using std::endl;
C++ Programming
Example 1 — Without using
/*
Program Name : without_using.cpp
Concept : Accessing namespace members directly
Input : No input
Output : Displays message
Logic :
1. Use std namespace explicitly
2. Access cout and endl using ::
*/
#include <iostream>
int main()
{
std::cout << "Welcome to C++" << std::endl;
return 0;
}
Output
Welcome to C++
C++ Programming
Example 2 — Using Entire Namespace
/*
Program Name : using_namespace_std.cpp
Concept : using namespace std
Input : No input
Output : Displays message
Logic :
1. Import std namespace
2. Use cout directly
*/
#include <iostream>
using namespace std;
int main()
{
cout << "Hello Student";
return 0;
}
Output
Hello Student
C++ Programming
Example 3 — Using Specific Members
/*
Program Name : using_specific_member.cpp
Concept : Using specific namespace members
Input : No input
Output : Displays message
Logic :
1. Import only cout and endl
2. Use them directly
*/
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Learning C++" << endl;
return 0;
}
Output
Learning C++
C++ Programming

How using Works Internally


When compiler sees:
using namespace std;
It allows all members of namespace std to be used directly in
current scope.
So:
cout
becomes:
std::cout
internally.
C++ Programming
Using with User-Defined Namespace
Example
/*
Program Name : user_defined_namespace.cpp
Concept : using with custom namespace
Input : No input
Output : Displays value
Logic :
1. Create namespace
2. Use using directive
3. Access variable directly
*/
#include <iostream>
using namespace std;
namespace Test
{
int value = 500;
}
using namespace Test;
int main()
{
cout << value;
return 0;
}
Output
500
C++ Programming

Scope of using
using can be applied:
• globally
• inside functions
• inside classes
C++ Programming

Example — Local Scope


#include <iostream>

int main()
{
using std::cout;

cout << "Inside main function";

return 0;
}
Here cout is available only inside main().
C++ Programming

• Advantages of using

Advantage Explanation
Shorter code No need to write namespace repeatedly
Easy readability Cleaner programs
Faster typing Helpful in small programs
Better learning Beginner-friendly
C++ Programming

• Disadvantages of using namespace std


Problem Explanation
Name conflicts Different libraries may contain same names
Confusion Difficult to identify source of function
Unsafe in large projects Can create ambiguity
C++ Programming

Best Practice
Small Programs
using namespace std;
is acceptable.
C++ Programming

Professional Projects
Prefer:
std::cout
std::cin
std::string
This avoids conflicts.
C++ Programming

Common Mistakes
1. Forgetting Namespace Name
Wrong:
using std;
Correct:
using namespace std;
C++ Programming

2. Using Before Namespace Exists


Wrong:
using namespace Test;

namespace Test
{
}
Namespace should be defined first.
C++ Programming

3. Creating Ambiguity
namespace A
{
int x = 10;
}
namespace B
{
int x = 20;
}
using namespace A;
using namespace B;
Now x becomes ambiguous.
C++ Programming

Practice Program 1
Problem
Create namespace Math with function square().
Use using namespace Math.
Display square of 8.
C++ Programming
Possible Solution
#include <iostream>
using namespace std;
namespace Math
{
void square(int x)
{
cout << "Square = " << x * x;
}
}
using namespace Math;
int main()
{
square(8);
return 0;
}
C++ Programming

Practice Program 2
Problem
Import only:
• cout
• endl
Display:
Welcome to Programming
C++ Programming

Possible Solution
#include <iostream>

using std::cout;
using std::endl;

int main()
{
cout << "Welcome to Programming" << endl;

return 0;
}
C++ Programming

• Real-Time Usage of using


Area Usage
Competitive programming Reduces typing
Teaching Easier for beginners
Large applications Specific member import
Game engines Organized namespaces
Libraries Controlled access
C++ Programming

Execution Flow Example


using namespace std;

cout << "Hello";


Step-by-Step
[Link] imports namespace std
[Link] cout inside std
[Link] output statement
[Link] result
C++ Programming

• Difference Between using namespace and using

Statement Meaning
using namespace std; Imports entire namespace
using std::cout; Imports only one member
C++ Programming

Pro Tips
Prefer importing only required members:
using std::cout;
using std::cin;
Avoid:
using namespace std;
in header files.
Use explicit namespaces in professional software.
Keep namespace usage limited to required scope.
References and Pointers
Chapter 12
Defining References in C++
C++ Programming

Introduction to References
A reference is another name (alias) for an existing variable.
Once a reference is connected to a variable:
• both names refer to the same memory location
• changing one changes the other
C++ Programming
C++ Programming
C++ Programming

You might also like