0% found this document useful (0 votes)
38 views278 pages

1 2 3 4 5 Merged

The document covers the fundamentals of programming, including algorithms, flowcharts, and computer languages, emphasizing their importance in problem-solving and software development. It discusses different types of programming languages, debugging techniques, and program design methodologies such as structured and modular programming. Additionally, it highlights the significance of compilers and interpreters in translating code, as well as the types of errors encountered in programming and strategies for debugging.

Uploaded by

nikhildubey2819
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)
38 views278 pages

1 2 3 4 5 Merged

The document covers the fundamentals of programming, including algorithms, flowcharts, and computer languages, emphasizing their importance in problem-solving and software development. It discusses different types of programming languages, debugging techniques, and program design methodologies such as structured and modular programming. Additionally, it highlights the significance of compilers and interpreters in translating code, as well as the types of errors encountered in programming and strategies for debugging.

Uploaded by

nikhildubey2819
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
You are on page 1/ 278

UNIT ONE

FUNDAMENTALS OF PROGRAMMING
CONTENT

Basics of Computer
Concepts of algorithm, Flow chart Compilers,
Languages,

Programming
Types of errors and Program design
Interpreter, Environments and
debugging techniques. techniques:
Debugging:

Structured, modular,
Bottom-up, top-down,
procedural, OOP
•Programming features:
•Data types, Expressions and
Operators-Arithmetic, unary,
logical, bitwise, relational,
assignment, comma operators.
•Data conversions. Input/Output
statements.
Concepts of algorithm

• An algorithm is a systematic approach to problem-solving,


involving logical steps to arrive at a solution. Whether
addressing mathematical or computer-related issues,
developing an algorithm is the initial phase of problem-solving.
It encompasses calculations, reasoning, and data processing,
and can be expressed through various means such as natural
languages, pseudocode, or flowcharts.
Use of Algorithm
• Computer Science: They underpin computer programming, addressing
tasks from basic sorting to complex endeavors like artificial intelligence.
• Mathematics: Algorithms solve mathematical problems, optimizing
solutions for linear equations or determining the shortest path in a graph.
• Operations Research: Algorithms optimize decisions in areas like
transportation, logistics, and resource allocation.
• Artificial Intelligence: Serving as the foundation, algorithms power
artificial intelligence and machine learning for tasks like image recognition
and decision-making.
• Data Science: In fields like marketing and healthcare, algorithms analyze
vast datasets, extracting valuable insights.
Flowchart

• Is the graphical or pictorial representation of an algorithm with the

help of different symbols, shapes, and arrows to demonstrate a process

or a program. With algorithms, we can easily understand a program.


Symbols in a
flowchart
Algorithm
and
Flowchart
• If you compare a
flowchart to a movie, then
an algorithm is the story
of that movie. In other
words, an algorithm is
the core of a flowchart.
• Computer languages:
Computer languages are formal systems
designed to communicate instructions to a
computer. They enable humans to write code
Basics of that computers can understand and execute.
Computer • Importance in programming:
Languages Essential for software development, computer
languages serve as the foundation for creating
applications, websites, and various software
solutions.
Like Python, Java, C and C++
Types of Computer Languages
• High-level languages: These languages are more abstract, making
them easier for humans to understand and write. Examples include
Python, Java, C++ and C#.
• Low-level languages: Closer to machine language, low-level
languages like Assembly , C and Machine Code provide more direct
control over hardware.
• Scripting languages: Interpreted languages like JavaScript and PHP
are often used for automating tasks and enhancing web development.
High-Level Languages
• Characteristics: High-level languages are designed for readability
and ease of use. They abstract complex operations, making it simpler
for programmers to express ideas.
• Examples: Python for its readability, Java for its portability, and C#
for its integration with Microsoft technologies.
• Use cases: High-level languages are commonly used in a wide range
of applications, from web development to artificial intelligence.
Low-Level Languages
Characteristics: Low-level languages offer more direct control over hardware, making them
suitable for system-level programming.

Examples: C language as a bridge between high-level languages and machine code, and
Machine Code as the binary representation understood by the computer's central processing
unit (CPU).
Role in system-level programming:

Low-level languages are crucial for tasks that require precise control over hardware resources.
Scripting Languages
Characteristics:

Scripting languages are often interpreted, allowing for quick development and testing. They are
commonly used for automating repetitive tasks.
Examples:

JavaScript for its role in web development, Ruby for its simplicity, and PHP for server-side scripting.

Applications:

Scripting languages are integral to web development, automation, and the creation of dynamic
content.
Choosing the Right Language

Factors to consider: The importance of considering project requirements, performance


needs, and ease of development when selecting a programming language.

Overview of popular languages:

Languages like Python for its versatility, Java for its platform independence, and C++ for
performance-critical applications.
• Explore and learn:

Explore different languages based on their project needs and interests.


• Compilers and interpreters share the task of
translating High-Level Language (HLL)

Compilers and source code into machine code

Interpreter understandable by computers. Typically,


computer programs are written in HLL for
human comprehension, but to make them
readable for computers, they must be
converted into machine language.
Con’t…

• A Compiler serves as a translator, converting High-Level


Language input into low-level language, such as machine or
assembly language. Its primary function is to transform
programming language codes into machine code (represented
in 0s and 1s) for computer comprehension.
Interpreter
• An interpreter is a program that translates a programming
language into a comprehensible language. The interpreter
converts high-level language to an intermediate language. An
Interpreter works line by line on a code.
Get Started With C

To start using C, you need two things:

• A text editor, like Notepad or Integrated Development


Environment(IDE) like Code::Block, VS Code to write C
code

• A compiler, like GCC, to translate the C code into a


language that the computer will understand.
Start first Program in C
• Let's create our first C file.
• Open VS Code and go to File > New > Empty File.
• Write the following C code and save the file as:
Example explained

Line 1: #include <stdio.h> is a header file library that lets us


work with input and output functions, such as printf()
(used in line 4). Header files add functionality to C
programs.
Con’t…
• Line 2: A blank line. C ignores white space. But we use it to
make the code more readable.
• Line 3: Another thing that always appear in a C program,
is main() This is called a function. Any code inside its curly
brackets {} will be executed.
• Line 4: the printf() is a function used to output/print text to the
screen. In our example it will output “I will be the best
programmer”.
Every C statement ends with
a semicolon ;
Con’t…

