0% found this document useful (0 votes)
4 views99 pages

OOPUnit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts and C++ basics, including key principles like classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It contrasts procedure-oriented programming with object-oriented programming, highlighting the benefits of OOP such as modularity, data hiding, and flexibility. Additionally, it covers fundamental C++ topics like data types, arrays, pointers, dynamic memory allocation, and user-defined data types.

Uploaded by

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

OOPUnit 1

The document provides an overview of Object-Oriented Programming (OOP) concepts and C++ basics, including key principles like classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It contrasts procedure-oriented programming with object-oriented programming, highlighting the benefits of OOP such as modularity, data hiding, and flexibility. Additionally, it covers fundamental C++ topics like data types, arrays, pointers, dynamic memory allocation, and user-defined data types.

Uploaded by

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

Object Oriented Programming

UNIT 1
Contents
UNIT 1: C++ Basics
1.1 Basic concepts of Object-Oriented Programming
1.2 Procedure Oriented Vs Object Oriented Programming
1.3 Benefits of OOP
1.4 Basics of C++
1.4.1 Data types
1.4.2 Identifiers and constants
1.4.3 Operators, Scope Resolution Operator
1.4.4 Expressions
1.4.5 Control Statements and Iteration
1.1 Basic concepts of Object-Oriented
Programming
 Classes and Objects
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
 Constructors and Destructors
 Access Modifiers
1.2 Procedure Oriented Vs Object Oriented
Programming
Procedure-Oriented Programming Object-Oriented Programming
Feature
(POP) (OOP)
Functions or procedures that perform Objects that combine data and
Primary Focus
actions on data. functions.

Top-down approach where the program Bottom-up approach, focusing on


Approach
is divided into functions. objects and classes.

Data is usually global and passed Data is encapsulated within objects and
Data Handling
between functions. protected by methods.

Modularity Achieved through functions. Achieved through objects and classes.

Functions directly access and Data is hidden within objects and


Data Access
manipulate data. accessed via methods.
Continue..
Procedure-Oriented Programming Object-Oriented Programming
Feature
(POP) (OOP)
Functions are reused, but data is Reusability through inheritance,
Reusability
not inherently reusable. polymorphism, and classes.
Less flexible, as changes in one More flexible, as changes to one
Flexibility
function may affect others. class do not affect others.

No data encapsulation; data can Data is encapsulated; access is


Security
be accessed by any function. controlled using methods.
Errors may affect the entire Errors are easier to isolate, as
Error Handling program due to global data data and behavior are grouped
access. within objects.
Continue..

Procedure-Oriented Programming Object-Oriented Programming


Feature
(POP) (OOP)
Difficult to maintain for large
Easier to maintain due to
Maintenance programs due to scattered data
modularity and encapsulation.
and functions.
Can be simpler for small Can be complex but scales better
Code Complexity
programs but harder to scale. for larger systems.

C, FORTRAN, Pascal, early C++, Java, Python, C#, Ruby,


Examples
versions of C++. Swift.
POP

Main
Function

Function1 Function2 Function3

Function4 Function5
OOP
OOP
OOP Concepts
 Class
• Class is the building block of C++ that leads to Object-Oriented
programming.
• It is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance
of that class.
• A class is like a blueprint for an object.
• Syntax:
class ClassName{
Access Specifiers:
Data Members;
Member Functions ;
}
Class
Example :
#include <iostream> int main() {
using namespace std; // Create an object of class
HelloWorld
class HelloWorld { HelloWorld hw;
public:
// Member function to print "Hello, World!" // Call the greet function to print
the message
void greet() {
[Link]();
cout << "Hello, World!" << endl;
}
return 0;
};
}
 Object
• An Object is an instance of a Class.
• When a class is defined, no memory is allocated but when it is instantiated (i.e.
an object is created) memory is allocated.
• Objects take up space in memory.
• When a program is executed the objects interact by sending messages to one
another.
• Each object contains data and code to manipulate the data.
• Objects can interact without having to know details of each other’s data or code,
it is sufficient to know the type of message accepted and the type of response
returned by the objects.
 Encapsulation
