Unit 3 Programming Language
Unit 3 Programming Language
A programming language is a formal set of instructions that can be used to produce a wide
range of outputs, such as software applications, algorithms, and systems. These languages are
used to communicate with computers and to create software programs that solve problems,
automate tasks, or perform operations.
Programming languages can be categorized into various types based on their purpose and the
level of abstraction from machine code:
a. Low-Level Languages
1. Machine Language:
o This is the lowest level of language and consists of binary code (1s and 0s). It is
directly understood by the computer's central processing unit (CPU).
2. Assembly Language:
o A step above machine language, assembly uses mnemonics and symbols to
represent machine-level code. It is still hardware-dependent.
b. High-Level Languages
High-level languages are more abstract and closer to human language, making them easier to
write, read, and understand.
1. Procedural Languages:
o C: One of the oldest and most powerful languages, used for system programming
and software development.
o Pascal: Primarily used for teaching programming concepts.
o Fortran: Widely used for numerical and scientific computing.
2. Object-Oriented Languages:
o Java: A versatile, platform-independent language that follows the object-oriented
programming (OOP) paradigm. It’s widely used for web applications, mobile
apps (Android), and large systems.
o Python: Known for its simplicity and readability, Python is great for web
development, data science, machine learning, and scripting.
o C++: An extension of C, adding object-oriented features, and widely used in
game development, system software, and performance-critical applications.
3. Functional Languages:
o Haskell: A purely functional programming language often used for academic
purposes and research.
o Lisp: One of the oldest programming languages, known for its use in artificial
intelligence.
4. Scripting Languages:
o JavaScript: Primarily used for web development, JavaScript enables interactive
elements on websites and is widely used for both front-end and back-end
development ([Link]).
o Ruby: Known for its simplicity and speed, Ruby is often used in web
development (e.g., with the Ruby on Rails framework).
o PHP: A server-side scripting language used in web development, often for
building dynamic websites.
Here are a few widely used programming languages and their primary applications:
a. Python
b. JavaScript
• Application: Web development (both front-end and back-end), mobile apps (React
Native), and interactive user interfaces.
• Why Use It: JavaScript is essential for creating dynamic websites and applications. It
runs in the browser, allowing for client-side scripting.
c. Java
d. C and C++
e. Swift
f. R and MATLAB
Regardless of the language, certain fundamental concepts are shared across most programming
languages:
1. Variables and Data Types:
o Variables store data, and data types define what kind of data can be stored (e.g.,
integer, string, boolean).
2. Control Structures:
o Conditional Statements (if, else): Allow the program to make decisions.
o Loops (for, while): Repeatedly execute a block of code.
3. Functions/Methods:
o Functions are reusable blocks of code that perform specific tasks. Functions can
accept inputs (parameters) and return outputs.
4. Objects and Classes (OOP):
o In Object-Oriented Programming, classes are templates for objects, which are
instances that hold data and functionality.
5. Arrays and Collections:
o Arrays and other data structures (e.g., lists, dictionaries, sets) store multiple values
in a single variable.
6. Error Handling:
o Mechanisms to handle and respond to errors in a program (e.g., using try-catch
blocks).
7. Libraries and Frameworks:
o Libraries provide pre-written code to handle common tasks. Frameworks give a
structured foundation for building applications (e.g., Django for Python, React for
JavaScript).
When deciding which programming language to learn or use for a project, consider the following
factors:
1. Project Requirements: What type of project are you working on? For example:
o For web development: JavaScript, HTML/CSS, Python.
o For mobile apps: Swift (iOS), Kotlin/Java (Android).
o For machine learning or data analysis: Python, R.
2. Performance Needs:
If you require high performance, C, C++, and Rust might be better options due to their
speed and low-level control.
3. Community and Support:
Consider the size of the language's community. A large community means more
resources, libraries, and support.
4. Ease of Learning:
Some languages like Python and JavaScript are known for being easier for beginners,
while others like C++ may have a steeper learning curve.
Programming Language Fundamentals, Types of Programming Languages,
Errors, and Program Design Tools
A programming language allows you to write instructions that a computer can execute. These
instructions are used to perform specific tasks, whether it’s solving a problem, automating a task,
or building an application. Below are some fundamental concepts to understand when learning
a programming language:
Programming languages can be classified into several categories, depending on their level of
abstraction and their purpose:
1. Low-Level Languages:
o Machine Language: The lowest-level language that consists of binary code (1s
and 0s) directly understood by a computer’s CPU.
o Assembly Language: A step above machine language, using mnemonics instead
of binary to represent machine instructions. It is still very close to the hardware.
2. High-Level Languages: High-level languages are more abstract and easier for humans to
understand and use. These are translated into machine language by compilers or
interpreters.
o Procedural Programming Languages:
These languages focus on a sequence of steps or instructions. They are great for
solving tasks that require a series of ordered steps.
▪ Examples: C, Pascal, Fortran.
o Object-Oriented Programming (OOP) Languages:
These languages are designed to represent real-world objects using classes and
objects. The four key concepts of OOP are Encapsulation, Abstraction,
Inheritance, and Polymorphism.
▪ Examples: Java, C++, Python.
o Functional Programming Languages:
These focus on the evaluation of functions and avoid changing state and mutable
data. Functions are treated as first-class citizens.
▪ Examples: Haskell, Lisp, F#.
o Scripting Languages:
These are typically interpreted rather than compiled and are often used to
automate tasks or interact with software.
▪ Examples: JavaScript, Python, Ruby.
o Markup Languages:
These are not strictly programming languages but are used to define the structure
and presentation of text. They are primarily used for creating web pages.
▪ Examples: HTML, XML, CSS.
Errors are issues that occur during the writing, compilation, or execution of a program. There are
three primary types of errors in programming:
1. Syntax Errors:
o Definition: These are errors in the structure or grammar of the program. The code
violates the language's syntax rules.
o Examples: Missing semicolons, mismatched parentheses, or improper
indentation.
o How to Fix: Carefully check the code for any misspelled keywords, incorrect
punctuation, or improper structure.
Example:
Example
If the code has a logic issue, it might print incorrect values or not handle all cases
properly.
3. Runtime Errors:
o Definition: These errors occur while the program is running. The program may
crash or produce unexpected results due to operations like division by zero or
accessing non-existent files.
o Examples: Trying to divide by zero, accessing a list index that doesn't exist, or
running out of memory.
o How to Fix: Use proper error handling techniques (e.g., try-catch blocks) and
check for conditions that might cause the error before executing the operation.
Example:
a = 5
b = 0
print(a / b) # This will cause a runtime error (division by zero)
When developing a program, good design is critical for creating reliable, efficient, and
maintainable code. Two important tools used in program design are Algorithms and
Flowcharts.
1. Algorithm:
o Definition: An algorithm is a step-by-step procedure or formula for solving a
problem. It is a high-level description of how the task will be performed, often
used before writing code.
o Key Features:
▪ Clear and unambiguous.
▪ Finiteness: It should terminate after a finite number of steps.
▪ Efficiency: It should solve the problem in a reasonable amount of time.
Example:
An algorithm to find the largest of two numbers might be:
1. Start
2. Read two numbers, a and b.
3. If a > b, then print a as the largest.
4. Else, print b as the largest.
5. End
2. Flowchart:
o Definition: A flowchart is a diagrammatic representation of an algorithm or
process, showing the steps and decision points in a visual manner.
o Key Components:
▪ Start/End: Represented by ovals, marking the beginning and end of the
process.
▪ Processes: Represented by rectangles, showing actions or steps.
▪ Decisions: Represented by diamonds, used for yes/no or true/false
decisions.
▪ Arrows: Show the flow of control between steps.
Example:
A flowchart to find the largest of two numbers might look like this:
(Start) --> [Input a, b] --> (a > b?) --> [Yes] --> [Print a] --> (End)
--> [No] --> [Print b] --> (End)
C is one of the oldest and most widely used programming languages, known for its efficiency,
performance, and portability. It was developed in the early 1970s by Dennis Ritchie at AT&T
Bell Labs. C is a general-purpose, high-level language with low-level features, making it
suitable for system programming, embedded systems, and application development.
1. Overview of C Programming
C is often called a "middle-level" language because it combines the features of both high-level
and low-level programming languages. It is high-level in that it supports abstract data types, and
it is low-level because it provides access to memory addresses and allows manual memory
management.
Key Characteristics of C:
1. Procedure-Oriented Language:
o C is primarily a procedural programming language, meaning the focus is on
functions (or procedures) that perform specific tasks.
o Programs in C are organized as a collection of functions that work together to
solve a problem.
2. Compiled Language:
o C programs are written in source code and then compiled into machine code by a
compiler (e.g., GCC).
o This compilation process produces executable files, making C programs faster
and more efficient.
3. Portability:
o One of C’s most important features is portability. Once a C program is written, it
can be run on any machine with a compatible C compiler.
o C is the foundation for many other programming languages, and its syntax and
principles are widely used in modern languages like C++, Java, and Python.
4. Low-Level Memory Access:
o C allows you to directly manipulate memory using pointers. Pointers are variables
that store memory addresses, giving C a great deal of flexibility and power in
managing memory.
5. Efficient and Fast:
o C is widely known for its performance. Because C provides low-level access to
memory and hardware resources, it is used for system-level programming where
performance is critical.
Here are some of the key features that make C powerful, efficient, and widely used:
a. Simplicity
• C provides a relatively simple set of features and constructs, making it easy to learn and
use for both beginners and experienced programmers.
• Its syntax is clear and concise, which has led to its adoption in both teaching and
industry.
b. Structured Programming
d. Memory Management
e. Modularity
• C allows you to write modular code by dividing programs into smaller functions, making
the program easier to maintain and debug. Functions are reusable and can be called
multiple times throughout the program.
f. Low-Level Access
g. Portability
• Programs written in C are generally more efficient and faster compared to programs
written in other high-level languages, which is why C is used for system programming,
operating systems, and real-time applications.
i. Extensibility
• C allows you to extend the language's functionality by writing your own libraries and
linking them to your program. This flexibility allows C to be used in a wide variety of
applications.
3. Structure of a C Program
1. Preprocessor Directives:
o These are instructions to the compiler to include external files, define constants,
or conditionally compile certain parts of code.
o Example:
2. Main Function:
o Every C program has a main() function, which is the entry point of the program.
o Example:
int main() {
// Code to execute
return 0; // Return statement
}
4. Functions:
o C programs can be divided into functions that perform specific tasks.
o Example:
// Function declaration
int add(int a, int b);
int main() {
int num1 = 10, num2 = 20, sum;
// Function definition
int add(int a, int b) {
return a + b; // Add two numbers and return the result
}
5. Applications of C
1. System Programming:
o Operating systems (e.g., UNIX, Linux) are written in C due to its low-level access
to hardware and efficient performance.
2. Embedded Systems:
o C is widely used in embedded systems programming, including firmware
development for microcontrollers and hardware devices.
3. Application Software:
o Many application software programs, including compilers, text editors, and
databases, are written in C.
4. Game Development:
o C and its descendant C++ are often used for game development due to their
performance and access to hardware resources.
5. Networking:
o Network programming and protocol implementation often use C for its
performance and low-level control.
6. Advantages of C
7. Disadvantages of C
In C programming, understanding the basic building blocks like data types, variables, C
tokens, and header files is essential for writing effective and efficient programs. Let's break
down these key concepts.
Data Types
Data types define the type of data a variable can hold. C has several primitive data types to
work with. These are classified into:
Example:
Variables
A variable in C is a name given to a memory location that stores a value. The value stored can
change during program execution.
2. C Tokens
In C programming, a token is the smallest unit in the code. Tokens are classified into the
following categories:
a. Keywords
Keywords are predefined, reserved words that have special meanings in C. They cannot be used
as identifiers (variable names, function names, etc.). C has 32 keywords.
• Examples:
o int, float, char, if, else, return, for, while, break, continue, switch, etc.
b. Identifiers
An identifier is a name used to identify variables, functions, arrays, etc. An identifier must start
with a letter (uppercase or lowercase) or an underscore _, followed by letters, digits, or
underscores.
c. Constants
A constant is a value that does not change during the program’s execution. Constants can be:
d. Operators
Operators are symbols that perform operations on variables and values. C has several types of
operators:
3. Header Files in C
Header files in C contain declarations and macro definitions that are shared across multiple
source files. They allow you to reuse code, define functions, and declare global variables.
Common header files include standard libraries, such as:
Example:
The #include directive is used to include these files. When the program is compiled, the code in
the header files is inserted into the source code.
4. Library Functions in C
Library functions are pre-defined functions that come with C’s standard library. These
functions simplify tasks by providing a higher-level interface to perform commonly used
operations. Some key libraries and their common functions include:
printf("Hello, World!");
int x;
scanf("%d", &x); // Reads an integer from the user
free(ptr);
char dest[20];
strcpy(dest, "World");
In C programming, statements and operators are essential building blocks that help you define
logic and control the flow of a program. Let's dive into both concepts in detail.
1. Statements in C
A statement is an instruction that the program executes. In C, statements are typically
expressions that perform actions or computations, and they control the flow of execution in the
program. There are several types of statements in C:
a. Expression Statement
An expression that is evaluated for its side effects, such as assignments or function calls. The
result of the expression is usually not used, but it performs an action.
• Example:
a = b + c; // Assignment statement
b. Declaration Statement
• Example:
Control the execution flow based on conditions or repetitions. These include if-else, switch-case,
for, while, do-while, and break statements.
if (a > b) {
printf("a is greater than b");
} else {
printf("b is greater than a");
}
switch (n) {
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
default:
printf("Default case");
}
• For Loop: Used for repetitive execution with a known number of iterations.
for (int i = 0; i < 5; i++) {
printf("%d\n", i); // Print numbers from 0 to 4
}
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
• Do-While Loop: Similar to the while loop but guarantees at least one execution.
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
• Continue Statement: Skips the current iteration of a loop and moves to the next
iteration.
2. Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical, logical, or data
manipulation tasks. C supports a wide range of operators, which can be classified as follows:
a. Arithmetic Operators
• Operators: +, -, *, /, %
• Examples:
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int div = a / b; // Division
int mod = a % b; // Modulus (remainder)
b. Relational Operators
Relational operators are used to compare two values. They return a boolean value (true or
false).
if (a == b) {
printf("a is equal to b");
}
if (a > b) {
printf("a is greater than b");
}
c. Logical Operators
Logical operators are used to perform logical operations, often in control flow statements like if-
else.
d. Assignment Operators
a++; // Increment a by 1
--b; // Decrement b by 1
f. Bitwise Operators
Bitwise operators are used to perform bit-level operations on data. They work on individual bits
of the operands.
• Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
• Examples:
int a = 5, b = 3;
int and_result = a & b; // Bitwise AND
int or_result = a | b; // Bitwise OR
int xor_result = a ^ b; // Bitwise XOR
int not_result = ~a; // Bitwise NOT
int left_shift = a << 1; // Left shift a by 1 bit
int right_shift = a >> 1; // Right shift a by 1 bit
The ternary operator is a shorthand for if-else statements. It evaluates a condition and returns
one of two values based on the result.
• Operator: ? :
• Example:
h. Sizeof Operator
The sizeof() operator is used to determine the size (in bytes) of a data type or variable.
• Example:
i. Comma Operator
The comma operator allows two expressions to be evaluated in a single statement. The result of
the second expression is returned.
• Example:
int a, b, c;
a = (b = 3, c = 4); // b = 3, c = 4, and a = 4
Preprocessor Directives in C
In C programming, preprocessor directives are lines of code that begin with a hash symbol (#)
and are processed by the preprocessor before the actual compilation of the program starts. The
preprocessor handles these directives before the program is compiled and is responsible for tasks
like including external files, defining constants, conditional compilation, and more.
Preprocessor directives are not statements or functions; they are instructions to the preprocessor
to perform specific actions.
1. #include Directive
The #include directive is used to include external files in the program, most commonly header
files. This allows you to use functions, constants, and variables that are declared in other files.
• Syntax:
• Examples:
o Including standard library headers:
• Explanation:
o Angle brackets < > are used for system libraries, meaning the compiler looks for
the file in system directories.
o Double quotes " " are used for user-defined files, meaning the compiler looks in
the current directory first.
2. #define Directive
The #define directive is used to define constants or macros. These constants are replaced by the
preprocessor before compilation.
• Syntax:
• Example:
• Explanation:
o The #define directive defines a constant, and whenever that constant appears in
the code, it is replaced with its value.
o The MAX macro is an example of a function-like macro. The macro does not
require parameters, and it’s evaluated wherever it is used in the code.
3. #undef Directive
• Syntax:
#undef MACRO_NAME
• Example:
#define PI 3.14
#undef PI // Undefine the macro PI
• Explanation: After #undef, the macro is no longer defined, and using it in the code
would result in a compiler error.
4. #if, #else, #elif, #endif Directives
These directives are used for conditional compilation. They allow code to be compiled or
excluded based on certain conditions (like defining constants or checking specific conditions).
• Syntax:
#if condition
// Code to compile if condition is true
#else
// Code to compile if condition is false
#endif
• Example:
#define DEBUG 1
#if DEBUG
printf("Debugging is enabled\n");
#else
printf("Debugging is disabled\n");
#endif
The #ifdef (if defined) and #ifndef (if not defined) directives are used to check whether a
macro has been defined or not.
• Syntax:
#ifdef MACRO_NAME
// Code if the macro is defined
#endif
#ifndef MACRO_NAME
// Code if the macro is not defined
#endif
• Example:
#define FEATURE_ENABLED
#ifdef FEATURE_ENABLED
printf("Feature is enabled\n");
#else
printf("Feature is not enabled\n");
#endif
#ifndef FEATURE_DISABLED
printf("Feature is enabled\n");
#endif
• Explanation:
o #ifdef checks if a macro is defined.
o #ifndef checks if a macro is not defined.
6. #error Directive
The #error directive generates a custom error message during compilation. It can be used to halt
the compilation with a specific message if certain conditions are met.
• Syntax:
#error error_message
• Example:
#if !defined(VERSION)
#error "VERSION must be defined!"
#endif
• Explanation: If VERSION is not defined, this will produce a custom error message,
helping the developer know what went wrong during the compilation.
7. #pragma Directive
The #pragma directive is used to provide additional instructions to the compiler. It is often used
for controlling specific compiler features, such as warnings or optimizations. It is compiler-
specific and may vary across different compilers.
• Syntax:
#pragma directive_name
• Example:
• Explanation:
o #pragma once is often used to avoid including a header file multiple times, which
could cause redefinition errors.
o Other compiler-specific pragmas can be used for controlling warnings,
optimizations, and other features.
8. #include Guards
While not strictly a preprocessor directive itself, include guards are commonly used in header
files to prevent multiple inclusions of the same header file, which can lead to errors.
• Syntax:
#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
// Header file content
#endif
• Example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#endif
• Explanation:
o #ifndef checks if the macro MY_HEADER_H has not been defined before. If not, it
defines the macro and includes the header file's content.
o #endif closes the conditional block.
In C, input/output (I/O) operations are primarily handled using functions provided by the
standard library <stdio.h>. There are functions for reading input from the user (input) and
displaying output to the console (output).
• scanf(): The scanf() function is used to read formatted input from the user.
o Syntax:
c
CopyEdit
scanf("format_specifier", &variable);
o Example:
c
CopyEdit
int a;
printf("Enter a number: ");
scanf("%d", &a); // Reads an integer
o Explanation: The %d format specifier tells scanf() to read an integer value, and
the &a gives the address of the variable a where the input will be stored.
• printf(): The printf() function is used to display formatted output to the screen.
o Syntax:
c
CopyEdit
printf("format_specifier", variable);
o Example:
c
CopyEdit
int a = 10;
printf("The value of a is: %d\n", a); // Displays the value of a
2. Control Statements in C
Control statements are used to control the flow of execution in a program. They help make
decisions or repeat actions based on certain conditions.
a. If-Else Statement
The if statement is used to make decisions in the program. If the condition inside the if is true,
the code block inside the if is executed. If it's false, the else block is executed (if present).
• Syntax:
c
CopyEdit
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
• Example:
c
CopyEdit
int a = 10;
if (a > 5) {
printf("a is greater than 5\n");
} else {
printf("a is less than or equal to 5\n");
}
Used when you have multiple conditions to check. The else if allows you to test more than
two conditions.
• Syntax:
c
CopyEdit
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}
• Example:
c
CopyEdit
int a = 10;
if (a > 15) {
printf("a is greater than 15\n");
} else if (a > 5) {
printf("a is greater than 5 but less than or equal to 15\n");
} else {
printf("a is less than or equal to 5\n");
}
c. Switch-Case Statement
The switch statement is used to select one of many code blocks to be executed. It checks the
value of a variable and compares it against multiple possible values.
• Syntax:
c
CopyEdit
switch (expression) {
case value1:
// Code block if expression == value1
break;
case value2:
// Code block if expression == value2
break;
default:
// Code block if no case matches
}
• Example:
c
CopyEdit
int a = 2;
switch (a) {
case 1:
printf("a is 1\n");
break;
case 2:
printf("a is 2\n");
break;
default:
printf("a is not 1 or 2\n");
}
• Explanation: The break statement ensures that the switch statement is exited once a
match is found. Without break, all cases below the matching case will be executed
(known as "fall through").
3. Loops in C
Loops are used to repeat a block of code multiple times based on a condition. C supports several
types of loops: for, while, and do-while.
a. For Loop
The for loop is used when you know the number of iterations beforehand.
• Syntax:
c
CopyEdit
for (initialization; condition; increment/decrement) {
// Code to execute
}
• Example:
c
CopyEdit
for (int i = 0; i < 5; i++) {
printf("i = %d\n", i);
}
• Explanation:
o The initialization is executed once at the beginning of the loop.
o The condition is checked before each iteration, and if it’s true, the loop
executes.
o The increment/decrement is executed after each iteration.
b. While Loop
The while loop is used when you don’t know the number of iterations in advance. It runs as long
as the condition is true.
• Syntax:
c
CopyEdit
while (condition) {
// Code to execute
}
• Example:
c
CopyEdit
int i = 0;
while (i < 5) {
printf("i = %d\n", i);
i++; // Increment i to avoid infinite loop
}
• Explanation: The loop will continue as long as the condition remains true. If the
condition is false initially, the loop won't execute at all.
c. Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the loop will execute at
least once, because the condition is checked after the loop executes.
• Syntax:
c
CopyEdit
do {
// Code to execute
} while (condition);
• Example:
c
CopyEdit
int i = 0;
do {
printf("i = %d\n", i);
i++;
} while (i < 5);
• Explanation: The do-while loop ensures that the code block will run at least once, even
if the condition is false initially.
Procedures/Functions in C
A function is a self-contained block of code that can be invoked from other parts of the program.
When a function is called, the program jumps to that function, executes its statements, and
returns to the calling code once the function execution is complete.
2. Types of Functions in C
• Standard Library Functions: These are predefined functions provided by C's standard
library, such as printf(), scanf(), strlen(), etc.
• User-Defined Functions: These are functions defined by the programmer to perform a
specific task. For example, a function to calculate the sum of two numbers.
3. Syntax of a Function in C
The function declaration is where you declare the function's name, return type, and parameters (if
any), but it does not contain the function body.
• Syntax:
return_type function_name(parameter_list);
• Example:
Function Definition
The function definition includes the actual body of the function, where the functionality is
implemented.
• Syntax:
return_type function_name(parameter_list) {
// Function body: code to be executed
}
• Example:
Function Call
To use a function in your program, you need to call it. A function is called by its name followed
by arguments (if any) in parentheses.
• Syntax:
function_name(arguments);
• Example:
int result = add(3, 4); // Calls the add function with arguments 3 and
4
4. Function Components
• Return Type: Specifies what type of value the function will return. It could be any valid
data type like int, float, char, or void (if no return value is needed).
• Function Name: A unique name used to identify the function. This name is used when
calling the function.
• Parameters (optional): Variables passed to the function to provide input values.
Functions may have zero or more parameters.
• Function Body: Contains the code that performs the task when the function is called.
5. Types of Functions
This type of function takes input values (parameters) and returns a result (output).
• Example: A function that adds two integers and returns the result.
#include <stdio.h>
Output:
makefile
CopyEdit
Sum: 8
These functions do not return any value. They can still take input parameters, but they do not
return a value.
#include <stdio.h>
void greet() {
printf("Hello, World!\n");
}
int main() {
greet(); // Call the greet function
return 0;
}
Output:
CopyEdit
Hello, World!
#include <stdio.h>
void displayMessage() {
printf("This is a message from the function.\n");
}
int main() {
displayMessage(); // Call the function
return 0;
}
Output:
vbnet
CopyEdit
This is a message from the function.
a. Pass by Value
When parameters are passed by value, the function receives a copy of the argument's value. Any
changes made to the parameter inside the function do not affect the original argument.
#include <stdio.h>
void changeValue(int x) {
x = 20; // Changes the value of x inside the function
}
int main() {
int num = 10;
changeValue(num); // num is passed by value
printf("num after function call: %d\n", num); // num remains
unchanged
return 0;
}
Output:
pgsql
CopyEdit
num after function call: 10
When parameters are passed by reference (using pointers), the function works with the actual
data, meaning any changes made to the parameter inside the function will affect the original
argument.
#include <stdio.h>
Output:
pgsql
CopyEdit
num after function call: 20
7. Recursion
A function is said to be recursive if it calls itself. Recursion is useful in solving problems that
can be broken down into smaller sub-problems, like in calculating factorials, Fibonacci series,
etc.
#include <stdio.h>
int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive case
}
int main() {
int num = 5;
printf("Factorial of %d is: %d\n", num, factorial(num));
return 0;
}
Output:
csharp
CopyEdit
Factorial of 5 is: 120
Function prototypes allow you to declare the function before its actual definition. This is useful
when the function is defined after the main() function or in a separate file.
int main() {
int sum = add(5, 3); // Function call
printf("Sum: %d\n", sum);
return 0;
}
Functions can return different types of values, such as integers, floating-point numbers,
characters, etc. If no value needs to be returned, you can use the void return type.
In C programming, arrays and strings are essential data structures used to store multiple values.
Arrays store elements of the same type, while strings are arrays of characters that are used to
handle textual data. Let's look at both in detail:
1. Array in C
An array is a collection of elements, all of the same type, stored in contiguous memory
locations. The size of an array is fixed when it is declared.
A[6] ={3,2,5,1,0,7}
3 2 5 1 0 7
Printf(“%d”, A[1]);
a. Declaring an Array
To declare an array in C, you specify the data type, the array name, and the number of elements
it can hold (size of the array).
• Syntax:
data_type array_name[size];
• Example:
b. Initializing an Array
You can initialize an array at the time of declaration or later in the program.
• Partially initialized: If you provide fewer values than the size of the array, the remaining
elements are automatically initialized to zero.
• Without specifying size: If the size is not specified, the compiler automatically
determines the size based on the number of elements in the initialization list.
You access array elements using an index, where the index starts at 0.
• Syntax:
array_name[index]
• Example:
First element: 10
Second element: 20
d. Multidimensional Arrays
C allows the use of multidimensional arrays, such as 2D arrays, which are useful for storing
data in tables or matrices.
• Syntax:
data_type array_name[rows][columns];
Accessing an element:
Output:
2. String in C
In C, a string is an array of characters that ends with a special null character '\0'. Strings are
used to store and manipulate textual data.
a. Declaring a String
You declare a string as an array of characters, ensuring the last character is the null character
'\0'.
• Syntax:
char str[size];
• Example:
• At the time of declaration: Strings can be initialized at the time of declaration using
double quotes.
Strings are stored as arrays of characters, so you can access individual characters using the array
index.
• Example:
Output:
First character: H
d. String Functions in C
C provides many built-in functions in the string.h library for string manipulation, such as:
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Hello";
printf("Length of string: %zu\n", strlen(a)); // Outputs 5
return 0;
}
• Arrays are used for storing collections of data (e.g., numbers), where the data is of the
same type.
• Strings are essentially arrays of characters, but they are specifically meant for handling
text, and they must always end with the null character '\0'.
a. Array Operations
• Iterating through arrays: Use loops like for to iterate through array elements.
b. String Operations
Pointers in C
A pointer in C is a variable that stores the memory address of another variable. Pointers allow
you to directly access and manipulate memory, which can lead to more efficient programs.
Understanding pointers is crucial for working with dynamic memory, arrays, strings, and
function calls.
1. What is a Pointer?
A pointer is a variable that stores the memory address of another variable. Instead of storing a
direct value, a pointer stores the address of the variable in memory where the actual value is
stored.
2. Pointer Declaration
To declare a pointer, you specify the type of data the pointer will point to, followed by an
asterisk (*), which indicates it is a pointer.
• Syntax:
data_type *pointer_name;
• Example:
3. Pointer Initialization
You can initialize a pointer by assigning it the address of a variable using the address-of
operator (&).
• Example:
Here, &num gives the address of the variable num, which is then stored in the pointer ptr.
4. Dereferencing a Pointer
Dereferencing is the process of accessing the value stored at the memory address that a pointer
holds. You do this by using the dereference operator (*).
• Syntax:
*pointer_name
• Example:
Output:
Value of num: 10
In this case, *ptr gives the value stored at the memory address stored in ptr, which is 10.
In C, an array is essentially a pointer to the first element of the array. You can use pointers to
iterate through the elements of an array.
• Example:
Output:
First element: 10
Second element: 20
Here, ptr points to the first element of the array arr. The expression *(ptr + 1) accesses the
second element in the array.
6. Pointer Arithmetic
Pointer arithmetic refers to the ability to perform arithmetic operations on pointers. You can add
or subtract integers to/from pointers to traverse arrays or move through memory addresses.
• Example:
Output:
First element: 10
Second element: 20
Fourth element: 40
In this example:
9. Null Pointer
A null pointer is a pointer that doesn’t point to any valid memory location. It is often used to
indicate that the pointer is not yet assigned to a specific variable or that it is meant to be empty.
• Syntax:
• Example:
Output:
Null pointers are important to check to avoid dereferencing an invalid memory address, which
could lead to a program crash.
A pointer to pointer is a pointer that stores the address of another pointer. This is used when
you need to work with multiple levels of indirection.
• Syntax:
data_type **pointer_to_pointer;
• Example:
Output:
Value of num: 10
In this example, ptr2 is a pointer to ptr, and **ptr2 dereferences it twice to access the value of
num.
9. Dynamic Memory Allocation using Pointers
Pointers are often used with dynamic memory allocation to allocate memory at runtime using
functions from the stdlib.h library like malloc(), calloc(), realloc(), and free().
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int*)malloc(5 * sizeof(int)); // Allocate memory for 5
integers
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
Ptr[0] ptr[1] ptr[2] ptr[3] ptr[4]
1 2 3 4 5
Output:
CopyEdit
1 2 3 4 5
In this example, memory for 5 integers is dynamically allocated using malloc(). After using the
memory, it is freed using free() to prevent memory leaks.
#include <stdio.h>
int main() {
int num = 10;
modify(&num); // Pass the address of num to the function
printf("Modified value: %d\n", num); // The value of num is
modified
return 0;
}
Output:
yaml
CopyEdit
Modified value: 20
In this case, the modify() function uses the pointer to change the value of the num variable in the
calling function.
In C, structures and unions are user-defined data types that allow you to group different types
of data together. Both are essential tools for organizing and manipulating data more effectively.
However, there are key differences between them.
1. Structure in C
A structure is a collection of variables (of different data types) grouped together under a single
name. It allows you to store different types of data (such as integers, floats, arrays, etc.) in a
single unit. The individual variables within a structure are known as members or fields.
a. Declaring a Structure
To define a structure, you use the struct keyword followed by the structure name and its
members.
• Syntax:
struct structure_name {
data_type member1;
data_type member2;
// other members...
};
• Example:
struct Person {
char name[50];
int age;
float height;
};
This declares a structure named Person with three members: name (a string), age (an integer),
and height (a floating-point number).
Once a structure is defined, you can create variables of that structure type.
• Example:
You can access members of a structure using the dot operator (.).
• Example:
Output:
Name: John
Age: 25
Height: 5.90
d. Structure Initialization
• Example:
e. Nested Structures
A structure can also contain other structures as members, leading to nested structures.
• Example:
struct Address {
char street[50];
char city[50];
char state[50];
};
struct Person {
char name[50];
struct Address addr;
};
f. Size of Structure
The size of a structure depends on the size of its members and padding (to align members in
memory). You can determine the size using the sizeof operator.
• Example:
2. Union in C
A union is similar to a structure, but with a key difference: in a union, all members share the
same memory location. This means that only one member of a union can hold a value at a time,
and the size of a union is the size of its largest member.
a. Declaring a Union
A union is declared using the union keyword, similar to a structure. However, since all members
share the same memory, only the largest member determines the size of the union.
• Syntax:
union union_name {
data_type member1;
data_type member2;
// other members...
};
• Example:
union Data {
int i;
float f;
char str[20];
};
Here, the union Data has three members: an integer (i), a float (f), and a string (str).
You can create variables of the union type in the same way you do with structures.
• Example:
You can access union members using the dot operator (.), similar to structures. However,
remember that all members share the same memory space, so writing to one member will
overwrite the value of others.
• Example:
Output:
i: 10
f: 3.14
str: Hello, World!
As you can see, assigning to [Link] overwrites the previously stored float value in data1.f.
d. Union Initialization
Unions can be initialized at the time of declaration, but only the first member will be initialized.
Subsequent members will share the same memory.
• Example:
e. Size of Union
The size of a union is determined by the size of its largest member. This is because all members
of a union share the same memory location.
• Example:
• Structures are used when you need to store multiple different types of data and all of
them should be available at the same time. For example, a student record might need to
store the student's name, age, grades, etc., at the same time.
• Unions are useful when you want to save memory and only need to store one of several
types of data at a time. For example, you might use a union to store a number (int), a
floating-point number (float), or a string in a data structure where only one of these is
used at any given moment.
struct Employee {
char name[50];
int age;
union Salary {
int basic;
float bonus;
} salary; // Union inside the structure
};
int main() {
struct Employee emp1;
strcpy([Link], "Alice");
[Link] = 30;
[Link] = 50000; // Using the basic salary of the employee
return 0;
}
Output:
In this example, the structure Employee contains a union Salary to store either a basic salary or
a bonus for each employee.
Files in C
In C, files are used to store data permanently, either in text format or binary format. By using
files, programs can read and write data to storage devices like hard drives or other forms of
permanent storage. The C programming language provides functions for handling files using
standard input/output (I/O) operations.
Files are essential when you need to store data between program executions or handle large
amounts of data that cannot be stored in memory.
1. Types of Files in C
• Text Files: Files that contain readable characters and data stored in a human-readable
format (e.g., .txt, .csv). In text files, data is stored as ASCII or Unicode characters.
• Binary Files: Files that store data in binary format (e.g., .dat). These files contain data
in a machine-readable format, which is more efficient than text files for storing complex
data types.
2. File Operations in C
• Opening a file
• Reading from a file
• Writing to a file
• Closing a file
The C Standard Library provides a set of functions for working with files. These functions are
defined in the <stdio.h> header.
a. Opening a File
To open a file, we use the fopen() function, which takes the file name and the mode in which
the file should be opened. The mode specifies whether you want to read from, write to, or append
data to the file.
• Syntax:
• File Modes:
o "r": Read-only mode. Opens the file for reading. The file must exist.
o "w": Write-only mode. Opens the file for writing. If the file doesn't exist, it is
created. If the file exists, its contents are overwritten.
o "a": Append mode. Opens the file for writing, and appends data at the end of the
file. If the file doesn't exist, it is created.
o "r+": Read and write mode. Opens the file for both reading and writing. The file
must exist.
o "w+": Write and read mode. Opens the file for both reading and writing. If the file
doesn't exist, it is created. If the file exists, its contents are overwritten.
o "a+": Append and read mode. Opens the file for both reading and appending data.
• Example:
To read from a file, we can use several functions, depending on how we want to read the data:
• fgets(): Reads a line from a file (including spaces), stopping at the newline character or
when the specified limit is reached.
o Syntax: char *fgets(char *str, int num, FILE *file);
o Example:
char str[100];
fgets(str, 100, file); // Reads a line from the file
printf("%s", str);
int buffer[10];
fread(buffer, sizeof(int), 10, file); // Reads 10 integers from
the file
c. Writing to a File
d. Closing a File
After finishing operations on a file, it is important to close the file using the fclose() function.
This ensures that any data still in the buffer is written to the file and the file is properly closed.
• Syntax:
• Example:
Here’s a simple example that demonstrates how to open a file, write data to it, and then read the
data from the file.
#include <stdio.h>
int main() {
// Open file for writing
FILE *file = fopen("[Link]", "w");
if (file == NULL) {
printf("File could not be opened for writing.\n");
return 1;
}
Output:
In this example:
• We first open the file [Link] for writing using the "w" mode.
• We then write two lines of text using fprintf() and fputs().
• After closing the file, we open the file again in "r" mode to read the data using fgets().
When performing file operations, it's important to check if the file was opened successfully and
handle potential errors. This can be done by checking the return value of functions like fopen(),
fread(), fwrite(), and fclose().
• Example:
FILE *file = fopen("[Link]", "r");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
Sometimes, you may need to seek to a specific position in a file to read or write data. You can
use fseek() and ftell() to achieve this.
• Example:
In this paradigm, the program is divided into a set of procedures or functions that perform
operations on data. The program flow is generally controlled by calling these procedures in a
specific order.
• Emphasis on Functions: The main focus is on writing functions that perform operations
on data.
• Top-Down Approach: The program is divided into smaller parts, and functions are
executed in a sequence.
• Global Data: Data is typically global, and functions modify this global data.
• Sequential Execution: The program execution is sequential, starting from the first
function and continuing through each function call.
#include <stdio.h>
int main() {
int result1 = add(10, 5);
int result2 = subtract(10, 5);
• In the above code, we have two functions (add and subtract) that operate on data. The
main focus is on how these functions process the data.
2. Object-Oriented Programming (OOP)
In OOP, the focus is on creating objects that combine both data and methods (functions) to
operate on that data. Objects interact with each other by calling methods, and the internal state of
an object is hidden from other objects (encapsulation).
• Encapsulation: Data and the functions that operate on data are bundled together in a
single unit, called an object. This allows data to be protected and hidden from other parts
of the program (information hiding).
• Abstraction: The complex reality is hidden from the user, providing only the essential
details. This allows developers to work with higher-level concepts.
• Inheritance: Allows the creation of new classes that are based on existing classes,
inheriting their properties and behaviors.
• Polymorphism: Objects can take many forms. It allows a single method or function to
behave differently based on the object it is operating on.
• Classes and Objects: A class is a blueprint, and an object is an instance of a class.
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
int main() {
Calculator calc;
int result1 = [Link](10, 5);
int result2 = [Link](10, 5);
Procedure-Oriented Programming
Aspect Object-Oriented Programming (OOP)
(POP)
Objects that combine both data and
Focus Functions that operate on data.
methods.
Top-down approach, starting with Bottom-up approach, starting with
Approach
functions and working downward. classes and creating objects.
Data is global and passed to Data is encapsulated inside objects and
Data Handling
functions. accessed through methods.
Functions can be reused, but data is High modularity through classes and
Modularity
not always protected. objects.
Strong data protection (encapsulation)
Data Limited protection (data is typically
ensures data is hidden from other parts of
Protection global).
the program.
Code Functions can be reused, but code Classes can be reused and extended
Reusability can become less flexible. (inheritance).
Less flexible; adding new features More extensible; new functionality can
Extensibility can require significant changes in be added by creating new classes and
existing code. objects.
Real-World Less natural mapping to real-world Objects and classes map directly to real-
Mapping objects. world entities.
C programming language (e.g., C++, Java, Python, etc. (e.g., classes and
Example
add(), subtract() functions). objects like Calculator)
1. Modularity: OOP organizes code into classes and objects, making it easier to manage
large codebases and divide tasks into smaller, manageable parts.
2. Reusability: With inheritance, code can be reused across different classes without
redundancy. This reduces the amount of code and makes maintenance easier.
3. Flexibility and Maintainability: OOP allows easier modifications and updates. If the
internal implementation of a class needs to change, it won't affect other parts of the
program that use the class.
4. Data Security: OOP provides better data security through encapsulation. The internal
state of an object is hidden and protected from outside interference.
5. Abstraction: OOP allows complex systems to be abstracted into simpler, more
manageable components (e.g., objects and methods), which makes development and
debugging easier.
1. Simplicity: POP is simpler and easier to understand for small programs or quick scripts,
as it focuses on a linear flow of execution and function calls.
2. Efficiency: For simple tasks, POP can be more efficient as it doesn’t involve the
overhead of classes, objects, and the complexities of OOP features like inheritance and
polymorphism.
3. Lower Memory Consumption: Since data in POP is global and there’s no need to
manage multiple objects, it can result in less memory consumption for small programs.
4. Faster Execution: As compared to OOP, procedure-oriented programs generally run
faster because of less memory management overhead.
The main features of OOP allow developers to organize and manage complex systems more
effectively.
1. Encapsulation
• Definition: Encapsulation is the concept of bundling the data (variables) and the
methods (functions) that operate on the data into a single unit known as a class.
Additionally, encapsulation involves hiding the internal state of an object from the
outside world and allowing access only through well-defined methods (getters and
setters).
• Benefits:
o Protects the object's internal state from unintended or harmful modifications.
o Helps in maintaining the integrity of the data by restricting direct access.
• Example:
class BankAccount {
private:
double balance; // Encapsulated data
public:
// Getter method to access balance
double getBalance() {
return balance;
}
In the above example, the balance variable is private, meaning it cannot be accessed directly
from outside the BankAccount class. The only way to interact with the balance is through the
public deposit(), withdraw(), and getBalance() methods.
2. Abstraction
int main() {
Shape* shape1 = new Circle();
Shape* shape2 = new Square();
In this example, the Shape class is abstract and contains a pure virtual function draw(). Derived
classes (Circle and Square) implement the draw() function, but the user only interacts with the
Shape class and doesn't need to know the details of how each shape is drawn.
3. Inheritance
• Definition: Inheritance is a mechanism where a new class (called the derived class) is
based on an existing class (called the base class). The derived class inherits the properties
and methods of the base class, allowing code reuse and extension of existing
functionalities.
• Benefits:
o Promotes code reuse by allowing a new class to inherit attributes and behaviors
from an existing class.
o Helps in creating a hierarchy of classes, leading to more organized and easier-to-
understand code.
• Example:
class Animal {
public:
void eat() {
std::cout << "Eating food\n";
}
};
class Dog : public Animal { // Dog class inherits from Animal class
public:
void bark() {
std::cout << "Barking\n";
}
};
int main() {
Dog dog;
[Link](); // Inherited from Animal class
[Link](); // Defined in Dog class
}
In this example, the Dog class inherits the eat() method from the Animal class, so we don't need
to redefine the eat() method for the Dog class.
4. Polymorphism
• Definition: Polymorphism means "many shapes" and refers to the ability of a single
function or method to operate on different types of objects. Polymorphism allows objects
of different classes to be treated as objects of a common superclass. There are two types
of polymorphism:
o Compile-time polymorphism (Method Overloading or Operator Overloading)
o Run-time polymorphism (Method Overriding)
• Benefits:
o Allows objects of different types to be treated uniformly, providing flexibility in
code.
o Simplifies code, making it easier to extend and maintain.
• Example (Run-time Polymorphism):
class Animal {
public:
virtual void sound() {
std::cout << "Animal makes a sound\n";
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
In this example, even though both Dog and Cat are derived from the Animal class, we can call
the same sound() method on both objects, and the appropriate method for each object is called
(this is known as method overriding).
• Definition:
o A class is a blueprint for creating objects. It defines the properties (variables) and
behaviors (methods) that the objects created from the class will have.
o An object is an instance of a class. It contains real data and can perform the
operations defined in its class.
• Benefits:
o Classes provide structure to the code, grouping related data and functionality
together.
o Objects represent real-world entities, making it easier to model complex systems.
• Example:
class Car {
public:
std::string model;
int year;
void start() {
std::cout << "Car is starting\n";
}
void stop() {
std::cout << "Car is stopping\n";
}
};
int main() {
Car myCar;
[Link] = "Tesla";
[Link] = 2021;
[Link]();
[Link]();
}
Here, Car is a class that defines properties like model and year and methods like start() and
stop(). myCar is an object of the Car class, and we can interact with it using the defined
methods.
• Modularity: Code is organized into classes and objects, making it easier to manage and
maintain.
• Reusability: Through inheritance, code can be reused and extended.
• Flexibility: Polymorphism allows the same function to work on different types of
objects.
• Scalability: OOP systems can be easily extended and modified to handle more complex
tasks.
• Maintainability: Encapsulation ensures that objects are self-contained, reducing the risk
of accidental interference with data and functionality.
• Abstraction: Complex implementations are hidden, making it easier for developers to
focus on high-level functionality.
Object-Oriented Programming (OOP) is based on several core principles that help in organizing
and structuring code in a more manageable and scalable way. These principles help developers
design and implement software in a way that is easier to maintain and extend. The four main
principles of OOP are:
1. Encapsulation
• Definition: Encapsulation is the concept of bundling the data (variables) and the
methods (functions) that operate on the data into a single unit, called a class.
Encapsulation also involves restricting access to the internal state of an object, exposing
only necessary parts through public methods (also known as getters and setters).
• Benefits:
o Hides the internal implementation of an object, allowing changes to be made
without affecting other parts of the program.
o Protects the object's state by preventing direct access to its data, ensuring
controlled access through well-defined methods.
Example:
class Account {
private:
double balance; // Private data member
public:
// Public getter method to access the balance
double getBalance() {
return balance;
}
In this example, the balance is hidden from the outside world, and can only be accessed or
modified using the deposit(), withdraw(), and getBalance() methods.
2. Abstraction
• Definition: Abstraction is the concept of hiding the complex implementation details of an
object and showing only the essential features. This allows the user to interact with an
object without needing to understand its internal workings.
• Benefits:
o Reduces complexity by providing a simplified interface.
o Encourages focus on what an object does rather than how it does it.
o Allows for implementation changes without affecting the rest of the program.
Example:
Here, the Vehicle class defines an abstract interface, and both Car and Bike provide their
specific implementation for the start() and stop() methods. Users of these classes don't need
to know the implementation details, just the behavior.
3. Inheritance
• Definition: Inheritance allows a new class (called the derived class) to inherit the
properties and behaviors (methods) of an existing class (called the base class). This
promotes code reuse and extends functionality without modifying the base class.
• Benefits:
o Promotes code reuse by allowing new classes to inherit behavior from existing
classes.
o Reduces redundancy by allowing shared functionality to be written only once in a
base class.
o Enables the creation of a class hierarchy, which helps in organizing and managing
large programs.
Example:
class Animal {
public:
void eat() {
std::cout << "Eating food\n";
}
};
class Dog : public Animal { // Dog class inherits from Animal class
public:
void bark() {
std::cout << "Barking\n";
}
};
int main() {
Dog dog;
[Link](); // Inherited from Animal class
[Link](); // Defined in Dog class
}
In this example, Dog inherits the eat() method from the Animal class, promoting code reuse.
4. Polymorphism
class Animal {
public:
virtual void sound() {
std::cout << "Animal makes a sound\n";
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
Here, sound() is overridden in both Dog and Cat classes. The object animal1 (which is of type
Dog) calls the sound() method from the Dog class, while animal2 (which is of type Cat) calls
the sound() method from the Cat class.
1. Modularity: OOP breaks down the software into smaller, self-contained objects, making
it easier to manage and develop. Each object is a modular unit that can be developed,
tested, and maintained independently.
2. Code Reusability: OOP promotes code reuse through inheritance, allowing developers
to build on existing code without redundancy.
3. Maintainability: OOP systems are easier to maintain and update because the code is
organized in such a way that it is more modular and less prone to errors. Changes to one
part of the system are less likely to affect others.
4. Flexibility: With polymorphism, objects of different classes can be treated uniformly,
allowing for greater flexibility in handling different types of objects.
5. Data Security: Encapsulation ensures that the internal state of an object is protected
from unintended modifications by other parts of the program.
6. Abstraction: OOP allows complex systems to be broken down into simpler, more
manageable components by hiding the internal details and focusing on high-level
functionality.
Disadvantages of Object-Oriented Programming (OOP)
In Object-Oriented Programming (OOP), the concepts of objects and classes are fundamental.
They represent the blueprint for organizing and structuring data and functionality within a
program.
1. Classes
• Definition: A class is a blueprint or prototype for creating objects. It defines the structure
and behavior of the objects that belong to it. In simpler terms, a class is a template that
specifies what attributes (data) and methods (functions) the objects of that class will have.
• Components of a Class:
o Attributes (or Data Members): These are the variables that define the state of
the class. They represent the properties of the class.
o Methods (or Member Functions): These are functions that define the behavior
of the class. They are used to manipulate the data and implement functionality.
• Syntax:
class ClassName {
private:
// Data members (variables)
dataType attribute1;
dataType attribute2;
public:
// Member functions (methods)
returnType functionName() {
// Function body
}
};
• Example:
class Car {
private:
string model;
int year;
public:
// Constructor to initialize the object
Car(string m, int y) {
model = m;
year = y;
}
In this example, the Car class has two attributes, model and year, and a method displayInfo()
that prints the details of the car.
2. Objects
• Example:
int main() {
// Creating an object of the Car class
Car myCar("Tesla", 2021);
Here, myCar is an object of the Car class, and it uses the displayInfo() method to show its
details.
Let’s consider a Book class that has attributes like title, author, and price, along with a
method to display the book details.
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
double price;
public:
// Constructor to initialize the object
Book(string t, string a, double p) {
title = t;
author = a;
price = p;
}
int main() {
// Creating objects of the Book class
Book book1("C++ Programming", "Bjarne Stroustrup", 39.99);
Book book2("The C Programming Language", "Brian Kernighan", 29.99);
return 0;
}
Explanation:
• Class Definition: Book class defines three private attributes: title, author, and price.
It also defines a constructor to initialize these attributes and a method
displayBookInfo() to display the book details.
• Objects: Two objects book1 and book2 are created from the Book class. Each object has
its own unique data (such as different titles, authors, and prices).
Output:
Book 1 Information:
Book Title: C++ Programming
Author: Bjarne Stroustrup
Price: $39.99
Book 2 Information:
Book Title: The C Programming Language
Author: Brian Kernighan
Price: $29.99
• Classes: Define a blueprint for creating objects. They describe what data and behavior
the objects created from them will have.
• Objects: Are instances of classes. Each object has its own state (data) and can call the
methods (behavior) defined by its class.
• Constructor: A special method that is automatically called when an object is created. It
initializes the object’s state.
• Methods: Functions defined inside a class that can manipulate the data of an object or
perform operations related to the object.
1. Operator Overloading
Operator overloading allows you to define custom behaviors for operators (e.g., +, -, *, /, etc.)
when applied to objects of user-defined types. This means that you can make operators work
with objects the same way they work with basic data types.
To overload an operator, you define a function using the operator keyword, followed by the
operator symbol. The function can be a member function of the class or a non-member function
(friend function).
Syntax:
returnType operator<operatorSymbol>(parameterList) {
// Function body
}
Suppose we have a Complex class that represents complex numbers, and we want to overload the
+ operator to add two complex numbers.
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize the complex number
Complex(float r, float i) : real(r), imag(i) {}
int main() {
Complex num1(3.2, 4.5), num2(1.7, 2.5);
Complex result = num1 + num2; // Using the overloaded '+' operator
return 0;
}
Explanation:
• Arithmetic operators: +, -, *, /, %
• Comparison operators: ==, !=, <, >, <=, >=
• Assignment operators: =, +=, -=, *=, /=
• Increment/Decrement: ++, --
• Input/Output operators: <<, >>
• Unary operators: -, ++, --, !, etc.
2. Function Overloading
Function overloading allows you to define multiple functions with the same name but different
parameter lists (i.e., different numbers or types of parameters). The compiler distinguishes
between these functions based on the number and types of arguments passed.
To overload a function, simply define multiple functions with the same name but different
parameter lists. The return type does not count towards function overloading.
Syntax:
returnType functionName(parameterList) {
// Function body
}
returnType functionName(anotherParameterList) {
// Function body
}
Let's overload the add function to handle both integer and float types.
#include <iostream>
using namespace std;
class Calculator {
public:
// Function to add two integers
int add(int a, int b) {
return a + b;
}
int main() {
Calculator calc;
cout << "Integer sum: " << intSum << endl; // Output: 15
cout << "Float sum: " << floatSum << endl; // Output: 16.0
return 0;
}
Explanation:
• Function Overloading: We have two add functions: one that takes int arguments and
another that takes float arguments.
• Usage: The compiler calls the correct version of add based on the type of arguments
provided.
1. Abstraction
Abstraction is the concept of hiding the complex implementation details and exposing only the
necessary parts of an object or system. This helps to reduce complexity and allows the
programmer to focus on high-level operations.
• Purpose: It helps to simplify interaction with objects by only showing the essential
features and hiding unnecessary details.
• How It Works: In OOP, abstract classes and interfaces are used to define what
operations can be performed, but without specifying how these operations are
implemented.
• Example: A Car class might have methods like start(), stop(), accelerate(). The
implementation details of these actions (e.g., the engine’s inner workings) are hidden, and
the user of the Car class only interacts with the exposed methods.
class Car {
public:
virtual void start() = 0; // Pure virtual function for abstraction
virtual void stop() = 0; // Pure virtual function for abstraction
};
In this example, Car is an abstract class, and its derived class Sedan provides the
implementation.
2. Encapsulation
Encapsulation is the process of bundling the data (attributes) and the methods (functions) that
operate on the data into a single unit, typically a class. It also involves restricting access to some
of the object’s components, making sure that data is protected from unauthorized access and
modification.
• Purpose: It helps protect the integrity of an object’s state by limiting direct access to its
internal data. Only authorized functions can modify or retrieve this data.
• How It Works: Data members are made private, and public methods (getters and setters)
are used to access and modify the data.
• Example:
class Account {
private:
double balance; // Private data
public:
// Getter function
double getBalance() {
return balance;
}
// Setter function
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
};
Here, the balance is encapsulated within the Account class, and the user can interact with it
only through the deposit method, ensuring the balance is only modified under specific
conditions.
3. Inheritance
Inheritance is the mechanism by which one class (the derived class) can inherit attributes and
methods from another class (the base class). This helps to achieve code reusability and method
overriding.
• Purpose: It allows new classes to take on properties and behaviors of existing classes,
facilitating reusability and maintaining relationships between classes.
• How It Works: The derived class inherits public and protected members from the base
class, and it can extend or modify the behavior by adding new members or overriding
base class methods.
• Example:
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
Here, Dog inherits from Animal. The Dog class can use the eat() method from Animal and also
add its own behavior with the bark() method.
• Types of Inheritance:
o Single Inheritance: A derived class inherits from one base class.
o Multiple Inheritance: A derived class inherits from more than one base class.
o Multilevel Inheritance: A derived class inherits from another derived class.
4. Polymorphism
Polymorphism is the ability of one object to take on many forms. It allows the same function or
operator to behave differently based on the context, especially when applied to different types of
objects.
• Purpose: It allows different objects to respond to the same method call in their own way,
which makes the program more flexible and extendable.
• Types of Polymorphism:
1. Compile-time Polymorphism (Static Polymorphism): Achieved through
function overloading and operator overloading. The method to be invoked is
determined at compile time.
2. Run-time Polymorphism (Dynamic Polymorphism): Achieved through method
overriding and virtual functions. The method to be invoked is determined at
runtime.
• Example (Run-time Polymorphism):
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound." << endl;
}
};
In this example, the sound() method is overridden in the Dog class. The actual method that gets
invoked depends on the type of the object (dynamic binding).
5. Template
A template in C++ is a feature that allows you to write generic programs, so that you can create
functions and classes to work with any data type.
• Purpose: It allows you to define functions, classes, and data structures that can operate
on any type of data, without needing to specify the type explicitly.
• How It Works: Templates can be used to create generic functions and generic classes.
The compiler will generate the correct version of the function/class based on the type of
argument passed.
• Example:
int main() {
cout << add(5, 10) << endl; // Works with int
cout << add(3.5, 4.5) << endl; // Works with double
return 0;
}
Here, the add function is a template that can add any two values of the same type, whether they
are integers, floating-point numbers, etc.
• Template Classes: You can also create template classes that work with any data type.
public:
Box(T v) : value(v) {}
T getValue() { return value; }
};
int main() {
Box<int> intBox(10);
Box<string> strBox("Hello");
cout << [Link]() << endl; // Output: 10
cout << [Link]() << endl; // Output: Hello
return 0;
}
Exception handling is a mechanism in C++ that allows you to handle runtime errors (or
exceptions) in a graceful and controlled way. Instead of the program crashing when an error
occurs, exception handling allows you to catch errors, report them, and recover from them.
Basic Structure
try {
// Code that might throw an exception
} catch (exception_type1 ex1) {
// Code to handle exception_type1
} catch (exception_type2 ex2) {
// Code to handle exception_type2
} catch (...) {
// Catch-all handler for any unknown exceptions
}
Explanation:
1. try block: You write the code that may throw an exception inside the try block.
2. throw keyword: When an error is detected, the throw keyword is used to throw an
exception.
3. catch block: The catch block catches and handles exceptions thrown by the try block.
You can have multiple catch blocks for different types of exceptions.
#include <iostream>
using namespace std;
class DivisionByZeroException {
public:
const char* what() const noexcept {
return "Error: Division by zero!";
}
};
int main() {
try {
int x = 10, y = 0;
double result = divide(x, y); // This will throw an exception
cout << "Result: " << result << endl;
} catch (const DivisionByZeroException& e) {
cout << [Link]() << endl; // Handle exception
}
return 0;
}
Explanation:
Built-in Exceptions
C++ has a standard set of exceptions that are defined in the <stdexcept> header. Some of the
most commonly used built-in exceptions are:
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
int x = 10, y = 0;
double result = divide(x, y); // This will throw an exception
cout << "Result: " << result << endl;
} catch (const runtime_error& e) {
cout << [Link]() << endl; // Handle exception
}
return 0;
}
Explanation:
You can have multiple catch blocks to handle different types of exceptions. The general order is
to catch specific exceptions first, and then catch the base std::exception to handle any
remaining errors.
try {
// Some code that might throw different exceptions
} catch (const std::invalid_argument& e) {
// Handle invalid_argument exception
} catch (const std::out_of_range& e) {
// Handle out_of_range exception
} catch (const std::exception& e) {
// Handle all other exceptions
}
The catch-all handler (catch(...)) is used when you don't know the type of exception that will
be thrown. It catches all exceptions that are not caught by other catch blocks.
try {
// Some code that might throw an unknown exception
} catch (...) {
cout << "Unknown error occurred!" << endl; // Catch all exceptions
}
Throwing Exceptions
You can throw exceptions manually in your program using the throw keyword. This can be used
to signal an error or exceptional condition that the caller must handle.
Custom Exceptions
You can define your own exceptions by creating classes that derive from std::exception or its
derived classes. By overriding the what() function, you can provide detailed error messages.