• Line 5: return 0 ends the main() function.

• Line 6: Do not forget to add the closing curly bracket }


to end the main function.
Variables
• Are containers for storing data values, like numbers and
characters.
• In C, there are different types of variables (defined
with different keywords), for example:
• int: stores integers (whole numbers), without decimals,
such as 123 -123
• float: - stores floating point numbers, with decimals,
such as 19.99 or -19.99
• char: - stores single characters, such as ‘a’ or ‘b’ single
quote.
Declaring Variable
• type variableName = value;

• int num = 10;

• int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
• The data type specifies the size and type of
C Data Types information the variable will store.
Basic Format Specifiers
Exercise
C Decimal Precision
• float myFloatNum = 3.5;
double myDoubleNum = 19.99;
printf("%f\n", myFloatNum); // Outputs 3.500000
printf("%lf", myDoubleNum); // Outputs 19.990000

• float myFloatNum = 3.5;


printf("%f\n", myFloatNum); // Default will show 6 digits
• printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
Exercise: • Make the output of the following example to
only show one digit after the decimal point:
Real time example
• // Create variables of different data types
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';
// Print the outputs
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
Type Conversion
• if you try to divide two integers, 5 by 2 you would
expect the result to be 2.5 But since we are working
with integers (and not floating-point values), the
following example will just output 2:
• int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2


There are two types of conversion
• Implicit Conversion (automatically)

• Explicit Conversion (manually)


Implicit Conversion
• Implicit conversion is done automatically by the
compiler when you assign a value of one type to
another.
• For example, if you assign an int value to a float.
• // Automatic conversion:
float myFloat = 9;

printf("%f", myFloat); // 9.000000


Explicit Conversion
• Explicit conversion is done manually by placing the type
in parentheses () in front of the value.

• // Manual conversion: int to float


float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000


You can also place the type in front of a variable

int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000


Constants
• If you don't want anyone to change existing variable values,
you can use the const keyword.

• const int myNum = 15; // myNum will always be 15

myNum = 10; // error

const int minutesPerHour = 60;

const float PI = 3.14;


Operators
• Operators are used to perform operations on variables
and values.

int sum1 = 100 + 50;


int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
Operators Groups

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators
Arithmetic Operators
• Arithmetic operators are used to perform common mathematical
operations.
Assignment Operators
• Assignment operators are used to assign values to
variables.
• int x = 10;

• int x = 10;
x += 5;
A list of all assignment operators
Comparison Operators

• Comparison operators are used to compare two values.

• This is important in programming, it helps us to find


answers and make decisions.

• The return value of a comparison is either 1 or 0 or true


and false.
A list of all comparison operators
Logical • Logical operators are used to determine the
logic between variables or values:
Operators
Programming
Environments and
Debugging Overview

• Introduction:
• Programming environments and debugging are
integral aspects of software development.
• A conducive programming environment and effective
debugging practices are crucial for writing high-
quality, error-free code.
• Importance:
• A well-configured programming environment
enhances developer productivity.
• Debugging ensures the identification and resolution
of issues, leading to reliable software.
In programming, errors can be broadly
categorized into three main types:
1. Syntax errors,

Error 2. Runtime errors


3. Logical errors.
Debugging is the process of identifying
and fixing these errors to ensure that the
program behaves as intended.
Types of error and techniques
• 1. Syntax Errors:
Syntax errors occur when the code violates the rules of the
programming language.
• Indicators:
• Typically detected by the compiler or interpreter during the compilation
or execution phase.
• Often accompanied by error messages pointing to the line and location
of the syntax issue.
Debugging Techniques

Carefully review the Check for missing or


error messages misplaced
provided by the punctuation, incorrect
compiler or keywords, or other
interpreter. syntax violations.
2. Runtime Errors
• Runtime errors occur during the
execution of the program and are
often related to issues like division by
zero, incorrect data types, or
undefined variables.
• Indicators:
• The program crashes or terminates
unexpectedly.
• Runtime error messages may provide
information about the nature of the
issue.
Debugging Techniques

1 2 3
Use print statements to Employ exception Utilize debugging tools to
trace the flow of the handling (try, except step through the code
program and identify the blocks) to catch and and inspect variable
point of failure. handle specific types of values during runtime.
errors.
• Logical errors do not result in syntax or
runtime errors, but they cause the
program to produce incorrect or
Logical unexpected outputs.
Errors • Indicators:
• The program runs without error messages,
but the output is not as expected.
• Review the program's logic and algorithms
to identify discrepancies.
Debugging • Use print statements strategically to output
intermediate values and verify calculations.
Technique • Employ systematic testing and code review
to catch logical errors early in the
s development process.
Common Print
Statements
Debugger
Tools
Logging
Code
Review

Debuggin • Insert print • Use integrated • Implement


statements at development logging to
• Conduct
thorough code
key points in environment record reviews with
g the code to
display
(IDE)
debuggers to
information
about the
peers
identify
to

variable values step through program's potential


Technique and trace the
program's
the code, set
breakpoints,
execution,
making it
errors,
especially

s execution. and inspect


variables.
easier to
analyze issues.
logical ones.
5. Unit Testing:
Write and run unit tests to ensure that
individual components of the code behave as
expected.
6. Pair Programming:
Collaborate with a colleague in pair
Con’t… programming to catch errors and share
insights.

Debugging is an essential skill for


programmers, and the ability to
troubleshoot effectively is crucial for
building robust and reliable software.
• Effective program design is crucial for
Program creating maintainable and scalable
software.
Design • Well-designed programs are easier to
Techniques understand, modify, and extend.
• Structured Programming:
A programming paradigm aimed at improving
the clarity, quality, and development time of a
computer program.
Example: Using control structures like
Structured sequences, selections, and iterations.
Programmi if condition:
# code block
ng else:
# code block
Modular Design Definition: Breaking down a
program into smaller, manageable, and
Modular independent modules.
Design Example: Creating separate modules for
input processing, data manipulation, and
output generation.
Example
# Module 1: Input processing
def process_input(data):
# code block
# Module 2: Data manipulation
def manipulate_data(data):
# code block
# Module 3: Output generation
def generate_output(data):
# code block
Bottom-Up
Approach
• Building the system from simple
components to more complex
ones.

• Example: Developing individual