• Encapsulation is defined as wrapping up data and information under a single
unit.
• Encapsulation is defined as binding together the data and the functions that
manipulate them.
• Encapsulation is achieved through the use of access specifiers: public, private,
and protected
Benefits of Encapsulation:
• Data Hiding: By keeping data private, encapsulation helps hide the
internal implementation details from the outside world, providing a
controlled way to access and modify it.
• Control Access: You can define functions (methods) that control how
data is accessed and modified.
• Security: It protects the integrity of the data by restricting unintended
or unauthorized changes.
• Modularity: Encapsulation makes it easier to update and maintain
code, as changes in the class's internal implementation don't affect
external code using the class.
 Abstraction

• Abstraction means displaying only essential information and hiding the details.
• Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
• Abstraction using Classes: We can implement Abstraction in C++ using classes.
The class helps us to group data members and member functions using available
access specifiers. A Class can decide which data member will be visible to the
outside world and which is not.
• Abstraction in Header files: One more type of abstraction in C++ can be header
files.
• For example, consider the pow() method present in math.h header file.
• Whenever we need to calculate the power of a number, we simply call the function
pow() present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.
 Polymorphism

• The word polymorphism means having many forms.


• In simple words, we can define polymorphism as the ability of a
message to be displayed in more than one form.
• A person at the same time can have different characteristics.
• A man at the same time is a father, a husband, and an employee.
• So the same person possesses different behavior in different
situations. This is called polymorphism
Types of polymorphism
1. Compile-time polymorphism, also known as static polymorphism,
is achieved through function overloading and templates.
2. Function overloading is the process of defining multiple functions
with the same name but with different parameters.
3. When a function is called, the compiler determines which version of
the function to use based on the arguments passed to it.
4. Templates are another way to achieve compile-time polymorphism,
where a function or class can be parameterized with one or more
types or values.
• Run-time polymorphism, also known as dynamic polymorphism, is
achieved through inheritance and virtual functions.
• Inheritance is the process of creating a new class from an existing
class, which inherits all the data members and member functions of the
base class.
• Virtual functions are functions that are declared in the base class and
are overridden in the derived classes.
• The correct version of a virtual function is chosen at run-time based on
the actual object that the pointer or reference points to when a virtual
function is invoked using a pointer or reference to the base class.
 Inheritance
• The capability of a class to derive properties and characteristics from
another class is called Inheritance.
• Syntax
class derived_class_name : access-specifier base_class_name
{
// body ....
};
Where
• class: keyword to create a new class
• derived_class_name: name of the new class, which will inherit the
base class
• access-specifier: Specifies the access mode which can be either of
private, public or protected. If neither is specified, private is taken as
default.
• base-class-name: name of the base class.
 A derived class doesn’t inherit access to private data members.
However, it does inherit a full parent object, which contains any
private members which that class declares.
Benefits of OOP
• Benifits of [Link]
 Basics of C++
1.4.1 Data types
Built-In Data Types
• Range refers to the minimum and maximum values that a variable of
a particular data type can store.
• If a program tries to store a number outside of the allowed range, it
can lead to overflow or underflow, which may cause incorrect results
or errors.
• Knowing the range helps programmers choose the appropriate data
type based on the expected values to avoid data loss or unintended
behavior.
void
• Void used to
1. Specify the return type of a function when it is not returning any value
Eg., void function(){ }
2. Indicate an empty argument list to a function
Eg., void function(void){ }
[Link] generic pointer
void *gp;
int *ip;
gp = ip // valid
* ip =*gp // invalid
Derived Data Types
 Arrays
an array is a data structure that is used to store multiple values of
similar data types in a contiguous memory location.
Syntax
data_type array_name[array_size];

Where
data type :Type of Elements(int,float)
array_name : Name of array
array_size : The number of elements the
array will hold
Properties of Arrays
• An Array is a collection of data of the same data type,
stored at a contiguous memory location.
• Indexing of an array starts from 0. It means the first
element is stored at the 0th index, the second at 1st, and
so on.
• Elements of an array can be accessed using their indices.
• Once an array is declared its size remains constant
throughout the program.
• An array can have multiple dimensions.
Declaring and Initializing an Array

#include <iostream> cout << "Second element:


