Object-Oriented Programming (OOP) is a way of writing programs. It organizes software around objects instead of only actions and logic.An object contains two main things:
Data (called attributes or properties)
Functions (called methods or behaviors)
OOP is used in many modern programming languages such as Java, C++, Python, Ruby, and C#.The main goal of OOP is to make programs easier to manage, reuse, and maintain. In OOP, code is divided into small parts called objects. Each object represents a real-world idea or thing. This makes complex programs easier to understand and develop.
Another important aim of OOP is to combine data and the functions that work on that data. This helps protect the data from being accessed directly by other parts of the program.In C++, OOP provides a new way to design programs using classes and objects. A class is like a blueprint, and an object is created from that blueprint. Using classes and objects, programmers can represent real-world things and their behaviors in a program.
Features of OOP
C++ is a powerful and fast programming language. It fully supports Object-Oriented Programming (OOP). It combines OOP features with the traditional C programming style. This helps developers write clean, reusable, and easy-to-maintain programs.
Below are the main features of OOP in C++:
Class: A class is a blueprint or model for creating objects. It defines the data (called data members) and the functions (called methods) that the objects will have.
2. Object: An object is created from a class. It is an instance of a class. Each object has its own data and can use the functions defined in the class.
Example Program (C++)
#include <iostream>
using namespace std;
class Car {
public:
string brand;
string model;
void display_info() {
cout << "Brand: " << brand << ", Model: " << model << endl;
}
};
int main() {
// Creating an object of the Car class
Car myCar;
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.display_info(); // Output: Brand: Toyota, Model: Corolla
return 0;
}
In this program, Car is a class that contains two data members, brand and model, and one function called display_info(). The class works like a blueprint for creating car objects. Inside the main() function, an object named myCar is created from the class Car. After creating the object, the values “Toyota” and “Corolla” are assigned to the brand and model of myCar. Then, the display_info() function is called using the object. This function prints the brand and model of the car on the screen. This example shows how a class and object work together in C++.
2. Encapsulation Encapsulation is one of the main principles of Object-Oriented Programming (OOP). It means combining data (attributes) and the functions (methods) that work on that data into a single unit called a class. In simple words, a class keeps related data and functions together. Encapsulation also protects the data by restricting direct access to it. This means the internal data of an object cannot be changed directly from outside the class. Instead, it can only be accessed or modified through special functions defined inside the class. This helps keep the data safe and makes the program more secure and organized.
In simple terms, encapsulation is like keeping your data inside a box, which is the class. You allow other parts of the program to use or change the data only through special functions called methods, instead of letting them access the data directly. This keeps the data safe and organized.
3. Abstraction
Abstraction is an important idea in Object-Oriented Programming (OOP). It means hiding the complicated details of a system and showing only the important parts. In simple words, abstraction lets you focus on what an object does rather than how it does it.
In C++, abstraction is usually done using abstract classes and pure virtual functions. An abstract class is like a template or interface for other classes. It defines what functions a class should have but does not provide full details about how they work.
A pure virtual function is a function declared in an abstract class without any implementation. Derived classes that inherit from the abstract class must provide their own implementation of this function. You cannot create an object directly from an abstract class. It is meant to be inherited by other classes.
4. Inheritance Inheritance is another core concept of OOP. It allows you to create a new class, called a derived class, from an existing class, called a base class. The derived class gets all the attributes (data members) and methods (functions) of the base class. This helps in reusing code and extending functionality.
You can also modify or add new behaviors in the derived class. The access to inherited members depends on the access specifiers used during inheritance: public, protected, or private.
5. Polymorphism Polymorphism is a key feature of OOP. It allows a single interface or function to work with different types of data. The term “polymorphism” means “many forms.” This feature makes programs more flexible because the same function can behave differently depending on which object calls it.
Polymorphism is commonly implemented in C++ through function overloading, operator overloading, and virtual functions.
In simple terms, polymorphism allows objects from different classes to be treated as if they belong to a common base class. At the same time, each object can still use its own special methods. This means we don’t need to know the exact class of an object. We can use a base class pointer or reference to work with different objects in the same way, making programs simpler and more flexible
Application of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is widely used in software development because it can model real-world entities, make code reusable, and improve maintainability. OOP is especially helpful for creating large and complex software, where modularity, scalability, and easy maintenance are important.
Here are some common applications of OOP in different areas:
1. Software Development OOP is the foundation of many modern programming languages, frameworks, and libraries. Some key applications include:
a. Game Development In game development, OOP is used to represent different game entities like players, enemies, weapons, and levels. Each object, such as a character or weapon, has attributes (like health or damage) and methods (like attack or move) that define its behavior.
b. Simulation Systems OOP is useful in simulations where different entities interact with each other. Examples include traffic systems, weather simulations, or population models.
2.Web Development In web development, OOP is used to create and manage complex websites and applications.
a. Web Frameworks Many modern web frameworks, like Django, Ruby on Rails, and ASP.NET, use OOP principles to organize web application components such as users, forms, databases, and views.
Example: In Django, models are Python classes that represent database tables. Each instance of a model represents a record in the database. A User class might have attributes like username and password, and methods like authenticate() and login().
b. Content Management Systems (CMS) CMS platforms like WordPress and Joomla are built using OOP. Different types of content, such as posts, pages, and comments, are treated as objects with specific attributes and methods.
Example: A Post class in WordPress can have properties like author, content, and published_date, and methods like publish(), edit(), or delete().
3. Mobile Application Development OOP is very important in mobile app development. User interfaces, app behaviors, and interactions are all modeled as objects.
a. Android and iOS Apps Android apps (using Java or Kotlin) and iOS apps (using Swift or Objective-C) use OOP to represent components such as views, controllers, data models, and network operations.
4. Database Management Systems (DBMS) Object-Oriented Database Management Systems (OODBMS) store data as objects instead of tables. This makes them align closely with OOP principles and easier to integrate with object-oriented programs.
5. Artificial Intelligence (AI) and Machine Learning (ML) OOP is often used in AI and ML systems, where objects can represent different entities, models, or processes. This makes it easier to organize complex algorithms and manage interactions between various parts of the system.
Structured VS Object-Oriented Programming
Structured Programming and Object-Oriented Programming (OOP) are two different paradigms used in software development. Each has its own approach to organizing and solving programming problems. Here is a detailed comparison of the two:
Structured Programming
Object-Oriented Programming (OOP)
A programming paradigm that focuses on functions and procedures to solve problems.
A programming paradigm based on objects that contain data and methods.
Follows a top-down approach.
Follows a bottom-up approach.
Divides program into functions or procedures.
Divides program into classes and objects.
Focuses on functions and logic.
Focuses on objects and data.
Data and functions are separate.
Data and functions are combined in objects.
Less secure; no data hiding.
More secure due to encapsulation and data hiding.
Limited code reusability.
High code reusability through inheritance and polymorphism.
Difficult to maintain large programs.
Easier to maintain and modify large programs.
Examples: C, Pascal
Examples: Java, C++, Python
Best for small and medium-sized programs.
Best for large and complex applications.
Tokens and Character Sets in C++
In C++, tokens and character sets are essential concepts for understanding how the language syntax works.
1. Tokens in C++ A token is the smallest meaningful unit of a C++ program. The compiler breaks the program into tokens during compilation. There are six main types of tokens in C++:
a. Keywords Keywords are reserved words that have special meanings in C++ and cannot be used as identifiers (such as variable names). Examples:int, float, class, return, if, while, for.
b. Identifiers
Identifiers are names used to identify variables, functions, classes, arrays, and other user-defined items in a program. They help programmers give meaningful names to different elements in the code.
Rules for Identifiers:
Must begin with a letter (a–z, A–Z) or an underscore (_).
May contain letters, digits (0–9), and underscores.
Cannot start with a number.
Cannot be a keyword.
Are case-sensitive (e.g., total and Total are different).
Literals represent constant values that appear directly in the code. These values do not change during program execution.
Types of Literals:
Integer literals: 42, -100
Floating-point literals: 3.14, 2.71828f
Character literals: 'a', '1'
String literals: "Hello, World!"
Boolean literals: true, false
Null pointer literal: nullptr
d. Operators
Operators are symbols that perform operations on variables and values. They are used to manipulate data and evaluate expressions.
Types of Operators:
Arithmetic Operators: +, -, *, /
Relational Operators: ==, !=, <, >
Logical Operators: &&, ||, !
Bitwise Operators: &, |, ^, ~
e. Punctuation (Separators)
Punctuation symbols, also called separators, are used to separate statements, blocks of code, and other elements in a program.
Examples:
Semicolon ( ; ) – Terminates a statement.
Comma ( , ) – Separates variables or function arguments.
Period ( . ) – Accesses members of an object.
Parentheses ( ) – Used in function calls and expressions.
Curly brackets ( { } ) – Define blocks of code.
Square brackets [] (used for array subscripts)
Colon : (used in various constructs like case labels, inheritance)
f. Comments
Comments are used to explain or document the code. They help programmers understand the program better. Comments are ignored by the compiler, which means they do not affect the execution of the program.
There are two types of comments in C++:
Single-line comment: Single-line comment Begins with // and continues to the end of the line. Example: // This is a comment
Multi-line comment: Multi-line comment begins with /* and ends with */. It can span multiple lines. Example: /* This is a comment */
2.Character Sets in C++ Character set is the combination of the English language (Alphabets and Whitespaces) and mathematical symbols (Digits and Special symbols). Character Setmeans that the characters and symbols that a C++ Program can understandand accept. These are grouped to form the commands, expressions, words,c-statements, and other tokens for the C++ Language.
1. Alphabets
Alphabets include the letters A to Z and a to z. C language is case-sensitive, which means small letters and capital letters are treated differently. For example, A and a are not the same in C.Alphabets are used to write:
C statements
Variable names
Character constants
There are 26 letters in the English alphabet, and all are used in C programming.
2. Digits Digits in the C language include numbers from 0 to 9. These digits can be used alone or combined to form numbers like 10, 25, or 100. Digits are mainly used to write numeric constants and assign numerical values to variables. There are a total of 10 digits used in C programming.
3. Special Symbols Special symbols include all keyboard characters except alphabets, digits, and white spaces. They are used to write different types of statements in C. For example, +, -, and * are used for arithmetic operations, <, > and == are used for comparison, = is used for assignment, and &&, || are used for logical operations. About 30 special symbols are used in C programming.
4. White Spaces White spaces include blank space, newline, tab, and carriage return. They make the program neat and easy to read. C compilers ignore white space characters while compiling the program.
Data Types
In C++, data types define the type of data that a variable can store. C++ provides different built-in data types, which are grouped into primitive (simple) types, derived types, and user-defined types. Understanding data types helps manage memory properly and prevents errors in programs.
1. Primitive Data Types Primitive data types are basic built-in types in C++. These include integer types, floating-point types, character types, and boolean types.
a. Integer Types Integer types are used to store whole numbers. C++ provides different integer types based on size and range.
int: A basic integer type. It is usually 4 bytes. Example: int x = 10;
short: A smaller integer type, usually 2 bytes. Example: short s = 100;
long: A larger integer type, usually 4 or 8 bytes depending on the system. Example: long l = 1000000;
b. Floating-Point Types
Floating-point types are used to store real numbers, which are numbers with decimal or fractional parts. In C++, the float type is a single-precision number and usually takes 4 bytes of memory, for example, float f = 3.14f;. The double type is a double-precision number and usually takes 8 bytes of memory, which allows it to store more accurate and larger decimal values, for example, double d = 3.14159265359;.
c. Character Types
Character types are used to store single characters or small integer values based on ASCII codes. The char type usually takes 1 byte of memory and can store characters like ‘A’, ‘b’, or ‘5’, for example, char c = 'A';. There are also signed char and unsigned char, which are special versions of char that store either negative and positive values or only positive values, such as signed char sc = -50; and unsigned char uc = 250;.
d. Boolean Type The bool type is used to store logical values in C++. It can store only two values: true or false. This type is commonly used in decision-making statements and conditions. For example, bool isTrue = true; stores a true value in a boolean variable.
2. Derived Data Types Derived data types are created from primitive data types. They are formed using basic data types and are defined by the user according to program needs. Examples of derived data types include arrays, pointers, references, and functions.
a. Array An array is a collection of elements of the same data type stored in consecutive memory locations. It is used to store multiple values in a single variable name. For example, int arr[5] = {1, 2, 3, 4, 5}; creates an array of five integers.
b. Pointer A pointer is a special variable that stores the memory address of another variable. It helps in dynamic memory allocation and efficient handling of data.
Example: int x = 10; int* p = &x; In this example, p is a pointer to an integer, and it stores the memory address of the variable x
3. User-Defined Data Types User-defined data types are created by the programmer to make the program more organized and meaningful. These types help in building complex data structures according to the needs of the program.
a. Struct (Structure)
A struct is a user-defined data type that allows grouping different types of variables under one name. It helps store related data together, such as name, age, and marks of a student.
b. Class
A class is similar to a struct, but it can also include functions (called methods) and supports access control like private and public members. A class is the main foundation of object-oriented programming (OOP) in C++.
c. Enum (Enumeration)
An enum is a user-defined data type that contains a set of named integer constants. It is used to give meaningful names to constant values, making the program easier to read and understand.
Format Specific
In C++, formatting refers to controlling how data is displayed on the screen or output stream. It allows programmers to present numbers, characters, and strings in a clear and organized way. Formatting is usually done using the iostream library with std::cout, and C++ provides several methods, including stream manipulators, printf-style formatting, and I/O flags.
1. Using iostream Stream Manipulators (C++ Style)
C++ offers stream manipulators to format output in a readable and type-safe way.
a. std::setw(int width) — Set Field Width
The setw() manipulator sets the minimum width of the next printed field. If the value is smaller than the specified width, it is padded with spaces (by default, on the left). This is useful for aligning numbers or text in tabular output.
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setw(5) << 42 << endl; // Prints " 42" with spaces added
return 0;
}
b. std::setfill(char ch) — Fill Character
The setfill() manipulator is used to specify which character will be used to fill the extra space when the field width (set by setw) is larger than the data. By default, spaces are used, but setfill() allows you to use any character.
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int num = 42;
cout << setw(5) << setfill('*') << num << endl; // Output: "**42"
return 0;
}
c.
std::left, std::right, std::internal — Align Text These manipulators control the alignment of text in a field:
std::left: Left-aligns the text.
std::right: Right-aligns the text.
std::internal: Aligns the text with padding between the sign and the number.
Example :
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159;
cout << fixed << setprecision(2) << pi << endl; // Output: "3.14"
cout << scientific << setprecision(2) << pi << endl; // Output: "3.14e+00"
return 0;
}
d. std::fixed and std::scientific — Floating Point Format
These manipulators control the way floating-point numbers are printed:
std::fixed: Forces fixed-point notation (i.e., shows a fixed number of decimal places).
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159;
cout << fixed << setprecision(2) << pi << endl; // Output: "3.14"
cout << scientific << setprecision(2) << pi << endl; // Output: "3.14e+00"
return 0;
}
e. std::setprecision(int n) — Control Decimal Precision
The setprecision() manipulator sets the number of significant digits for floating-point numbers.
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.141592653589793;
cout << setprecision(4) << pi << endl; // Output: "3.142"
return 0;
}
2. Using printf-style Formatting (C-Style) While C++ provides stream manipulators for formatting, you can also use C-style formatting with the printf function (from <cstdio>). This style uses format specifiers to control output.
a. Common Format Specifiers
Specifier
Meaning
%d or %i
Integer
%f
Floating-point number
%c
Character
%s
String
%x
Hexadecimal (lowercase)
%X
Hexadecimal (uppercase)
%o
Octal
%p
Pointer (address)
%e
Scientific notation
Example :
#include <cstdio>
int main() {
int num = 42;
double pi = 3.14159;
char ch = 'A';
printf("Integer: %d\n", num); // Output: Integer: 42
printf("Floating-point: %.2f\n", pi); // Output: Floating-point: 3.14
printf("Character: %c\n", ch); // Output: Character: A
return 0;
}
Basic Input/ Output
In C++, input and output are handled using cin (keyboard input) and cout (screen output) from the <iostream> library. cout displays messages, cin reads user input, and endl adds a newline while flushing the output.
Output in C++: std::cout
The cout object is used to send output to the console. The insertion operator << sends data to cout, and endl adds a newline while flushing the output buffer.
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
The cout object is used for console output, the << operator (insertion operator) sends data to the cout stream, and endl inserts a newline while also flushing the output buffer. For example, an integer, a floating-point number, and a character can be displayed as follows:
#include <iostream>
using namespace std;
int main() {
int num = 10;
double pi = 3.14159;
char letter = 'A';
cout << "Integer: " << num << endl;
cout << "Pi: " << pi << endl;
cout << "Character: " << letter << endl;
return 0;
}
2. Input in C++: cin The cin object is used to read input from the user, usually from the keyboard. The extraction operator >> sends the input into a variable. For example, a program can prompt the user to enter their age using cout, read the value with cin, and then display it back
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You entered: " << age << endl;
return 0;
}
cin reads data from the user, while >> is the extraction operator that stores the input in a variable.
Example Reading and Printing Multiple Inputs You can read and print multiple inputs in C++ using cin for input and cout for output. For instance, a program can ask the user to enter their name and age, store the values in variables, and then display them:
#include <iostream>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
cin >> name; // Reads a single word (up to the first space)
cout << "Enter your age: ";
cin >> age; // Reads an integer value
cout << "Name: " << name << ", Age: " << age << endl;
return 0; }
In this example, cin reads the user’s input, storing it in variables, and cout prints the formatted result on the screen.
3. Basic Example: Input and Output Together
You can take multiple inputs from the user and display them in a formatted way using cin, getline, and cout. For example, a program can ask the user for their name, age, and height, and then print the information neatly:
#include <iostream>
#include <string>
#include <iomanip> // For setw and formatting manipulators
using namespace std;
int main() {
string name;
int age;
double height;
// Input from user
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
cin >> age;
cout << "Enter your height (in meters): ";
cin >> height;
// Output formatted data
cout << "\n-- User Information --" << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << " years" << endl;
cout << "Height: " << fixed << setprecision(2) << height << " meters" << endl;
return 0;
}
In this example, getline(cin, name) reads a full line including spaces for the name, cin reads numeric inputs, and cout displays the formatted output. The fixed and setprecision(2) manipulators ensure the height is displayed with two decimal places.
Basic Program Structure
A C++ program has some important parts. These parts include header files, the main() function, and sometimes other functions or variables.C++ programs follow a clear and organized structure. The program always starts running from the main() function.
Here is a simple overview of the main parts and their usual order in a C++ program:
1. Program Structure Breakdown
a. Preprocessor Directives Preprocessor directives are special instructions that are processed before the program is compiled. They usually include header files, which contain useful functions and features needed in the program.
#include <iostream> // Header for input and output
#include: This directive tells the preprocessor to include the specified file before the program is compiled. In this example, <iostream> is included to use standard input and output features like cout and cin.
b. Namespace Declaration In C++, the standard library (such as std::cout, std::cin, etc.) is placed inside a namespace called std. You can write std:: before each standard library object, or you can declare that you are using the standard namespace.
using namespace std; // Avoids writing 'std::' every time
using namespace std;: This statement allows you to use standard library features without adding the std:: prefix each time.
c. The main() Function The main() function is the starting point of every C++ program. Program execution always begins from the main() function. The return type of main() is usually int, which means it returns an integer value to the operating system when the program ends.
int main() { // Code for execution goes here return 0; // 0 means successful execution }
int main(): Defines the main function where program execution starts.
return 0;: Returns an integer value, usually 0, to indicate that the program finished successfully.
d. Statements and Declarations
Inside the main() function (or any other function), you can declare variables, perform calculations, control the flow of the program, and display output.
Declarations: These are used to define variables or objects before using them in the program.
Statements: These are lines of code that perform specific actions, such as assigning values to variables, doing calculations, or printing output to the screen.
2. Basic C++ Program Example
Let’s look at a simple program to understand the basic structure of a C++ program:
#include <iostream> // Include the iostream header for input and output using namespace std; // Use the standard namespace to avoid writing std:: int main() { // Program execution starts here int num1, num2, sum; cout << "Enter two numbers: "; // Display message cin >> num1 >> num2; // Take input from user sum = num1 + num2; cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl; return 0; // Return 0 to show successful execution }
Explanation:
This program includes the <iostream> header to use input and output features. The main() function is where the program starts. Inside it, three variables are declared. The program takes two numbers from the user, adds them, and stores the result in sum. Finally, it displays the result and returns 0 to show successful execution.
Control Statements in C++
Control Statements in C++ are used to control how a program runs. They help the program make decisions, repeat tasks, or change the flow of execution based on certain conditions. There are three main types of control statements in C++:
Decision-making statements are also called conditional or branching statements. They allow the program to execute different blocks of code depending on certain conditions. These conditions are checked as either true or false. Based on the result, the program chooses the appropriate path.
The main decision-making statements in C++ are if, else-if, and switch.
a. if Statement The if statement executes a block of code only if the given condition is true. It allows the program to take action when a specific condition is satisfied.
Syntax:
if (condition) { // Code to execute if condition is true }
In this example, the code inside the if block will be executed because the condition (num >0) is true.
b. if-else Statement The if-else statement provides an alternative
block of code to execute if the condition is false. The else statement is used in conjunction with an if statement to specify a block of code that should be executed when the condition in the if statement is false. Syntax if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
Here, since num is not greater than 0, the program will print “The number is not positive.”
c. Else-if Statement
The else-if statement is used to check multiple conditions one by one. It is helpful when there are more than two possible conditions. The program checks each condition in order. When one condition becomes true, its block of code is executed, and the rest are skipped. If none of the conditions are true, the else block runs.
Syntax:
if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition2 is true } else if (condition3) { // Code to execute if condition3 is true } else { // Code to execute if none of the above conditions are true }
Example: int num = 0; if (num > 0) { cout << "The number is positive." << endl; } else if (num < 0) { cout << "The number is negative." << endl; } else { cout << "The number is zero." << endl; }
Explanation: In this program, the variable num is 0. The if statement checks if it is greater than 0 — it’s not. The else-if statement checks if it is less than 0 — it’s not. Since neither condition is true, the else block runs, and the program prints:
d. Switch Statement
The switch statement is used as an alternative to multiple if-else conditions when you want to compare a single variable with several possible values. It makes the code more readable, especially when there are many options.
A switch statement lets the program choose one of many code blocks to execute based on the value of an expression. If none of the cases match, the default block runs.
Syntax:
switch (expression) { casevalue1: // Code to execute if expression == value1 break; casevalue2: // Code to execute if expression == value2 break; casevalue3: // Code to execute if expression == value3 break; default: // Code to execute if no case matches }
In a switch statement, each case defines a possible value to compare with the expression. The break statement ends the current case, preventing the program from executing the next cases unintentionally. The default block runs when none of the specified case values match the expression, providing a fallback option.
Explanation: Here, the variable day is 3. The switch statement compares day with each case. Since day == 3, the program executes the code under case 3 and prints:
Example Program: Using Multiple Decision-Making Statements in C++
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; if (num > 0) // if-else statement { cout << "The number is positive." << endl; } else if (num < 0) { cout << "The number is negative." << endl; } else { cout << "The number is zero." << endl; } switch (num) // switch statement { case 1: cout << "The number is one." << endl; break; case 2: cout << "The number is two." << endl; break; default: cout << "The number is neither one nor two." << endl; } return 0; }
In this program, the user enters a number. The if-else statement checks whether the number is positive, negative, or zero. Then, the switch statement checks if the number is 1 or 2. If it is not 1 or 2, the default case runs.
2. Looping Statement
In C++, looping statements allow you to execute a block of code repeatedly based on a given condition. Loops are very useful for performing repetitive tasks, processing data, and controlling the flow of a program. There are three main types of loops in C++: for, while, and do-while.
a. For Loop
The for loop is used to execute a block of code a specific number of times. It is generally used when the number of repetitions is known in advance. The for loop combines initialization, condition checking, and increment or decrement in a single line.
Syntax
for (initialization; condition; increment/decrement) { // Code to be executed }
Problem: Calculate the sum of integers from 1 to n by using for loop.
#include <iostream> using namespace std; int main() { int n = 10; int total = 0; for (int i = 1; i <= n; i++) { total += i; } cout << "The sum is: " << total << endl; return 0; }
While Loop in C++
A while loop is used to run a block of code again and again as long as a given condition is true. It is called a pre-test loop because the condition is checked before the loop executes. If the condition is false at the beginning, the code inside the loop will not run even once.
Syntax
while (condition) { // Code to be executed }
Example #include <iostream> using namespace std; int main() { int i = 1; // Loop while i is less than or equal to 5 while (i <= 5) { cout << "Iteration " << i << endl; i++; // Increment i after each iteration } return 0; }
do–While Loop
The do–while loop is a looping statement in C++ that ensures the code inside the loop is executed at least once, regardless of whether the condition is true or false. In this loop, the program first executes the code block and then checks the condition. Unlike the while loop, where the condition is checked before executing the code, the do–while loop checks the condition after the execution of the loop body. Because the condition is tested after the code runs, it is called a post-test loop.
If the condition is true, the loop continues to execute again. If the condition becomes false, the loop stops.
Syntax
do { // Code to be executed } while (condition);
Example:
#include <iostream> using namespace std; int main() { int i = 1; // Loop runs at least once and continues while i <= 5 do { cout << "Iteration " << i << endl; i++; } while (i <= 5); return 0; }
Explanation
In this program, the variable i is initialized to 1. The do–while loop first executes the statements inside the loop and prints “Iteration” along with the value of i. After printing, the value of i is increased by 1 using i++. Then the condition (i ≤ 5) is checked. If the condition is true, the loop continues; otherwise, it stops. As a result, the program prints Iteration 1 to Iteration 5.
3. Statements
In C++, jump statements are used to control the flow of execution by jumping to a different part of the program. These statements allow you to manipulate the loop execution, skip certain iterations, and exit the loops prematurely when the specified conditions are met. The primary jump statements in C++ are break, continue, goto, and return. Each serves a different purpose in altering the flow of control within loops, conditional blocks, or functions.
a. Break Statement The break statement is used to exit from a loop or a switch statement prematurely, regardless of whether the loop or switch condition has been satisfied.
Use of Break Statement The break statement in C++ is used to terminate a loop or switch statement immediately. When the program encounters a break, it exits the loop or switch block and continues execution from the next statement after it.
The break statement can be used inside loops such as for, while, and do-while to exit the loop before completing all iterations.
Flow chart of break statements
Example: #include <iostream> using namespace std; int main() { for(int i = 1; i <= 10; i++) { if(i == 5) { break; // stops the loop when i becomes 5 } cout << i << " "; } return 0; }
Break statement in the for loop:
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit the loop when i equals 5 } cout << i << " "; } return 0; } Output: 1 2 3 4
Break Statements in Switch Statements
#include <iostream> using namespace std; int main() { int day = 3; switch(day) { case 1: cout << "Sunday"; break; case 2: cout << "Monday"; break; case 3: cout << "Tuesday"; break; case 4: cout << "Wednesday"; break; default: cout << "Invalid day"; } return 0; }
Output : Tuesday
b. Continue Statement
The continue statement is used inside loops to skip the rest of the current iteration and move to the next iteration of the loop. When the continue statement is encountered, the remaining statements inside the loop for that iteration are skipped, and the loop proceeds with the next iteration.
uses of continue loop:
In loops: Skips the current iteration and continues with the next iteration of the loop.
Continue in C++
Example of continue statement
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip the iteration when i equals 3 } cout << i << " "; } return 0; } Output: 1 2 4 5
C. Goto Statement
The goto statement is used to jump to a labeled statement in a C program. It transfers the program control directly to the specified label. Although it is generally discouraged because it can make programs harder to read and maintain, it may still be useful in some special situations where structured control statements (like loops and conditionals) are not convenient.
Usage
It can be used in any part of the program to jump to a specific label defined elsewhere in the code.
Fig.: Go to Statement
Example of Go to Statement
#include <iostream> using namespace std; int main() { int i = 1; loop_start: if (i > 5) { goto end; // Jump to 'end' label when i exceeds 5 } cout << i << " "; i++; goto loop_start; // Jump back to 'loop_start' label end: cout << "\nEnd of loop"; return 0; }
Explanation: This C++ program uses a for loop from 1 to 5. When the value of i becomes 3, the continue statement skips that iteration, so 3 is not printed. All other numbers are printed, resulting in the output 1 2 4 5.
D. Return Statement The return statement is used to exit from a function and optionally return a value to the calling function. It is primarily used in non-void functions to return a value, but in main(), it is used to indicate the program’s exit status.
Usage of return statement
• In functions: Exits the function and optionally returns a value. • In main(): Returns an integer exit code to the operating system (0 for successful execution).
Example of Return statement
#include <iostream> using namespace std; int add(int a, int b) { // Function to add two numbers return a + b; // Return the sum of a and b } int main() { int result = add(3, 4); // Call the add function cout << "The sum is: " << result << endl; return 0; // Indicates successful execution }
Project Work solution
Write a program that uses for loop to print the numbers from 1 to 10.
#include <iostream> using namespace std; int main() { // Loop from 1 to 10 for (int i = 1; i <= 10; i++) { cout << i << " "; } cout << endl; // Move to the next line after printing all numbers return 0; }
Write a program that uses while loop to print the even numbers from 2 to 10.
#include <iostream> using namespace std; int main() { int i = 2; // Start from the first even number while (i <= 10) { cout << i << " "; i += 2; // Increment by 2 to get the next even number } cout << endl; // Move to the next line after printing return 0; }
Write a program that uses do-while loop to repeatedly ask the user to enter a number and then print out whether the number is even or odd until the user enters 0.
#include <iostream> using namespace std; int main() { int num; do { // Ask the user to enter a number cout << "Enter a number (0 to exit): "; cin >> num; if (num == 0) { cout << "Exiting the program." << endl; break; // Exit the loop if the number is 0 } // Check if the number is even or odd if (num % 2 == 0) { cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; } } while (true); // Repeat indefinitely until 0 is entered return 0; }
Write a program that uses for loop to calculate the sum of the first 10 natural numbers.
#include <iostream> using namespace std; int main() { int num; do { // Ask the user to enter a number cout << "Enter a number (0 to exit): "; cin >> num; if (num == 0) { cout << "Exiting the program." << endl; break; // Exit the loop if the number is 0 } // Check if the number is even or odd if (num % 2 == 0) { cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; } } while (true); // Repeat indefinitely until 0 is entered return 0; }
Write a program that uses while loop to calculate the product of the first 5 natural numbers.
#include <iostream> using namespace std; int main() { int i = 1; // Start from 1 int product = 1; // Initialize product as 1 while (i <= 5) { product *= i; // Multiply current number to product i++; // Move to the next number } cout << "The product of the first 5 natural numbers is: " << product << endl; return 0; }
Write a program that uses do-while loop to repeatedly ask the user to enter a number and then print out whether the number is even or odd until the user enters 0.
#include <iostream> using namespace std; int main() { int num; do { // Ask the user to enter a number cout << "Enter a number (0 to exit): "; cin >> num; // Check if the user wants to exit if (num == 0) { cout << "Exiting the program." << endl; break; // Exit the loop } // Determine if the number is even or odd if (num % 2 == 0) { cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; } } while (true); // Repeat the loop until 0 is entered return 0; }
Write a program that takes an integer input from the user and checks if it’s positive, negative, or zero using if-else ladder statement.
#include <iostream> using namespace std; int main() { int num; // Take input from the user cout << "Enter an integer: "; cin >> num; // Check if the number is positive, negative, or zero if (num > 0) { cout << num << " is positive." << endl; } else if (num < 0) { cout << num << " is negative." << endl; } else { cout << "The number is zero." << endl; } return 0; }
Write a program that takes character input from the user and checks if it’s a vowel, consonant, digit, or special character using if-else ladder statement.
#include <iostream> using namespace std; int main() { char ch; // Take character input from the user cout << "Enter a character: "; cin >> ch; // Check if the character is a vowel if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { cout << ch << " is a vowel." << endl; } // Check if the character is a consonant (alphabet but not a vowel) else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { cout << ch << " is a consonant." << endl; } // Check if the character is a digit else if (ch >= '0' && ch <= '9') { cout << ch << " is a digit." << endl; } // If it is none of the above, it is a special character else { cout << ch << " is a special character." << endl; } return 0; }
Write a program that takes character input from the user and checks whether it is a vowel or consonant using switch statement.
#include <iostream> using namespace std; int main() { char ch; // Take character input from the user cout << "Enter an alphabet character: "; cin >> ch;
// Convert uppercase letters to lowercase for simplicity if (ch >= 'A' && ch <= 'Z') { ch = ch + ('a' - 'A'); // Convert to lowercase } // Check if the character is a vowel or consonant switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': cout << ch << " is a vowel." << endl; break; default: // Check if the character is an alphabet letter if (ch >= 'a' && ch <= 'z') { cout << ch << " is a consonant." << endl; } else { cout << "Invalid input! Not an alphabet character." << endl; } } return 0; }
Write a program that takes user input of a number and checks if it’s divisible by 5, 3, 2, or not using a switch statement.
#include <iostream> using namespace std;
int main() { int num;
// Take number input from the user cout << "Enter a number: "; cin >> num;
// Use modulo to determine divisibility switch (0) { case 0: if (num % 5 == 0) { cout << num << " is divisible by 5." << endl; break; } case 1: if (num % 3 == 0) { cout << num << " is divisible by 3." << endl; break; } case 2: if (num % 2 == 0) { cout << num << " is divisible by 2." << endl; break; } default: if (num % 5 != 0 && num % 3 != 0 && num % 2 != 0) { cout << num << " is not divisible by 5, 3, or 2." << endl; } }
return 0; }
Write a program to check if a given year is a leap year or not using if-else statement.
#include <iostream> using namespace std;
int main() { int year;
// Take year input from the user cout << "Enter a year: "; cin >> year;
// Check for leap year if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { cout << year << " is a leap year." << endl; } else { cout << year << " is not a leap year." << endl; } } else { cout << year << " is a leap year." << endl; } } else { cout << year << " is not a leap year." << endl; }
return 0; }
Write a program to check if a given number is even or odd using if-else statement
#include <iostream> using namespace std;
int main() { int num;
// Take input from the user cout << "Enter a number: "; cin >> num;
// Check if the number is even or odd if (num % 2 == 0) { cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; }
return 0; }
Write a program to find the largest of three numbers using if-else statement.
#include <iostream> using namespace std;
int main() { int num1, num2, num3;
// Take three numbers as input from the user cout << "Enter three numbers: "; cin >> num1 >> num2 >> num3;
// Determine the largest number using if-else if (num1 >= num2 && num1 >= num3) { cout << num1 << " is the largest number." << endl; } else if (num2 >= num1 && num2 >= num3) { cout << num2 << " is the largest number." << endl; } else { cout << num3 << " is the largest number." << endl; }