functions or modules before
integrating them into the main
program.
Example
# Function 1
def simple_function():
# code block

# Function 2
def complex_function():
simple_function()
# additional code block
Top-Down Approach
• Starting with the main program and breaking it
into smaller modules.

• Example: Defining the main program structure


and then implementing each module.
Example
# Main Program
def main_program():
module_1()
module_2()

# Module 1
def module_1():
# code block
# Module 2
def module_2():
# code block
• Procedural Programming:
Organizing code as procedures or functions.
• Example: Defining procedures for specific
tasks.

Procedural # Procedure 1
def procedure_1():
Programmi # code block
ng # Procedure 2
• def procedure_2():
• # code block
Object-Oriented
Programming
(OOP)
OOP Definition: Organizing code around

objects that encapsulate data and behavior.

• Example : Defining classes and objects.


// Class definition
class Animal {
public:
Animal(std::string name) : name(name) {}
void make_sound() {
// code block
Example }
private:
std::string name;
};
// Object instantiation
Animal cat("Cat");
END UNIT ONE
UNIT TWO
FUNDAMENTALS OF PROGRAMMING
Content
• Control statements:
• While, do-while,
• for statements,
• nested loops,
• if else,
• switch,
• break, Continue, and goto statements,
• Iterations.
• Concept of subprograms.

• Functions:

• Storage class -Scope and extent of variables,

• Argument types- actual, formal, dummy.

• Function definition, declaration, prototype.

• Recursion.
Control Statement
While Loop
• The while loop is used to repeatedly execute a

block of code as long as the given condition is true.


Example
#include <stdio.h>

int main() {
int count = 0;
while (count < 5) {
printf("Count is %d\n", count);
count++;
}
return 0;
}
Practice Example One
• #include <stdio.h>

• int main() {
• int i = 1;
• while (i <= 5) {
• printf("%d ", i);
• i++;
• }
• return 0;
•}
Output

12345
Practice Example Two
• #include <stdio.h>

• int main() {
• int count = 3;
• while (count > 0) {
• printf("Countdown: %d\n", count);
• count--;
• }
• printf("Blastoff!\n");

• return 0;
• }
Output

Countdown: 3
Countdown: 2
Countdown: 1
Blastoff!
Practice Example Three
• #include <stdio.h>

• int main() {
• int num = 2;
• while (num <= 16) {
• printf("%d ", num);
• num *= 2;
• }
• return 0;
•}
Output

2 4 8 16
Do-While Loop:

• The do-while loop is used to execute a block of code at least once, and then repeatedly

execute it as long as the given condition is true.


Example
#include <stdio.h>

int main() {
int count = 0;
do {
printf("Count is %d\n", count);
count++;
} while (count < 5);
return 0;
}
Practice Example One
• #include <stdio.h>

• int main() {
• int i = 1;
• do {
• printf("%d ", i);
• i++;
• } while (i <= 5);
• return 0;
•}
Output

12345
Practice Example Two
• #include <stdio.h>

• int main() {
• int count = 3;
• do {
• printf("Countdown: %d\n", count);
• count--;
• } while (count > 0);
• printf("Blastoff!\n");
• return 0;
• }
Output

Countdown: 3
Countdown: 2
Countdown: 1
Blastoff!
Practice Example Three
• #include <stdio.h>

• int main() {
• int num = 2;
• do {
• printf("%d ", num);
• num *= 2;
• } while (num <= 16);
• return 0;
•}
Output

2 4 8 16
For Loop:

• The for loop is used to iterate over a sequence of

statements.
Example
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("Current number is %d\n", i);
}
return 0;
}
Nested Loops

• Nesting loops means placing one loop


inside another.
Example

1. #include <stdio.h>

2. int main() {
3. for (int i = 1; i <= 3; i++) {
4. for (int j = 1; j <= 3; j++) {
5. printf("(%d, %d)\n", i, j);
6. }
7. }
8. return 0;
9. }
If-Else Statement

• The if-else statement is used for


decision-making.
Example

#include <stdio.h>

int main() {
int num = 10;
if (num % 2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}
return 0;
}
Switch Statement

• The switch statement is used for


decision-making based on the
value of a variable.
Example
1. #include <stdio.h>
2. int main() {
3. int option = 2;
4. switch (option) {
5. case 1: printf("Case 1\n");
6. break;
7. case 2: printf("Case 2\n");
8. break;
9. case 3: printf("Case 3\n");
10. break;
11. default: printf("Default case\n");
12. }
13. return 0;
14. }
Rules for switch
statement
• Expression Type:
• The expression inside the switch statement must result in an
integral type (char, int, short, long) or an enumerated type.

• int option = 2;
• switch (option) {
• // Cases...
• }
Case Constants

• The case constants must be constant integral expressions. They


should not be variables or expressions.

• switch (expression) {
• case 1: // Valid constant
• // Code...
• break;
• // Other cases...
• }
Default Case

• The default case is optional and can be used for


handling values not covered by any of the case
statements.

• switch (expression) {
• // Cases...
• default:
• // Code for default case...
• }
Break Statement

A break statement is used to exit the switch statement. If it


is omitted, control will fall through to the next case.

• switch (expression) {
• case 1:
• // Code...
• break;
• case 2:
• // Code...
• break;
• }
Fall-Through

• If a break statement is omitted, the control will continue to the next case. This is known
as fall-through.

• switch (expression) {
• case 1:
• // Code...
• // No break, falls through to the next case
• case 2:
• // Code...
• break;
• }
Break Statement

• The break statement is used to terminate the innermost loop


(for, while, or do-while) or switch statement. When
encountered, the break statement immediately exits the loop
or terminates the switch statement, transferring control to the
statement following the loop or switch.
• #include <stdio.h>
Example
• int main() {
• int i;
• for (i = 1; i <= 10; i++) {
• if (i == 5) {
• break; // exit the loop when i is 5
• }
• printf("%d ", i);
• }
• return 0;
• }
In this example, the loop will print numbers from 1 to 4, and when i becomes 5,
the break statement is encountered, and the loop is exited.
Continue Statement

• The continue statement is used to skip the rest of

the code inside a loop for the current iteration and

move to the next iteration.


Example
• #include <stdio.h>