using namespace std; " << arr[1] << endl;
int main() { cout << "Last element: "
// Declare an array of 5 << arr[4] << endl;
integers return 0;
int arr[5] = {1, 2, 3, 4, 5};
// Accessing array elements
}
cout << "First element: " <<
arr[0] << endl;
Array with Default Values (Initializing at Declaration)
#include <iostream> for(int i = 0; i < 5; i++) {
using namespace std; cout << "Element at index "
int main() { << i << ": " << arr[i] << endl;
// Declare and initialize an array with }
default values
int arr[5] = {10, 20, 30}; // The last return 0;
two elements will be set to 0. }
Accessing Elements Using a Loop
#include <iostream>
using namespace std;
int main() {
int arr[3] = {5, 10, 15};
// Loop through and print all array elements
for(int i = 0; i < 3; i++) {
cout << "Element " << i << ": " << arr[i] << endl;
}
return 0;
}
 Pointers
 A pointer is a variable that stores the memory address of another variable.
 Pointers are powerful and versatile, allowing for dynamic memory
management, efficient array manipulation, and complex data structures like
linked lists and trees.
 Pointers
 Declaration: To declare a pointer, use the * operator:

data_type* pointer_name;
 Initialization: You can initialize a pointer with the address of a variable using
the address-of operator &:

int var = 10;


int* ptr = &var; // ptr now holds the address of var
#include <iostream> cout << "Value of ptr: " << ptr << endl;
using namespace std; // Address of var (same as above)
cout << "Value pointed to by ptr: "
<< *ptr << endl; // Output: 20
int main() {
// Changing the value of var using
int var = 20; the pointer
int* ptr = &var; // Pointer to var *ptr = 30; // var is now 30
cout << "New value of var: " << var
cout << "Value of var: " << var << << endl; // Output: 30
endl; // Output: 20 return 0;
cout << "Address of var: " << &var << }
endl; // Address of var
Dynamic Memory Allocation
Pointers are often used with dynamic memory
allocation, which allows you to allocate memory at
runtime using new and release it using delete.
Dynamic Memory Allocation
#include <iostream> cout << "Value: " << *ptr << endl; //
using namespace std; Output: 50

