C++ Programming Notes
C++ Programming Notes
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
2. Object-Oriented
Supports:
• Classes
• Objects
• Encapsulation
• Inheritance
• Polymorphism
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.
6. Reusability
• Code reuse using:
• Functions
• Classes
• Inheritance
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
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
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
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
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
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
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
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
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
Practice Program
Problem
Store and display:
[Link] English character using char
2.A Greek or Indian character using wchar_t
C++ Programming
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
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
Sample Program
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
Syntax
signed int a;
unsigned int b;
Other valid forms:
unsigned x; // unsigned int
signed short s;
unsigned long n;
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
Usage
• Used when values are small and memory efficiency is important
• Common in embedded systems and arrays with many elements
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
Usage
• Used for large counts, IDs, population, distance, etc.
• Useful when int range is not enough
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
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
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
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
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
1. Literal Constants
Definition
• Fixed values written directly in the program
• Value cannot be changed
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
int main() {
const float PI = 3.14f;
int radius = 5;
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
Syntax
"\escape_character"
Explanation:
• \ → escape character (backslash)
• escape_character → tells the compiler what special action to
perform
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
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
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
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
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
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
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
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
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
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
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 CALLS
Definition
A function call executes the function by passing required values.
Syntax
function_name(arguments);
Example
sqrt(25);
C++ Programming
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
cout << rand();
return 0;
}
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
int main() {
cout << "Hello World";
return 0;
}
Here:
• <iostream> defines cout
• Without it → compilation error
C++ Programming
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
Stream Purpose
cin Standard input (keyboard)
cout Standard output (screen)
cerr Standard error output
clog Buffered error output
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
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
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>
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
int main() {
cout << setw(5) << 25;
}
Output:
25
(Default fill character is space)
C++ Programming
int main() {
cout << setfill('*') << setw(5) << 25;
}
Output:
***25
Now * fills the empty spaces instead of space.
C++ Programming
int main() {
cout << setfill('0') << setw(5) << 42;
}
Output:
00042
C++ Programming
Key Notes
setfill() remains active until changed
setw() works only for the next output
Must include <iomanip>
C++ Programming
int main() {
int n = 100;
cout << dec << n;
}
Output:
100
dec is the default format.
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
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
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
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
Solution:
cin >> age;
[Link](); // Clear buffer
[Link](name, 50);
OR
cin >> age;
[Link](1000, '\n');
[Link](name, 50);
C++ Programming
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
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
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
2. Post-Increment (a++)
Value is used first, then increased.
int a = 5;
int b = a++;
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; // -5
Now the value is actually changed.
C++ Programming
cout << y; // 10
Minus of minus becomes plus.
C++ Programming
Example:
int a = 5, b = 3;
Example:
int a = 5, b = 3;
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
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
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
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
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
Syntax
1️⃣ Logical AND (&&)
condition1 && condition2
True only if both conditions are true.
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
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
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
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
Part Meaning
while loop keyword
condition loop continues while condition is true
statements repeated execution
The while Statement (C++)
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.
4. Prefer Indentation
Readable code example:
while(condition)
{
statements;
}
Mini-Projects
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
Pro Tips
Use i++ for counting loops (most common).
Use -- for reverse loops.
Example:
for(int i = 10; i >= 1; i--)
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
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.
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
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
• Sample Program
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
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
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 semicolon
Wrong:
#define PI 3.14;
Correct:
#define PI 3.14
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
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 name: The name you will use to call the function.
• 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
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
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
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);
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
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
Syntax
return_type function_name(parameter_list);
Example
int add(int a, int b);
#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
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);
void fun(double);
fun(5.5f);
Compiler may get confused.
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
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
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;
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
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
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
Memory Concept
int x = 100;
Memory is created.
extern int x;
No memory created.
Only tells compiler:
“Variable exists elsewhere.”
C++ Programming
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
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
Syntax
static data_type variable_name;
Syntax Explanation
• static → storage class keyword
• data_type → variable type
• variable_name → identifier
C++ Programming
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
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
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
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
• 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
Mistake 2
Using register for large variables.
Wrong:
register double largeArray[1000];
Registers are very limited.
C++ Programming
• Comparison Table
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;
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
}
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
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
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
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
Common Mistakes
1. Forgetting Scope Resolution Operator
Wrong:
[Link]();
Correct:
Student::display();
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
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
Syntax of using
1. Using Entire Namespace
using namespace namespace_name;
Example:
using namespace std;
C++ Programming
Scope of using
using can be applied:
• globally
• inside functions
• inside classes
C++ Programming
int main()
{
using std::cout;
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
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
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
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