• int main() {
• int i;
• for (i = 1; i <= 5; i++) {
• if (i == 3) {
• continue; // skip the rest of the loop for i=3
• }
• printf("%d ", i);
• }
• return 0;
• }
In this example, the loop will print numbers 1, 2, 4, and 5. The continue statement skips the print statement for i=3.
Goto Statement

• The goto statement is used to transfer control to a labeled

statement in the same function. It's generally considered

bad practice and should be used cautiously to avoid

creating unreadable and unmaintainable code.


Example
• #include <stdio.h>

• int main() {
• int i = 1;
• loop_start:
• if (i <= 5) {
• printf("%d ", i);
• i++;
• goto loop_start; // jump to the labeled statement
• }
• return 0;
• }
In this example, the loop is simulated using the goto statement. It prints numbers from 1 to 5 and then exits.
subprograms

• In C, the concept of subprograms is implemented

through functions. Functions are blocks of code that

perform a specific task and can be called from other

parts of the program. They allow for code modularity,

reusability, and better organization. Here are key points

related to the concept of subprograms (functions) in C:


Function Declaration and Definition

• Declaration: Before using a function, you typically declare it by


specifying its name, return type, and parameters. This informs the
compiler about the function's signature.

int add(int a, int b); // Function declaration


Definition
• The actual code for the function is written separately, known as the
function definition.

• int add(int a, int b) {


• int c = a + b;
• return c;
•}
Function Call

Once a function is declared and defined, it can be called from other


parts of the program.

int result = add(5, 7); // Calling the add function


Example
#include <stdio.h>
// Function declaration
void greet() {
printf("Hello, welcome to the world of C programming!\n");
}
int main() {
// Calling the function
greet();
return 0;
}
Return Statement

• Functions can return a value using the return statement. The return
type is specified in the function declaration.

• int add(int a, int b) {


• return a + b;
• }
Parameters

• Functions can take parameters (inputs) to perform their task.


Parameters are specified in the function declaration.

• int add(int a, int b) {


• return a + b;
• }
Void Functions

• Functions that do not return a value are declared with the void
return type.

• void greet() {
• printf("Hello, World!\n");
• }
Storage Class - Scope and Extent of Variables:
• Storage Class defines the scope, visibility, and lifetime of a variable.

• There are four storage classes in C: auto, register, static, and extern.

• The auto storage class (default) is used for local variables. Variables are
created when the block containing the declaration is entered and
destroyed when it's exited.

• The static storage class is used for variables that retain their values
between function calls. It has internal linkage by default.
Example
• #include <stdio.h>
• void exampleFunction() {
• // Automatic variable (default storage class)
• int autoVar = 10;
• // Static variable
• static int staticVar = 20;
• printf("Auto Variable: %d\n", autoVar);
• printf("Static Variable: %d\n", staticVar);
• }
• int main() {
• exampleFunction();
• // autoVar is not accessible here as it has local scope to exampleFunction
• return 0;
• }
register Storage Class

• The register storage class is used to define local variables that should
be stored in a register instead of RAM.

• The keyword register suggests to the compiler that the variable will
be heavily used, and it should be kept in the CPU register for faster
access.
Example
• #include <stdio.h>
• int main() {
• register int i; // Declare a register variable

• for (i = 0; i < 5; i++) {


• printf("%d ", i);
• }
• return 0;
•}
In this example, the register keyword suggests that variable i should be
stored in a register.
extern Storage Class

• The extern storage class is used to declare a global variable that is


defined elsewhere in the program.
• When you use extern, you're telling the compiler that the variable is
declared somewhere else, and it should be linked at the time of
compilation.
• It's often used when a variable is defined in one source file and needs
to be used in another.
Example
• // File1.c
• #include <stdio.h>

• extern int globalVar; // Declare the global variable

• int main() {
• printf("Value of globalVar: %d\n", globalVar);

• return 0;
•}
Argument Types - Actual, Formal, Dummy

• In function calls, actual parameters (arguments) are the values passed


to the function.
• Formal parameters are the parameters listed in the function
definition.
• Dummy parameters are used in function prototypes to indicate the
number and type of arguments the function expects.
Example
• #include <stdio.h>
• // Function prototype with dummy parameters
• void display(int num1, int num2);
• int main() {
• int a = 10, b = 20;
• // Calling the function with actual parameters
• display(a, b);
• return 0;
• }
• // Function definition with formal parameters
• void display(int num1, int num2) {
• // Accessing formal parameters
• printf("Formal parameters: num1 = %d, num2 = %d\n", num1, num2);
• }
Function Definition, Declaration, Prototype:

• A function definition includes the actual code that makes up the


function.
• A function declaration provides information to the compiler about the
function's name, return type, and parameters.
• A function prototype is a declaration that tells the compiler what the
function looks like.
Example
• #include <stdio.h>
• // Function Declaration (Prototype)
• int multiply(int, int);
• int main() {
• int x = 4, y = 5;
• // Function Call
• int product = multiply(x, y);
• printf("Product: %d\n", product);
• return 0;
• }
• // Function Definition
• int multiply(int num1, int num2) {
• return num1 * num2;
• }
Recursion:
• Recursion is a programming technique where a function calls
itself directly or indirectly.
• In recursive functions, there must be a base case to prevent
infinite recursion.
• Factorial calculation is a classic example of a recursive function.
Example

int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
UNIT THREE
FUNDAMENTALS OF PROGRAMMING
Content
• Headers and library functions
• Macros.
• Array: Array representation
• Operations on array elements
• Using arrays
• Multidimensional arrays
• Strings, operations on strings
• Structures & Unions
• Declaration and usage of structures and Unions.
Headers and Library Functions
• Headers in C are files that contain declarations of functions, data
types, and macros.
• They provide interfaces to use functionalities defined in libraries.
• Library functions are predefined functions provided by C libraries that
can be used to perform various tasks.
• For example, stdio.h is a header file that contains declarations for
standard input/output functions like printf() and scanf().
Example
• #include <stdio.h>

• int main() {
• printf("Hello, world!\n");
• return 0;
•}
Macros

• Macros in C are preprocessor directives that define symbolic

constants or perform text replacement in the code.

• They are defined using the #define directive and are typically used for

defining constants or creating simple functions-like constructs.


Example
• #include <stdio.h>
• #define PI 3.14159
• #define SQUARE(x) ((x) * (x))

• int main() {
• double radius = 5.0;
• printf("Area of the circle: %f\n", PI * SQUARE(radius));
• return 0;
•}
Array

