Introduction to C++
Start your programming journey by understanding what C++ is, why it is used and how it differs from C.
START DAY 01#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!";
return 0;
}
Course Introduction
Learn C++ from the foundation
This course is designed to take you from the fundamentals of C++ programming to advanced concepts. Each day focuses on a specific topic followed by practice and MCQ tests.
Introduction to C++
Understand the foundation of C++ programming.
What is C++?
C++ is a cross-platform language that can be used to create high-performance applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
Why Use C++?
- C++ is one of the world's most popular programming languages.
- C++ can be found in today's operating systems, Graphical User Interfaces and embedded systems.
- C++ is an object-oriented programming language which gives a clear structure to programs.
- C++ allows code to be reused, lowering development costs.
Difference Between C and C++
C++ was developed as an extension of C, and both languages have almost the same syntax.
Basic Syntax of C++
Every C++ program follows a basic structure. Understanding this structure is important before writing more complex programs.
प्रत्येक C++ program एक basic structure को follow करता है। बड़े programs लिखने से पहले इस structure को समझना जरूरी है।
Basic C++ Program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0;
}
Explanation
- #include <iostream> — Includes the input/output library.
- using namespace std; — Allows us to use standard C++ features without writing std:: every time.
- int main() — The main function where program execution begins.
- cout — Used to display output on the screen.
- return 0; — Indicates that the program has completed successfully.
- { } — Define the beginning and end of a block of code.
- ; — Used to terminate most C++ statements.
- #include <iostream> — Input/Output library को program में include करता है।
- using namespace std; — Standard C++ features को बिना बार-बार std:: लिखे use करने देता है।
- int main() — Program का execution यहीं से शुरू होता है।
- cout — Screen पर output दिखाने के लिए use होता है।
- return 0; — बताता है कि program successfully complete हुआ।
- { } — Code block की शुरुआत और अंत को define करते हैं।
- ; — अधिकांश C++ statements के अंत में लगाया जाता है।
Comments in C++
Comments are notes written inside the source code. They are ignored by the compiler and are mainly used to explain the code.
Comments source code के अंदर लिखे गए notes होते हैं। Compiler comments को ignore करता है। इनका उपयोग code को समझाने के लिए किया जाता है।
1. Single-Line Comment
A single-line comment starts with //.
Single-line comment // से शुरू होता है।
// This is a single-line comment
#include <iostream>
using namespace std;
int main()
{
// Display message
cout << "Hello World";
return 0;
}
2. Multi-Line Comment
A multi-line comment starts with /* and ends with */.
Multi-line comment /* से शुरू होकर */ पर समाप्त होता है।
/*
This is a
multi-line comment
*/
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0;
}
Quick Revision
// → Single-line comment
/* ... */ → Multi-line comment
#include <iostream> → Input/Output library
main() → Program execution starts here
cout → Output
; → Statement terminator
The main difference between C and C++ is that C++ supports classes and objects, while C does not.
Lesson Summary
C++ Data Types
Learn the basic data types used in C++ programs.
C++ Data Types
Data types specify the type of data that a variable can store.
In this lesson, we will learn four basic data types: int, char, string, and float.
int — Integer
int is used to store whole numbers.
Examples: 1, 2, 3, 10, 100
int a = 10;
int b = 20;
char — Character
char is used to store a single character.
It can store letters such as a to z and A to Z.
A character is written inside single quotes (' ').
char grade = 'A';
char letter = 'b';
string — Text
string is used to store a sequence of characters.
A string can contain a word, name, or sentence.
A string is written inside double quotes (" ").
string name = "Gautam";
string message = "Hello World";
float — Decimal Value
float is used to store decimal values.
Examples: 1.23, 4.24, 10.5
float a = 1.23;
float b = 4.24;
Write a C++ Program to Add Two Numbers
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int sum = a + b;
cout << "Sum = " << sum;
return 0;
}
Sum = 30
Here, a + b adds the two numbers and stores the result in sum.
Write a C++ Program to Subtract Two Numbers
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b = 10;
int difference = a - b;
cout << "Difference = " << difference;
return 0;
}
Difference = 10
Write a C++ Program to Multiply Two Numbers
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int product = a * b;
cout << "Product = " << product;
return 0;
}
Product = 200
Write a C++ Program to Divide Two Numbers
#include <iostream>
using namespace std;
int main() {
float a = 20;
float b = 5;
float quotient = a / b;
cout << "Quotient = " << quotient;
return 0;
}
Quotient = 4
Data Types at a Glance
| Data Type | Used For | Example |
|---|---|---|
| int | Whole numbers | 10 |
| char | Single character | 'A' |
| string | Text / Sentence | "Hello" |
| float | Decimal values | 1.23 |
+ → Addition
- → Subtraction
* → Multiplication
/ → Division
C++ Data Types
C++ Data Types
Learn char, string and float with simple C++ examples.
char — Character
char is used to store a single character.
It can store characters from a to z and A to Z.
Example
#include <iostream>
using namespace std;
int main() {
char letter = 'A';
cout << "Character = " << letter;
return 0;
}
Character = A
string — Text
string is used to store a sequence of characters.
Characters can be combined to make a word, name or sentence. This is called a string.
Example
#include <iostream>
using namespace std;
int main() {
string message = "Hello World";
cout << message;
return 0;
}
Hello World
float — Decimal Value
float is used to store decimal values.
Examples: 1.23, 4.24, 10.5
Complete Code Example
#include <iostream>
using namespace std;
int main() {
float a = 20;
float b = 5;
float quotient = a / b;
cout << "Quotient = " << quotient;
return 0;
}
Quotient = 4
C++ Data Types
Swap Two Numbers
Learn how to swap two numbers using a third variable.
Swap Two Numbers Using a Third Variable
Write a C++ program to swap two numbers using a third variable.
Suppose: a = 10 and b = 20.
Store the Value of a in c
First, store the value of a in the third variable c.
c = a;
Store the Value of b in a
Now, store the value of b in a.
a = b;
Store the Value of c in b
Finally, store the original value of a, which is saved in c, into b.
b = c;
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
The third variable c temporarily stores the original value of a.
C++ Program to Swap Two Numbers
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int c = 0;
c = a;
a = b;
b = c;
cout << "a = " << a << endl;
cout << "b = " << b;
return 0;
}
a = 20
b = 10
Swap Two Numbers
Variables, Data Types & Operators
Learn variables, data types, input/output and operators in C++.
Variables and Constants
A variable is used to store data that can be changed during the execution of a program.
A constant is a value that cannot be changed after it is defined.
Data Types
Data types define the type of data that a variable can store.
Examples: int, char, string, float
Keywords and Identifiers
Keywords are reserved words in C++ that have a special meaning.
Examples: int, float, return, if
Identifiers are names given to variables, functions and other program elements.
Input and Output — cin, cout
cin is used to take input from the user.
cout is used to display output on the screen.
Relational Operators
Relational operators are used to compare two values. The result of a relational operation is either true or false.
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal to | 10 == 10 | true |
| != | Not equal to | 10 != 20 | true |
| > | Greater than | 20 > 10 | true |
| < | Less than | 10 < 20 | true |
| >= | Greater than or equal to | 20 >= 20 | true |
| <= | Less than or equal to | 10 <= 20 | true |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b = 10;
cout << (a == b) << endl;
cout << (a != b) << endl;
cout << (a > b) << endl;
cout << (a < b) << endl;
cout << (a >= b) << endl;
cout << (a <= b) << endl;
return 0;
}
0 1 1 0 1 0
Note: In C++, 1 = true and 0 = false.
Logical Operators
Logical operators are used to combine two or more conditions.
| Operator | Name | Meaning | Example |
|---|---|---|---|
| && | AND | Both conditions must be true | a > 10 && b < 20 |
| || | OR | At least one condition must be true | a > 10 || b < 20 |
| ! | NOT | Reverses the result | !(a > b) |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b = 10;
// AND
cout << (a > 10 && b < 20) << endl;
// OR
cout << (a > 30 || b < 20) << endl;
// NOT
cout << !(a < b) << endl;
return 0;
}
1 1 1
Note: In C++, Logical Operators return 1 (true) or 0 (false).
Bitwise XOR Operator
The ^ operator is called Bitwise XOR. It compares the corresponding bits of two numbers.
| Operator | Name | Rule | Example |
|---|---|---|---|
| ^ | Bitwise XOR | Different bits → 1, Same bits → 0 | 5 ^ 3 |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 3;
int result = a ^ b;
cout << "XOR = " << result;
return 0;
}
XOR = 6
Important: ^ is a Bitwise XOR operator, not a Logical Operator.
Assignment Operators
Assignment operators are used to assign or update values in variables.
| Operator | Name | Example | Meaning |
|---|---|---|---|
| = | Assignment | a = 10 | a में 10 store |
| += | Add and Assign | a += 5 | a = a + 5 |
| -= | Subtract and Assign | a -= 5 | a = a - 5 |
| *= | Multiply and Assign | a *= 5 | a = a * 5 |
| /= | Divide and Assign | a /= 5 | a = a / 5 |
| %= | Modulus and Assign | a %= 5 | a = a % 5 |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 20;
a += 5;
cout << "After += : " << a << endl;
a -= 5;
cout << "After -= : " << a << endl;
a *= 2;
cout << "After *= : " << a << endl;
a /= 2;
cout << "After /= : " << a << endl;
a %= 6;
cout << "After %= : " << a << endl;
return 0;
}
After += : 25 After -= : 20 After *= : 40 After /= : 20 After %= : 2
Increment and Decrement
The ++ operator increases a value by 1. The -- operator decreases a value by 1.
| Operator | Name | Operation | Example |
|---|---|---|---|
| ++ | Increment | Value + 1 | a++ |
| -- | Decrement | Value - 1 | a-- |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 10;
cout << "Initial value = " << a << endl;
a++;
cout << "After Increment = " << a << endl;
a--;
cout << "After Decrement = " << a << endl;
return 0;
}
Initial value = 10 After Increment = 11 After Decrement = 10
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division and remainder.
| Operator | Name | Operation | Example |
|---|---|---|---|
| + | Addition | a + b | 10 + 5 = 15 |
| - | Subtraction | a - b | 10 - 5 = 5 |
| * | Multiplication | a * b | 10 * 5 = 50 |
| / | Division | a / b | 10 / 5 = 2 |
| % | Modulus | a % b | 10 % 3 = 1 |
Complete Example
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 3;
cout << "Addition = " << a + b << endl;
cout << "Subtraction = " << a - b << endl;
cout << "Multiplication = " << a * b << endl;
cout << "Division = " << a / b << endl;
cout << "Remainder = " << a % b << endl;
return 0;
}
Addition = 13 Subtraction = 7 Multiplication = 30 Division = 3 Remainder = 1
+ → Addition
- → Subtraction
* → Multiplication
/ → Division
% → Remainder / Modulus
Write a C++ Program to Swap Two Numbers Without Using a Third Variable
In this program, two numbers are swapped without using a third variable.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b;
return 0;
}
After swapping:
a = 20
b = 10
Variables, Data Types & Operators
Conditional Statements
Learn XOR swap and conditional statements in C++.
XOR Swap
XOR can be used to swap two integer values without using a third variable.
Complete Example — Swap Two Numbers Using XOR
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "After swapping:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b;
return 0;
}
After swapping: a = 20 b = 10
Note: XOR swap is generally demonstrated with integer values.
if Statement
The if statement executes a block of code when a given condition is true.
Complete Example
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are eligible.";
}
return 0;
}
You are eligible.
if-else Statement
The if-else statement executes one block when the condition is true and another block when it is false.
Complete Example
#include <iostream>
using namespace std;
int main() {
int number = 10;
if (number > 0) {
cout << "Positive number";
}
else {
cout << "Negative number";
}
return 0;
}
Positive number
Nested if
A nested if means using one if statement inside another if statement.
Complete Example
#include <iostream>
using namespace std;
int main() {
int age = 20;
int id = 1;
if (age >= 18) {
if (id == 1) {
cout << "Entry allowed";
}
}
return 0;
}
Entry allowed
else-if Ladder
An else-if ladder is used to check multiple conditions one by one.
Complete Example
#include <iostream>
using namespace std;
int main() {
int marks = 75;
if (marks >= 90) {
cout << "Grade A+";
}
else if (marks >= 75) {
cout << "Grade A";
}
else if (marks >= 60) {
cout << "Grade B";
}
else if (marks >= 50) {
cout << "Grade C";
}
else {
cout << "Fail";
}
return 0;
}
Grade A
switch Statement
The switch statement is used to select one block of code from multiple choices.
Complete Example
#include <iostream>
using namespace std;
int main() {
int day = 2;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid day";
}
return 0;
}
Tuesday
Note: The break statement stops the execution of the switch block.
Loops
Learn for, while and do-while loops in C++.
for Loop
The for loop is used to execute a block of code repeatedly for a specific number of times.
| Part | Purpose | Example |
|---|---|---|
| Initialization | Starting value | int i = 1 |
| Condition | Checks the condition | i <= 5 |
| Update | Changes the value | i++ |
Complete Example
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
return 0;
}
1 2 3 4 5
while Loop
The while loop repeatedly executes a block of code as long as the given condition is true.
| Step | Purpose |
|---|---|
| Initialization | Set the starting value |
| Condition | Check the condition |
| Update | Change the value inside the loop |
Complete Example
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << i << endl;
i++;
}
return 0;
}
1 2 3 4 5
do-while Loop
The do-while loop executes the code block at least once and then checks the condition.
| Step | Working |
|---|---|
| 1 | Execute the code |
| 2 | Check the condition |
| 3 | Repeat if condition is true |
Complete Example
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << endl;
i++;
} while (i <= 5);
return 0;
}
1 2 3 4 5
Important: A do-while loop executes at least once, even when the condition is false initially.
Loop Comparison
| Loop | Condition Check | Minimum Execution | Common Use |
|---|---|---|---|
| for | Before execution | 0 times | Known number of iterations |
| while | Before execution | 0 times | Condition-based repetition |
| do-while | After execution | At least 1 time | Menu/input-based programs |
Break, Continue & Lambda Expressions
Learn break, continue and lambda expressions in C++.
break Statement
The break statement is used to stop the loop immediately.
| Keyword | Purpose | Works In |
|---|---|---|
| break | Stops the loop | for, while, do-while, switch |
Example 1 — Stop Loop
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
return 0;
}
1 2 3 4
Example 2 — Break with while Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 10) {
if (i == 4) {
break;
}
cout << i << endl;
i++;
}
return 0;
}
1 2 3
Example 3 — Break with Number
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
cout << i << " ";
}
return 0;
}
1 2
continue Statement
The continue statement skips the current iteration and moves to the next iteration.
| Keyword | Purpose |
|---|---|
| continue | Skips the current iteration |
Example 1 — Skip Number 3
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
1 2 4 5
Example 2 — Skip Even Number
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue;
}
cout << i << " ";
}
return 0;
}
1 3 5
Example 3 — Skip Number 2
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
i++;
if (i == 2) {
continue;
}
cout << i << " ";
}
return 0;
}
1 3 4 5
Lambda Expressions
A lambda expression is a small anonymous function that can be created directly in C++ code.
| Part | Meaning |
|---|---|
| [] | Capture list |
| () | Parameters |
| {} | Function body |
Example 1 — Simple Lambda
#include <iostream>
using namespace std;
int main() {
auto greet = []() {
cout << "Hello C++";
};
greet();
return 0;
}
Hello C++
Example 2 — Lambda with Parameters
#include <iostream>
using namespace std;
int main() {
auto add = [](int a, int b) {
return a + b;
};
cout << add(10, 20);
return 0;
}
30
Example 3 — Lambda with Variable
#include <iostream>
using namespace std;
int main() {
int number = 10;
auto square = [number]() {
return number * number;
};
cout << square();
return 0;
}
100
Quick Revision
| Topic | Purpose |
|---|---|
| break | Stops the loop immediately |
| continue | Skips the current iteration |
| Lambda | Creates a small anonymous function |
Characters & Strings
Learn char, character input/output, strings and basic string operations.
Introduction to Character (char)
The char data type is used to store a single character in C++.
Example
#include <iostream>
using namespace std;
int main()
{
char letter = 'A';
cout << "Character = " << letter;
return 0;
}
Output
Important Points
- char stores a single character.
- Character values are written inside single quotes (' ').
- Examples: 'A', 'b', '7', '@'
- A char variable can store only one character at a time.
Character Input and Output
We can use cin to take a character as input and cout to display it.
Example
#include <iostream>
using namespace std;
int main()
{
char letter;
cout << "Enter a character: ";
cin >> letter;
cout << "You entered: " << letter;
return 0;
}
Example Input
Output
cin → Input
cout → Output
char → Single character
Introduction to String
A string is used to store a sequence of characters such as a name, word or sentence.
Example
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
cout << "Name = " << name;
return 0;
}
Output
Important Points
- string stores multiple characters.
- Strings are written inside double quotes (" ").
- Examples: "Hello", "Rahul", "Hello World"
- The <string> header is used for the C++ string class.
String Input and Output
We can use cin to take a single word and getline() to take a complete line or sentence as input.
Using cin
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello " << name;
return 0;
}
Note: cin stops reading when it encounters whitespace.
Using getline()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
cout << "Enter a sentence: ";
getline(cin, message);
cout << "You entered: " << message;
return 0;
}
Example Input
Output
Basic String Operations
C++ provides several basic operations for working with strings.
1. Find String Length
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
cout << name.length();
return 0;
}
2. String Concatenation
The + operator can be used to join strings.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first = "Hello";
string second = "World";
string result = first + " " + second;
cout << result;
return 0;
}
3. Compare Strings
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "Hello";
string b = "Hello";
if (a == b)
{
cout << "Strings are equal";
}
return 0;
}
4. Access Individual Characters
String characters can be accessed using an index. The first index is 0.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
cout << name[0];
return 0;
}
5. Change a Character
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
name[0] = 'S';
cout << name;
return 0;
}
Quick Revision
char → Stores one character
string → Stores multiple characters
cin → Takes input
cout → Displays output
getline() → Reads a complete line
length() → Finds string length
+ → Joins strings
== → Compares strings
string[0] → Accesses first character
Character Functions & String Operations
Learn character functions, string traversal, length, comparison and manipulation.
Character Functions
C++ provides useful character functions such as isalpha(), isdigit(), toupper() and tolower().
1. isalpha()
Checks whether a character is an alphabet letter. It returns a non-zero value if the character is alphabetic.
#include <iostream>
using namespace std;
int main()
{
char ch = 'A';
if (isalpha(ch))
{
cout << "It is an alphabet";
}
return 0;
}
2. isdigit()
Checks whether a character is a digit from 0 to 9.
#include <iostream>
using namespace std;
int main()
{
char ch = '7';
if (isdigit(ch))
{
cout << "It is a digit";
}
return 0;
}
3. toupper()
Converts a lowercase alphabet character into uppercase.
#include <iostream>
using namespace std;
int main()
{
char ch = 'a';
cout << char(toupper(ch));
return 0;
}
4. tolower()
Converts an uppercase alphabet character into lowercase.
#include <iostream>
using namespace std;
int main()
{
char ch = 'Z';
cout << char(tolower(ch));
return 0;
}
isalpha() → Checks alphabet
isdigit() → Checks digit
toupper() → Converts to uppercase
tolower() → Converts to lowercase
String Traversal
String traversal means accessing each character of a string one by one using an index or loop.
Using Index
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
cout << name[0] << endl;
cout << name[1] << endl;
cout << name[2] << endl;
return 0;
}
a
h
Using for Loop
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
for (int i = 0; i < name.length(); i++)
{
cout << name[i] << endl;
}
return 0;
}
a
h
u
l
String Length
String length means the total number of characters present in a string.
Using length()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "Rahul";
cout << "Length = " << name.length();
return 0;
}
Using size()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "Hello";
cout << "Length = " << text.size();
return 0;
}
length() → Returns number of characters
size() → Also returns number of characters
String Comparison
Two strings can be compared using comparison operators such as == and !=.
Compare Two Strings
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first = "Hello";
string second = "Hello";
if (first == second)
{
cout << "Strings are equal";
}
return 0;
}
Not Equal
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first = "Hello";
string second = "World";
if (first != second)
{
cout << "Strings are different";
}
return 0;
}
String Manipulation
String manipulation means performing operations such as joining, copying and searching strings.
1. String Concatenation
Concatenation means joining two or more strings.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first = "Hello";
string second = "World";
string result = first + " " + second;
cout << result;
return 0;
}
2. String Copying
A string can be copied into another string using the assignment operator =.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first = "Hello";
string second;
second = first;
cout << second;
return 0;
}
3. String Searching
The find() function can be used to search for a character or substring.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "Hello World";
size_t position = text.find("World");
if (position != string::npos)
{
cout << "Found at position " << position;
}
return 0;
}
Quick Revision
isalpha() → Checks alphabet
isdigit() → Checks digit
toupper() → Converts to uppercase
tolower() → Converts to lowercase
string[index] → Access character
length() → Finds string length
size() → Finds string length
== → Compares strings
+ → Concatenates strings
= → Copies a string
find() → Searches character/substring
Character & String
Learn character variables, strings, vowels, string length and palindrome programs.
What is a Character (char)?
A char is a data type used to store a single character in C++. A character is written inside single quotes.
Declaration
char letter;
Initialization
char letter = 'A';
Complete Example
#include <iostream>
using namespace std;
int main()
{
char letter = 'A';
cout << "Character = " << letter;
return 0;
}
char → Stores one character
'A' → Character constant
char letter = 'A'; → Declaration + Initialization
What is a String?
A string is a sequence of characters used to store words, names or complete sentences.
Declaration
string name;
Initialization
string name = "Rahul";
String Input using cin
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Name = " << name;
return 0;
}
Note: cin reads only one word. To read a complete sentence containing spaces, use getline().
String Input using getline()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
cout << "Enter a sentence: ";
getline(cin, message);
cout << "You entered: " << message;
return 0;
}
string name; → Declaration
string name = "Rahul"; → Initialization
cin >> name; → Single word input
getline(cin, name); → Complete line input
Count Vowels and Consonants in a String
In this program, we traverse the string character by character and count vowels and consonants separately.
Program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
int vowels = 0;
int consonants = 0;
cout << "Enter a string: ";
getline(cin, text);
for (int i = 0; i < text.length(); i++)
{
char ch = tolower(text[i]);
if (isalpha(ch))
{
if (ch == 'a' || ch == 'e' ||
ch == 'i' || ch == 'o' ||
ch == 'u')
{
vowels++;
}
else
{
consonants++;
}
}
}
cout << "Vowels = " << vowels << endl;
cout << "Consonants = " << consonants;
return 0;
}
Example Input
Output
Consonants = 7
Logic
Step 1: Take a string as input.
Step 2: Traverse every character using a loop.
Step 3: Convert the character to lowercase.
Step 4: Check whether it is a vowel.
Step 5: Otherwise, if it is an alphabet, count it as a consonant.
Find String Length Without Built-in Length Function
We can find the length of a string manually by traversing every character and increasing a counter.
Program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
int length = 0;
cout << "Enter a string: ";
getline(cin, text);
for (char ch : text)
{
length++;
}
cout << "Length = " << length;
return 0;
}
Example Input
Output
length = 0 → Counter starts from 0
for (char ch : text) → Traverses every character
length++ → Increases counter for every character
Check Whether a String is Palindrome
A palindrome is a word or string that reads the same forward and backward.
Examples
MADAM → Palindrome
LEVEL → Palindrome
RADAR → Palindrome
HELLO → Not Palindrome
Program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string text;
cout << "Enter a string: ";
cin >> text;
bool palindrome = true;
int start = 0;
int end = text.length() - 1;
while (start < end)
{
if (text[start] != text[end])
{
palindrome = false;
break;
}
start++;
end--;
}
if (palindrome)
{
cout << "Palindrome";
}
else
{
cout << "Not Palindrome";
}
return 0;
}
Example 1
Output: Palindrome
Example 2
Output: Not Palindrome
Logic
Step 1: Take a string as input.
Step 2: Set start = 0.
Step 3: Set end = length - 1.
Step 4: Compare characters from both ends.
Step 5: If any characters are different, it is not a palindrome.
Step 6: Move start forward and end backward.
Day 13 Quick Revision
char → Stores a single character
string → Stores a sequence of characters
cin → Takes single-word input
getline() → Takes complete line input
Vowels → A, E, I, O, U
Consonant → Alphabet other than vowels
String traversal → Accessing characters one by one
Palindrome → Same forward and backward
start = 0 → First character index
end = length - 1 → Last character index
Functions
Learn functions, declaration, definition, parameters and return values in C++.
Functions
A function is a block of code that performs a specific task. Functions help us divide a large program into smaller and reusable parts.
A function runs when it is called.
Example: Simple Function
#include <iostream>
using namespace std;
void greet() {
cout << "Hello C++";
}
int main() {
greet();
return 0;
}
Hello C++
Function Declaration and Definition
Function declaration tells the compiler about the function before it is used. Function definition contains the actual code of the function.
A function can be declared before the main() function and defined later.
Example: Declaration and Definition
#include <iostream>
using namespace std;
// Function Declaration
void greet();
// Function Definition
void greet() {
cout << "Welcome to C++";
}
int main() {
greet();
return 0;
}
Welcome to C++
Function Parameters
Parameters are variables used to pass data to a function. They allow a function to work with different values.
Example: Function with Parameters
#include <iostream>
using namespace std;
void add(int a, int b) {
cout << "Sum = " << a + b;
}
int main() {
add(10, 20);
return 0;
}
Sum = 30
Return Value
A function can return a value to the place where it was called. The return statement is used to send a value back from a function.
Example: Function with Return Value
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
cout << "Sum = " << result;
return 0;
}
Sum = 30
Quick Revision
| Topic | Meaning |
|---|---|
| Function | Block of code for a specific task |
| Declaration | Tells compiler about the function |
| Definition | Contains the actual function code |
| Parameter | Used to pass data to a function |
| return | Sends a value back from the function |
Functions, Arrays & Strings
Learn call by value, call by reference, recursion, arrays and strings in C++.
Call by Value
In Call by Value, a copy of the actual value is passed to the function. Changes made inside the function do not affect the original variable.
Example: Call by Value
#include <iostream>
using namespace std;
void change(int x) {
x = 20;
}
int main() {
int a = 10;
change(a);
cout << "a = " << a;
return 0;
}
a = 10
Call by Reference
In Call by Reference, a reference to the original variable is passed to the function. Changes made inside the function affect the original variable.
Example: Call by Reference
#include <iostream>
using namespace std;
void change(int &x) {
x = 20;
}
int main() {
int a = 10;
change(a);
cout << "a = " << a;
return 0;
}
a = 20
Recursion
Recursion is a process in which a function calls itself. A base condition is required to stop the recursive calls.
Example: Recursion
#include <iostream>
using namespace std;
void count(int n) {
if (n == 0)
return;
cout << n << endl;
count(n - 1);
}
int main() {
count(5);
return 0;
}
5 4 3 2 1
One-Dimensional Arrays
A one-dimensional array stores multiple values of the same data type in a single sequence.
Example: One-Dimensional Array
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << numbers[i] << endl;
}
return 0;
}
10 20 30 40 50
Two-Dimensional Arrays
A two-dimensional array stores data in rows and columns. It is commonly used to represent tables and matrices.
Example: Two-Dimensional Array
#include <iostream>
using namespace std;
int main() {
int numbers[2][2] = {
{10, 20},
{30, 40}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << numbers[i][j] << " ";
}
cout << endl;
}
return 0;
}
10 20 30 40
Strings
A string is used to store a sequence of characters or text. In C++, the string data type is commonly used for text.
String Example 1: Store a Name
#include <iostream>
using namespace std;
int main() {
string name = "Rahul";
cout << "Name = " << name;
return 0;
}
Name = Rahul
String Example 2: Store a Sentence
#include <iostream>
using namespace std;
int main() {
string message = "I am learning C++";
cout << message;
return 0;
}
I am learning C++
String Example 3: Take String Input
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello " << name;
return 0;
}
Enter your name: Amit Hello Amit
String Example 4: Find String Length
#include <iostream>
using namespace std;
int main() {
string text = "Hello";
cout << "Length = " << text.length();
return 0;
}
Length = 5
String Example 5: Join Two Strings
#include <iostream>
using namespace std;
int main() {
string firstName = "Rahul";
string lastName = "Sharma";
string fullName = firstName + " " + lastName;
cout << "Full Name = " << fullName;
return 0;
}
Full Name = Rahul Sharma
Quick Revision
| Topic | Key Point |
|---|---|
| Call by Value | Copy of value is passed |
| Call by Reference | Reference of original variable is passed |
| Recursion | Function calls itself |
| 1D Array | Stores data in a single sequence |
| 2D Array | Stores data in rows and columns |
| String | Stores characters or text |
MCQ Test Series
Test your understanding after completing the lessons.
C++ Introduction Test
Basic questions based on Day 01.
C++ Data Types Test
Basic questions based on Day 02 — Data Types and Arithmetic Operations.
C++ Variables & Data Types Test
Basic questions based on Day 03 — char, string and float.
C++ Operators & Swapping Test
Basic questions based on Day 04 — Operators and swapping two numbers.
C++ Variables, Operators & Input/Output Test
Questions based on Day 05 — Variables, Constants, Operators, cin and cout.
C++ Conditional Statements Test
Questions based on Day 06 — XOR Swap, if, if-else, Nested if, else-if Ladder and switch.
C++ Loops Test
Questions based on Day 07 — for, while and do-while loops.
C++ Break, Continue & Lambda Test
Questions based on Day 08 — break, continue and lambda expressions.
C++ Functions Test
Questions based on Day 09 — functions, parameters and return values.
C++ Functions, Arrays & Strings Test
Questions based on Day 10 — Call by Value, Call by Reference, Recursion, Arrays and Strings.
Practice Area
Practice questions coming soon.
After completing each day, practice questions will be added here.