int main() { delete ptr; // Free the allocated


memory
int* ptr = new int; // Dynamically
allocate memory for an int return 0;
*ptr = 50; // Assign a value to }
the allocated memory
References
 A reference is an alias for an existing variable.
 Once a reference is initialized to a variable, you can use the reference to access
or modify the original variable.
 References provide a way to work with variables without needing to use
pointers, and they are often used in function parameters to allow modifications
to the original argument.
 A variable can be declared as a reference by putting ‘&’ in the declaration.
 Variables associated with reference variables can be accessed either by its
name or by the reference variable associated with it.
Declaring a Reference

data_type &reference_name = variable_name;


#include <iostream>
using namespace std;
int main() {
int var = 20;
int &ref = var; // ref is a reference to var
cout << "Value of var: " << var << endl; // Output: 20
cout << "Value of ref: " << ref << endl; // Output: 20
// Modifying the value using the reference
ref = 30; // Changes var as well
cout << "New value of var: " << var << endl; // Output: 30
return 0;
}
References as Function Parameters
 References are commonly used in function parameters to allow functions to modify
the argument passed to them.
#include <iostream>
using namespace std;
void increment(int &num) {
num++; // Increment the original variable
}
int main() {
int value = 10;
increment(value); // value is passed by reference
cout << "Value after increment: " << value << endl; // Output: 11
return 0;
}
 User-Defined Data Types
Structure
Union
Classes
Enumeration
 Structure
• Used to group data items of different types into a single type.
• For Eg. Structure can be Address, in which it further contains
information such as House number, Building name, street, city, state,
pin code, etc.
• It is defined by using the ‘struct’
#include <iostream> int main()
using namespace std; {
struct address
// Declaring structure ad1={10,"C_WING","Tajpore"};
struct address { cout<<"House No. is " <<
ad1.house_no << endl;
int house_no; cout<< ad1.b_name << endl;
char b_name[40]; cout<< ad1.street_name<<
char street_name[40]; endl;

}; }
 Union
• It is a data structure that allows multiple members to share the same
memory location.
• All members of a union overlap, meaning they start at the same
memory address.
• You can store different types of data in a union, but only one member
can hold a value at any given time.
• The union provides a way to save memory when you only need to use
one of the members at a time.
• Syntax:

union UnionName {
Type1 member1;
Type2 member2;
// other members
};
#include <iostream>
using namespace std; // Assign a float value (overwrites the integer)
union Data { data.f = 3.14;
int i; cout << "data.f: " << data.f << endl;
float f;
char c; // Assign a character value (overwrites the float)
}; data.c = 'A';
int main() { cout << "data.c: " << data.c << endl;
Data data;
// Only the last assigned member holds the valid value
// Assign an integer value cout << "data.i (after assigning char): " << data.i << endl;
data.i = 10; cout << "data.f (after assigning char): " << data.f << endl;
cout << "data.i: " << data.i << endl;
return 0;
}
data.i is first assigned an integer value (10).
Then, data.f is assigned a float value (3.14), which
overwrites data.i.
Finally, data.c is assigned a character ('A'), which
overwrites data.f.
Since all the union members share the same memory,
only the most recently assigned member holds a valid
value, and the others show undefined or garbage
values.
 Classes
Please Refer Slide 12-13
 Enumeration
• An enumeration (or enum) is a user-defined
data type that consists of integral constants.
• It is used to represent a set of named integer
constants, which makes the code more readable
and manageable.
Syntax:

enum EnumName {
Constant1,
Constant2,
Constant3,
// ...
};
• By default, the first constant in an enumeration
is assigned the integer value 0, and each
subsequent constant is assigned an integer value
incremented by 1.
1.4.2 Identifiers and constants

• identifiers are names used to identify variables, functions, arrays, classes,


objects, and other user-defined items. They are essentially labels that refer to
program elements.
Rules for Naming Identifiers:
• Starting Character: An identifier must start with a letter (a-z, A-Z) or an
underscore (_).
• Example: x, myVariable, _myVar
• Subsequent Characters: After the first character, an identifier can contain letters
(a-z, A-Z), digits (0-9), and underscores (_).
• Example: variable1, my_var
• Length: There is no strict limit on the length of an identifier, but it is
good practice to keep it reasonably short and meaningful. Most C++
compilers allow identifiers up to 255 characters, though.
• Case Sensitivity: C++ is case-sensitive, meaning Variable, variable,
and VARIABLE would all be considered different identifiers.
• Keywords: Identifiers cannot be keywords (reserved words) in C++.
• Example: int, return, class, while are keywords and cannot be used as
identifiers.
• No Special Characters: Identifiers cannot contain spaces or special
characters such as @, #, or * (except for the underscore _).
Examples of Valid Identifiers:
•x
• sum_of_numbers
• totalAmount
• _tempData
• my_array_1
Examples of Invalid Identifiers:

• 1value (cannot start with a digit)


• int (keyword)
• my-variable (cannot contain hyphens)
• total amount (cannot have spaces)
Naming Conventions:
• While C++ doesn't enforce specific conventions, the following are commonly used
practices:

• Camel Case: Common in variable and function names (myVariable, calculateSum).


• Snake Case: Common in variable names (my_variable, total_sum).
• Pascal Case: Common in class names (MyClass, StudentRecord).
• Uppercase with Underscores: Typically used for constants or macros (MAX_SIZE,
PI).
Constant:
• A constant refers to a value that cannot be modified once it has been initialized.
• Constants are used to represent fixed values that do not change throughout the
execution of a program.
• C++ provides several ways to define constants:
 const Keyword: The const keyword is used to define variables whose value
cannot be changed after initialization.

const int MAX_SIZE = 100; // 'MAX_SIZE' cannot be modified


const double PI = 3.14159; // 'PI' cannot be modified
 #define Preprocessor Directive: The #define directive is used to define macros
(which are constants or expressions) before the compilation process begins. It is
handled by the preprocessor.
• #define MAX_SIZE 100
• #define PI 3.14159
 Constant Member Variables in Classes: You can also define constants within
classes using the const keyword.
class Circle {
public:
const double PI = 3.14159; // Constant member
};
 Enumerated Constants: enum or enum class can be used to define named
constants.
enum Days { Monday, Tuesday, Wednesday, Thursday, Friday };
Comparison of Constant Types:
Value Known At
Type Scope Type Safety Example
Compile Time?

Local, Global, Class const int MAX_SIZE =


const No Yes
Members 100;

Local, Global, Class constexpr int MAX_SIZE


constexpr Yes Yes
Members = 100;

#define Global (preprocessor) No No #define MAX_SIZE 100

Local or Global enum Days { Monday,


enum Yes Yes
(enumerations) Tuesday };
1.4.3 Operators, Scope Resolution Operator
 Operators
• Operators are symbols that perform operations on variables and values. C++ has a wide
variety of operators, categorized based on the type of operation they perform.

• Categories of Operators in C++


[Link] Operators: These operators are used to perform mathematical operations.

+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulo (remainder of division)
int a = 10, b = 5;
int sum = a + b; // sum = 15
int diff = a - b; // diff = 5
int prod = a * b; // prod = 50
int quotient = a / b; // quotient = 2
int remainder = a % b; // remainder = 0
ational (Comparison) Operators: These operators are used to compare two values.
Equal to
Not equal to
Greater than
Less than
Greater than or equal to
Less than or equal to
int x = 5, y = 10;
bool result1 = (x == y); // false
bool result2 = (x != y); // true
bool result3 = (x > y); // false
bool result4 = (x < y); // true
[Link] Operators: These operators are used to perform logical operations,
commonly in conditional statements.

• && : Logical AND


• || : Logical OR
• ! : Logical NOT
bool a = true, b = false;
bool andResult = (a && b); // false
bool orResult = (a || b); // true
bool notResult = !a; // false
[Link] Operators: These operators are used to assign values to
variables.

= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
%= : Modulo and assign
int a = 10;
a += 5; // a = a + 5 -> a = 15
a -= 3; // a = a - 3 -> a = 12
a *= 2; // a = a * 2 -> a = 24
a /= 4; // a = a / 4 -> a = 6
[Link] and Decrement Operators: These operators are used to
increase or decrease a value by 1.

• ++ : Increment (increases by 1)
• -- : Decrement (decreases by 1)
int x = 5;
int a = ++x; // x becomes 6, then a = 6
Pre-increment / Pre-decrement: Changes the value first, then uses it.
int x = 5;
int a = ++x; // x becomes 6, then a = 6
Post-increment / Post-decrement: Uses the value first, then changes it.
int x = 5;
int a = x++; // a = 5, then x becomes 6
[Link] Operators: These operators perform bit-level operations on integer
types.
& : Bitwise AND
| : Bitwise OR
^ : Bitwise XOR (exclusive OR)
~ : Bitwise NOT (one's complement)
<< : Left shift
>> : Right shift
int a = 5, b = 3;
int andResult = a & b; // andResult = 1 (0101 & 0011 = 0001)
int orResult = a | b; // orResult = 7 (0101 | 0011 = 0111)
int xorResult = a ^ b; // xorResult = 6 (0101 ^ 0011 = 0110)
[Link] (Ternary) Operator: A shorthand for if-else statements.
condition ? expr1 : expr2;
If the condition is true, expr1 is executed; otherwise, expr2 is executed.
int x = 10;
int result = (x > 5) ? 100 : 200; // result = 100
[Link] Operator: The sizeof operator returns the size (in bytes) of a data type or
object.
int x = 10;
size_t size = sizeof(x); // size = 4 on most systems (size of an int)
 Operator Precedence and Associativity
 Operator precedence determines the order in which operators are evaluated in
an expression.
 For example, multiplication and division have higher precedence than addition
and subtraction. Associativity determines the direction in which operators of the
same precedence are evaluated.

 Left to Right: Most operators, like +, -, *, /, are evaluated from left to right.
 Right to Left: Assignment operators (=, +=, -=) and conditional (?:) operators are
evaluated from right to left.
Scope Resolution Operator
• To define the scope of a variable, function, or class. It
helps specify the context or namespace in which a
particular name (variable, function, class, etc.) resides.
Uses of the Scope Resolution Operator (::)
1. Accessing Global Variables/Functions:
If there is a local variable or function that hides a global variable or function, the
scope resolution operator can be used to refer to the global version.

int x = 10; // Global variable

void test() {
int x = 20; // Local variable (hides the global variable)
std::cout << "Local x: " << x << std::endl; // Prints 20
std::cout << "Global x: " << ::x << std::endl; // Using :: to access the global x,
prints 10
}
Defining Functions Outside the Class:
When defining member functions outside the class definition, the scope resolution
operator is used to specify that the function belongs to a particular class.
class MyClass {
public:
void display(); // Declaration inside the class
};

// Definition outside the class using scope resolution operator


void MyClass::display() {
std::cout << "Hello from MyClass" << std::endl;
}
Accessing Static Members:
Static members of a class are shared by all instances of the class. You can access them using the scope
resolution operator, either inside or outside the class.
class MyClass {
public:
static int count; // Static member variable
};
int MyClass::count = 0; // Defining the static member outside the class

int main() {
MyClass::count = 5; // Accessing static member using the scope resolution operator
std::cout << "Count: " << MyClass::count << std::endl;
return 0;
}
Accessing Namespace Members:
The scope resolution operator is also used to access variables, functions, and
classes that are part of a specific namespace.
namespace MyNamespace { int main() {
int x = 100; // Accessing members of
void print() { MyNamespace using the scope
resolution operator
std::cout << "Inside
MyNamespace" << std::endl; std::cout << MyNamespace::x
<< std::endl; // Prints 100
}
MyNamespace::print();
} // Prints "Inside MyNamespace"
return 0;
}
1.4.4 Expressions
• An expression is a combination of operators,constants and variables arranged as
per the rules of the language.
• It may be include function calls which return values.
• An expression may consist of one or more operand and zero or more operators to
produce a value.
Types of expressions

1. Constant Expression : A constant expression is an expression that consists of


only constant values. It is an expression whose value is determined at the
compile-time but evaluated at the run-time. It can be composed of integer,
character, floating-point, and enumeration constants.12,3.14, ‘x’
2. Integral Expression: Expression which produce integer results after
implementing all the type conversions.x+y,5+int(2.0)
3. Float Expression : Expression which produce floating point results.
x*y/10,10.28
4. Relational (Comparison) Expressions: These expressions compare
two values using relational operators (==, !=, >, <, >=, <=) and return a
boolean value (true or false).
5. Logical Expressions: Logical expressions evaluate conditions using
logical operators (&&, ||, !) and return boolean values.
6. Pointer Expressions: Pointer expressions involve dereferencing a
pointer (*) or getting the address of a variable (&).
7. Bitwise Expressions: Bitwise expressions are used to manipulate
data at bit [Link] used for testing or shifting bits. X<<3
Assignment Expressions
1. Chained Assignment
x= (y= 10) or x = y =10
• Chained statement cannot be used to initialize variables at the time of
declaration.
float a=b=12.34 // invalid

float a=20.50,b=12.23; // valid


2. Embedded Assignment :
x=(y=50) +10;
3. Compound Assignment :
Combination of the assignment operator with binary arithmetic operator.
x=x+10
can be written as
x += 10;
+= operator is called compound assignment operator or short hand assignment
operator . General form :
variable1 op= variable2
1.4.5 Control Statements and Iteration
• Control structures are used to dictate the flow of execution of a program based
on conditions or repeated actions.
• They allow you to make decisions, repeat tasks, and control the order in which
code is executed.
1. Sequential Structure
• This is the default mode of control in C++. Statements are executed
one after the other in the order they are written, unless altered by
other control structures.
2. Selection (Decision) Structures
if statement: Used to execute a block of code if a specified condition is
true.
if (condition) {
// code block executed if condition is true
}
• if-else statement: Used to execute one block of code if the condition
is true, and another block if it is false.
if (condition) {
// code block executed if condition is true
} else {
// code block executed if condition is false
}
if-else if-else statement: Used to check multiple conditions and
execute different blocks of code for each condition.
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// block 3
}
switch statement: Used to select one of many code blocks to be executed based on a
single expression's value.
switch (expression) {
case value1:
// block of code
break;
case value2:
// block of code
break;
default:
// block of code if no case matches
}
3. Repetition (Looping) Structures
for loop: Used to repeat a block of code a specific number of times.
for (initialization; condition; increment/decrement) {
// code to be executed
}
while loop: Used to repeat a block of code as long as a condition is true.
while (condition) {
// code to be executed
}
do-while loop: Similar to the while loop, but guarantees that the block of
code will be executed at least once, because the condition is checked after
the code block.
do {
// code to be executed
} while (condition);
4. Jump Control Structures continue: Skips the current iteration of
break: Exits a loop or switch statement a loop and moves to the next iteration.
early. for (int i = 0; i < 10; i++) {
while (condition) { if (i == 5) {
if (exitCondition) { continue; // skips the rest of the
break; // exit loop loop when i is 5
} }
} }
return: Exits from a function and
optionally returns a value.
return 0; // exits the function and
returns 0

You might also like