• An array in C is a collection of elements of the same data type stored

in contiguous memory locations.

• Elements in an array can be accessed using an index. Arrays are

declared using square brackets [].


Example
• #include <stdio.h>

• int main() {
• int arr[5] = {1, 2, 3, 4, 5};
• printf("First element: %d\n", arr[0]);
• return 0;
•}
Length of Array

The length of an Array can be specified by any positive integer constant


expression.
Like

int arr[5];

int arr[5+5];

int arr[5*4];

int arr[-6];

int x;
int arr[x = 21/7];
SPECIFYING THE LENGTH OF ARRAY USING MACRO IS AN EXCELLENT PRACTICE.

#define N 10
int arr[N];
Example without macro
#include <stdio.h>
int main(){
int arr[10], i;
for(i = 0; i < 10; i++){
printf(“Enter the value for index %d: “, i);
scanf(“%d” , &arr[i]);
}
printf(“\n Array elements are as follows: \n”);
for(i = 0 ; i < 10; i++){
printf(“%d “, arr[i]);
}
return 0;
}
Example with macro
#include <stdio.h>
#define N 10
int main(){
int arr[N], i;
for(i = 0; i < N; i++){
printf(“Enter the value for index %d: “, i);
scanf(“%d” , &arr[i]);
}
printf(“\n Array elements are as follows: \n”);
for(i = 0 ; i < N; i++){
printf(“%d “, arr[i]);
}
return 0;
}
Initializing an array
If elements are lesser than length

int arr[10] = {1,2,3,5,7,8};

int arr[10] = {1,2,3,5,7,8,0,0,0,0};


Designated • Designated initialization is a feature that
allows to initialize specific elements of an
Initialization array explicitly by specifying their indices
of arrays within braces {}.
int arr[10] = {1,0,0,0,0,4,5,0,0,0};

We want:
1 in position 0
4 in position 5
5 in position 6
int arr[10] = { [0] = 1 , [5] = 4, [6] = 5};
• #include <stdio.h>

• int main() {
• // Array with designated initialization
• int arr[5] = {[1] = 10, [3] = 30};
• // Printing the elements of the array
• for (int i = 0; i < 5; i++) {
• printf("arr[%d] = %d\n", i, arr[i]);
• }
• return 0;
• }
Operations on Array Elements

• Operations on array elements include accessing, modifying, and

performing computations on array elements using loops or other

techniques.
Example
• #include <stdio.h>

• int main() {
• int arr[5] = {1, 2, 3, 4, 5};
• int sum = 0;
• for (int i = 0; i < 5; i++) {
• sum += arr[i];
• }
• printf("Sum of array elements: %d\n", sum);
• return 0;
• }
Practice Examples
• Write a program that finds the maximum element in an array of
integers.

int arr[] = {5, 8, 3, 10, 6};


Solution
• #include <stdio.h>
• int main() {
• int arr[] = {5, 8, 3, 10, 6};
• int size = sizeof(arr) / sizeof(arr[0]);
• int max = arr[0];
• for (int i = 1; i < size; i++) {
• if (arr[i] > max) {
• max = arr[i];
• }
• }
• printf("Maximum element in the array: %d\n", max);
• return 0;
• }
Second Practice
• Write a program that reverses the elements in an array.

int arr[] = {1, 2, 3, 4, 5};


• #include <stdio.h>
• int main() {
• int arr[] = {1, 2, 3, 4, 5};
• int size = sizeof(arr) / sizeof(arr[0]);
• printf("Original array: ");
• for (int i = 0; i < size; i++) {
• printf("%d ", arr[i]);
• }
• printf("\nReversed array: ");
• for (int i = size - 1; i >= 0; i--) {
• printf("%d ", arr[i]);
• }
• printf("\n");
• return 0;
• }
Third Practice
• Write a program that counts the number of even elements in an array.

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


Solution
• #include <stdio.h>
• int main() {
• int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
• int size = sizeof(arr) / sizeof(arr[0]);
• int count = 0;
• for (int i = 0; i < size; i++) {
• if (arr[i] % 2 == 0) {
• count++;
• }
• }
• printf("Number of even elements in the array: %d\n", count);
• return 0;
• }
How many elements are there in these arrays?
sizeof() operator
sizeof(name_of_arr)
sizeof(name_of_arr[0]
To find the number of elements in array
Multidimensional Arrays

• Multidimensional arrays are arrays with more than one dimension. They can be thought
of as arrays of arrays.
Syntax for two-dimensional array
Visualizing two dimensional array
Combining
Size of an array
Initializing two dimensional array
Better approach
How to access elements in 2D array
How to print 2 D array
Practice Examples
• Write a program to find the transpose of a given 2D array.
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int transpose[COLS][ROWS];
// Finding transpose of the matrix
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Printing the transpose matrix
printf("Transpose of the matrix:\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Second Practice
• Write a program to find the largest element in a 2D array and print its
position (row and column).
• #include <stdio.h>
• #define ROWS 3
• #define COLS 3
• int main() {
• int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
• int max = matrix[0][0];
• int maxRow, maxCol;
• // Finding the largest element and its position
• for (int i = 0; i < ROWS; i++) {
• for (int j = 0; j < COLS; j++) {
• if (matrix[i][j] > max) {
• max = matrix[i][j];
• maxRow = i;
• maxCol = j;
• }
• }
• }
• // Printing the largest element and its position
• printf("Largest element in the matrix: %d\n", max);
• printf("Position: Row %d, Column %d\n", maxRow + 1, maxCol + 1);
• return 0;
• }
Third Practice
• Write a program to search for a specific element in a 2D array and
print its position (row and column) if found.
#include <stdio.h>
#include <stdbool.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int searchElement = 5;
bool found = false;
int foundRow, foundCol;
// Searching for the element
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (matrix[i][j] == searchElement) {
found = true;
foundRow = i;
foundCol = j;
break;
}}
if (found) {
break; } }
// Printing the search result
if (found) {
printf("Element %d found at position: Row %d, Column %d\n", searchElement, foundRow + 1, foundCol +
1);
} else {
printf("Element %d not found in the matrix.\n", searchElement);
} return 0;
Syntax for three dimensional
array

data_type array_name[size1][size2][size3];

int cube[2][3][4] = { {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, {{13, 14, 15, 16},
{17, 18, 19, 20}, {21, 22, 23, 24}}};
Example
• #include <stdio.h>
• int main() {
• // Declaration and initialization of a three-dimensional array
• int cube[2][3][4] = {
• {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
• {{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}
• };
• // Accessing and printing elements of the three-dimensional array
• printf("Elements of the three-dimensional array:\n");
• for (int i = 0; i < 2; i++) {
• for (int j = 0; j < 3; j++) {
• for (int k = 0; k < 4; k++) {
• printf("%d ", cube[i][j][k]);
• }
• printf("\n");
• }
• printf("\n");
• }
• return 0;
• }
Strings, Operations on Strings

• Strings in C are arrays of characters terminated by a null character \0.

Operations on strings include concatenation, comparison, copying,

etc.
Example
• #include <stdio.h>
• #include <string.h>

• int main() {
• char str1[] = "Hello";
• char str2[] = "World";
• strcat(str1, str2);
• printf("Concatenated string: %s\n", str1);
• return 0;
•}
Structures & Unions

• Structures and unions are user-defined data types that allow storing

different types of data under a single name.

• Structures allocate memory for each member individually, while

unions allocate memory that is the size of the largest member.


Example
• // Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Assign values to members of s1
s1.myNum = 13;
s1.myLetter = 'B';
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
UNIT FOUR
FUNDAMENTALS OF PROGRAMMING
Content
• Pointers:
• Pointer and address arithmetic,
• Pointer operations and declarations,
• Pointer and arrays,
• Pointer to structure.
• Call by value,
• Call by reference.
• Dynamic memory allocation.
• Sorting and searching algorithms:
• Selection sort,
• Bubble sort,
• Insertion sort,
• Linear and binary search.
Pointers
Pointer is a special variable that can store some address.
Syntax for declaring pointer variable
Examples
Need of address of operator (&)
Like
Important points
Value of operator • Value of operator/indirection operator/dereference
operator is an operator that is used to access the
(*) value stored at the location pointed by the pointer.
We can also change the value of the object by the pointer.
Important point
One more point
Example: Incrementing and decrementing pointers

int arr[5] = {1, 2, 3, 4, 5};

int *ptr = &arr[0]; // Pointer to the first element of arr

ptr++; // Incrementing pointer

printf("Next element: %d\n", *ptr); // Outputs: 2

ptr--; // Decrementing pointer

printf("Previous element: %d\n", *ptr); // Outputs: 1


Pointer and Arrays

Arrays in C/C++ can be accessed using pointers.

Arrays and pointers are closely related in C/C++.


Example: Accessing array elements using pointers

int arr[5] = {10, 20, 30, 40, 50};

int *ptr = arr; // Pointer to the first element of arr

printf("First element: %d\n", *ptr); // Outputs: 10

ptr++; // Moving to the next element

printf("Second element: %d\n", *ptr); // Outputs: 20


Pointer to Structure

• Pointers can also be used with structures in C/C++.

• They allow efficient manipulation and passing of structures.

• Structures and unions are user-defined data types that allow storing different types of
data under a single name.

• Structures allocate memory for each member individually, while unions allocate
memory that is the size of the largest member.
Structure is the best solution for such problems

• Structure is user defined data type that can be used to group elements of different types into a
single type.
Example: Using a pointer to access structure
members

struct Point {
int x;
int y;
};

struct Point p1 = {5, 10};


struct Point *ptr = &p1; // Pointer to struct Point

printf("Coordinates: (%d, %d)\n", ptr->x, ptr->y); // Accessing structure members using pointer
Searching algorithms
Linear search

Is the simplest search algorithm. It works by checking each element in a

list one by one until it finds the element it is looking for. Linear search is

not very efficient for large lists, but it can be effective for small lists.
Example
#include <stdio.h>
// Function to perform linear search
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index if key is found
}
}
return -1; // Return -1 if key is not found
}
int main() {
int arr[] = {12, 45, 23, 6, 78, 54, 39};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 78;
// Perform linear search
int index = linearSearch(arr, n, key);
if (index != -1) {
printf("Element found at index: %d\n", index);
} else {
printf("Element not found\n");
}
return 0;
}
Binary search

• Is a more efficient search algorithm than linear search. It works by

dividing the list in half and then searching the half that contains the

element it is looking for. Binary search can be used to search sorted

lists of any size.


Example
#include <stdio.h>
// Function to perform binary search
int main() {
int binarySearch(int arr[], int left, int right, int key) { int arr[] = {6, 12, 23, 45, 54, 78, 39};
while (left <= right) { int n = sizeof(arr) / sizeof(arr[0]);
int mid = left + (right - left) / 2; int key = 78;
// Check if key is present at mid
if (arr[mid] == key) { // Perform binary search (array must
return mid; be sorted)
} int index = binarySearch(arr, 0, n - 1,
// If key is greater, ignore left half
key);
if (arr[mid] < key) {
left = mid + 1; if (index != -1) {
} printf("Element found at index:
// If key is smaller, ignore right half %d\n", index);
else { } else {
right = mid - 1;
} printf("Element not found\n");
} }
// Key not found return 0;
return -1;
} }
Sorting Algorithms
Merge sort

• Is a sorting algorithm that works by dividing a list into two halves,

sorting each half, and then merging the two sorted halves

together. Merge sort is a very efficient sorting algorithm and can be

used to sort lists of any size.


Example
#include <stdio.h> // Copy the remaining elements of L[], if any
while (i < n1) {
int main() {
// Function to merge two subarrays arr[left..mid] and arr[k] = L[i]; int arr[] = {12, 11, 13, 5, 6, 7};
arr[mid+1..right] i++; int n = sizeof(arr) / sizeof(arr[0]);
void merge(int arr[], int left, int mid, int right) { k++;
int n1 = mid - left + 1; }
int n2 = right - mid; printf("Original array: ");
// Copy the remaining elements of R[], if any
while (j < n2) {
for (int i = 0; i < n; i++) {
// Create temporary arrays arr[k] = R[j]; printf("%d ", arr[i]);
int L[n1], R[n2]; j++; }
k++; printf("\n");
// Copy data to temporary arrays L[] and R[] }
for (int i = 0; i < n1; i++) { }
}
L[i] = arr[left + i]; // Perform merge sort
// Function to perform merge sort on array mergeSort(arr, 0, n - 1);
for (int j = 0; j < n2; j++) { arr[left..right]
R[j] = arr[mid + 1 + j]; void mergeSort(int arr[], int left, int right) {
} if (left < right) {
int mid = left + (right - left) / 2;
printf("Sorted array: ");
// Merge the temporary arrays back into arr[left..right] for (int i = 0; i < n; i++) {
int i = 0, j = 0, k = left; // Sort first and second halves printf("%d ", arr[i]);
while (i < n1 && j < n2) { mergeSort(arr, left, mid); }
if (L[i] <= R[j]) { mergeSort(arr, mid + 1, right);
arr[k] = L[i]; printf("\n");
i++; // Merge the sorted halves
merge(arr, left, mid, right);
} else {
} return 0;
arr[k] = R[j]; } }
j++;
}
k++;
}
Selection sort

• Is a sorting algorithm that works by finding the smallest element in a

list and then swapping it with the first element in the list. Selection

sort is a simple sorting algorithm, but it is not very efficient for large

lists.
1 2

5
3 4
Example
#include <stdio.h> int main() {
int arr[] = {64, 25, 12, 22, 11};
// Function to perform selection sort int n = sizeof(arr) / sizeof(arr[0]);
void selectionSort(int arr[], int n) { printf("Original array: ");
for (int i = 0; i < n - 1; i++) { for (int i = 0; i < n; i++) {
int minIndex = i; printf("%d ", arr[i]);
// Find the index of the smallest element in the unsorted }
part of the array printf("\n");
for (int j = i + 1; j < n; j++) { // Perform selection sort
if (arr[j] < arr[minIndex]) { selectionSort(arr, n);
minIndex = j;
} printf("Sorted array: ");
} for (int i = 0; i < n; i++) {
// Swap the smallest element with the first element of printf("%d ", arr[i]);
the unsorted part }
int temp = arr[i]; printf("\n");
arr[i] = arr[minIndex];
arr[minIndex] = temp; return 0;
} }
}
Insertion sort

• Is a sorting algorithm that works by inserting each element of a list

into its correct position in the sorted list. Insertion sort is a simple

sorting algorithm, but it is not very efficient for large lists.


Example
#include <stdio.h>
int main() {
// Function to perform insertion sort int arr[] = {12, 11, 13, 5, 6};
void insertionSort(int arr[], int n) { int n = sizeof(arr) / sizeof(arr[0]);
int i, key, j; printf("Original array: ");
for (i = 1; i < n; i++) { for (int i = 0; i < n; i++) {
key = arr[i]; printf("%d ", arr[i]);
j = i - 1; }
printf("\n");
// Move elements of arr[0..i-1], that are greater
than key, to one position ahead of their current position // Perform insertion sort
while (j >= 0 && arr[j] > key) { insertionSort(arr, n);
arr[j + 1] = arr[j]; printf("Sorted array: ");
j = j - 1; for (int i = 0; i < n; i++) {
} printf("%d ", arr[i]);
arr[j + 1] = key; }
} printf("\n");
}
return 0;
}
Bubble sort

• Is the simplest sorting algorithm that works by repeatedly

swapping the adjacent elements if they are in the wrong order.

This algorithm is not suitable for large data sets as its average

and worst-case time complexity is quite high.


QuickSort

• is a sorting algorithm based on the divide and conquer

algorithm that picks an element as a pivot and partitions the

given array around the picked pivot by placing the pivot in its

correct position in the sorted array.


Important Point

• The best sorting and searching algorithm to use will depend on the

specific needs of the application. For example, if the list is small,

linear search may be the best option. If the list is large and sorted,

binary search may be the best option. If the list is large and not

sorted, merge sort or quick sort may be the best option.


UNIT FIVE
FUNDAMENTALS OF PROGRAMMING
Content
• File Handling:
• Declaration of files,
• types of files File pointer.
• File input/ output and usage,
• File operation
• Introduction to Object Oriented Programming:
• OOPS concepts,
• OOP languages- C++, Python etc.
File Handling

• In C, we can create, open, read, and write to files


by declaring a pointer of type FILE, and use the
fopen() function:

• FILE *fptr
fptr = fopen(filename, mode);
Con’t…
• To create a file, you can use the w mode inside
the fopen() function.
Create a
File • The w mode is used to write to a file. However,
if the file does not exist, it will create one for
you:
Example
int main() {
FILE *fptr;

// Create a file
fptr = fopen("filename.txt", "w");

// Close the file


fclose(fptr);

return 0; // Return 0 to indicate success


}
To create file in specific folder, use absolute path as:

fptr = fopen("C:\directoryname\filename.txt", "w");


We can use the w mode from the previous
example and write something to it.

Write To a File The w mode means that the file is opened


for writing.

To insert content to it, you can use the


fprintf() function and add the pointer
variable (fptr in our example) and some text
Example
int main() {
FILE *fptr;

// Create a file
fptr = fopen("filename.txt", "w");

// Write some text to the file


fprintf(fptr, “Adding this text to filename.txt");
// Close the file
fclose(fptr);

return 0; // Return 0 to indicate success


}
• If you write to a file that already
exists, the old content is deleted,
Important Point
and the new content is inserted.
This is important to know, as you
might accidentally erase existing
content.
Append Content To a File

If you want to add content to a file without deleting the old


content, you can use the a mode.

The a mode appends content at the end of the file:


Example

int main() {
FILE *fptr;

// Create a file
fptr = fopen("filenamef.txt", "a");

// Write some text to the file


fprintf(fptr, “\nAppend this");
// Close the file
fclose(fptr);

return 0; // Return 0 to indicate success


}
Important Point

• Just like with the w mode; if the file does not exist, the a mode will

create a new file with the "appended" content.


Read a File

In the previous example, we To read from a file, In order to read the content The fgets() function takes fgets(myString, 100, fptr);
wrote to a file using w and a of filename.txt, we can use three parameters:
modes inside the fopen() we can use the r the fgets() function.
function. mode:
Con’t…

The first parameter specifies where to store the file content,


which will be in the myString array we just created.

The second parameter specifies the maximum size of data to


read, which should match the size of myString (100).

The third parameter requires a file pointer that is used to


read the file (fptr in our example).
Example
int main() {
FILE *fptr;
// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file


char myString[100];

// Read the content and store it inside myString


fgets(myString, 100, fptr);

// Print file content


printf("%s", myString);

// Close the file


fclose(fptr);

return 0;
}
Important Point

• The fgets function only reads the first line of the file.

• To read every line of the file, we can use a while loop:


Example
• int main() {
• FILE *fptr;
• // Open a file in read mode
• fptr = fopen("filename.txt", "r");

// Store the content of the file
• char myString[100];

// Read the content and print it
• while(fgets(myString, 100, fptr)) {
• printf("%s", myString);
• }

// Close the file
• fclose(fptr);

return 0;
• }
Object Oriented and
Procedural Programming

Write once run anywhere!


Object Oriented Concepts

• To develop an application we require a programming language which

uses one of the following concepts:

a. Procedural Oriented Programming Concepts

b. Object Oriented Programming Concepts


Procedural Oriented Programming Concepts
• A language is said to be procedural oriented if the applications are
developed with the help of procedures or functions.

• Examples of Procedural Oriented Programming concepts are:

• C Language , COBAL , FORTRAN , PASCAL
Limitations of Procedural Programming
▪ The applications which are develop by using procedural oriented programming languages
are difficult to maintain and debugging of such applications are time consuming.

▪ The applications that are develop by using procedural oriented programming languages
do not provide full security to the data.

▪ The applications that are develop by using procedural oriented programming concepts
give more importance to the functions rather than data, the data available in the
applications that are develop by using procedural oriented programming concepts are
open and therefore they are not suitable for developing distributed applications.
Continue…

▪ The applications which are developed by using procedural oriented programming

concepts are difficult to enhance that is, it does not support the integration of new

modules.

▪ The procedure and functions are the fundamental concepts of procedural oriented

programming concepts, the design of these fundamental concepts are very weak

therefore they are not suitable to develop real time and complex applications.
Note:

• The procedural oriented languages are also called as structured programming language.

• Object Oriented Programming Concepts

• The applications which are develop with the help of objects and classes are said to

follow object oriented programming concepts.


Example of Languages using object oriented concepts are:

• Simula, C++ , JAVA , .NET , RUBBY , Small talk , LISP, Python

• Even though C++ as an object oriented programming language , but

according to programming language experts it is called as partial

object oriented language because of the following reasons:


Continue…

▪ In a C++ application we can write some code inside the class and some code

outside the class.

▪ An application in C++ can be develop without following any object oriented

programming concepts.

▪ The friend function concept in C++ can violate (break) all the security provide for

the data, and accessing it.


Continue…
• The object and classes are the fundamental concepts of object
oriented programming.
Object

a) Any entity that exist physically in the real world , which requires
memory called as object.
b) Every object will contain some properties and actions.
c) The properties are data or information which describe the object
and they are represented by variable.
d) The actions are the task or the operations performed by objects and
they represent by methods.
Class

▪ A class is a collection of common properties and common actions of a group of objects.

▪ A class can be considered as a plan, blueprint or model for creating the objects.

▪ For every class we can create (n) numbers of objects. And without a class object creation

is not possible.

▪ An object is an instance of a class.


Con’t…

▪ All the object oriented programming concepts are derived from the real world,

from human being lives so that programming becomes so simpler.

▪ The programmer can understand the concepts easily and implement them

without any difficulty.

▪ The design of the object oriented programming concept is very strong, and they

are suitable for developing real time and complex applications.


The various object oriented programming concepts are:

1. Encapsulation

2. Inheritance

3. Polymorphism
Encapsulation

It is the process of bindings the variables and methods into a single entity.

• Encapsulation can be achieved with the help of a class.

• Using encapsulation we can improve the maintenance of the applications.

• Using encapsulation we can achieve data hiding (if we have a class) using

encapsulation we can implement abstraction.


Abstraction means

• (which will decide what to hide and what to presents that is we can implement security.

• Using encapsulation we can isolate or separate the members from one class to another

class and thereby reducing the debugging time.

• For example we are creating an application for a bank, a bank has employee and

customers so we can create separate class for employee details like ID, Name and

separate class for its customers as per below:


Example
• public class Customer{

• int ID;
• String name;
• }

• public class Employee{
• int ID;
• String name;
• }
Inheritance
• It is a process of acquiring the members from one class to another class.
• Using inheritance we can achieve reusability and thereby reducing the code
size and development time of the application.
• Like:
• In a company if we develop an application for rate of interest as rate of
interests are different so if one programmer develop one structure or
application for car loan we can use it for gold loan, house loan and etc.
Continue…
• Or Microsoft has developed Windows XP supposed in 5 years and after 2 years wanted to develop

Window Vista now he doesn’t require 5 years more to develop Windows Vista he can use the

concepts of Inheritance and inherit all the properties, functions and methods which were used for

developing Windows XP and only add some new updates to it and change the name from XP to

Vista so now it will only 5-8 months approximately.

• It should not be left unsaid that the concept of inheritance plays key role in technology world.
Polymorphism

• If a single entity shows multiple behaviours or forms then that is said

to be polymorphism using polymorphism we can achieve flexibility

where a single entity can perform different operations according to

the requirement.
Class

Using a class we can achieve encapsulation.

• Using a class we can create user defined data type where we can store (n)

numbers of values and any type of values, according to the application

requirements a class can contain variables and methods which are together called

as members of the class.

• The Java program can contain (n) numbers of classes.


How to write a class in Java.

• Syntax:
• Class className{
• Datatype variable1;
• Datatype variable2;
• Datatype variable3;
• :
• :
• Return type methodName1(parameters)
• {
• Statements;
• }
• Return type methodName2(parameters)
• {
• Statements;
• }
• :
• :
• }
Example
class Student{
• int rollName;
• double marks;
• String name;
• void display(){
• System.out.println("Roll No: " +rollName);
• System.out.println("Mark: " +marks);
• System.out.println("Name: " +name);
• }
• public static void main(String args[]){
• System.out.println("Student Information");
• Student st = new Student();

• st.display();
• }
•}
File Name Student.Java
• When the above Java program Student.Java is compiled the compiler will verify
whether the Java code available in the program is valid or not, if valid the
compiler generates Student.class.
• The .class file generated by the compiler will be provided to the JVM for
execution.
• The execution of the Java program will be done by JVM and it begins from the
main method.
• Initially the Java stack will be empty.

You might also like