0% found this document useful (0 votes)
6 views

Unit 2 Cpp(Bt205)

The document covers algorithms, flowcharts, and programming paradigms, explaining their characteristics, differences, and when to use each. It also discusses the evolution of programming languages across five generations, highlighting key features and examples for each. Additionally, it introduces basic C++ programming concepts, including variables, keywords, and conditional constructs.

Uploaded by

rishitagupta2007
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)
6 views

Unit 2 Cpp(Bt205)

The document covers algorithms, flowcharts, and programming paradigms, explaining their characteristics, differences, and when to use each. It also discusses the evolution of programming languages across five generations, highlighting key features and examples for each. Additionally, it introduces basic C++ programming concepts, including variables, keywords, and conditional constructs.

Uploaded by

rishitagupta2007
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/ 26

Unit 2

Algorithms & Flowcharts


1. Algorithms
An algorithm is a step-by-step procedure to solve a problem or perform a task. It is
written in a human-readable format before being implemented in a programming
language.

Characteristics of a Good Algorithm:

• Unambiguous – Each step should be clear and precise.


• Input & Output – Should take zero or more inputs and produce at least one
output.
• Finiteness – Must terminate after a finite number of steps.
• Feasibility – Should be implementable with available resources.
• Language Independent – Should be written in a way that can be implemented
in any programming language.

Example: Algorithm to Add Two Numbers

1. Start
2. Read first number (A)
3. Read second number (B)
4. Compute Sum = A + B
5. Display Sum
6. Stop

Algorithm: Simple Interest Calculation


Step 1: Start
Step 2: Input the principal amount P
Step 3: Input the rate of interest R
Step 4: Input the time period T
Step 5: Calculate the simple interest using the formula:
SI = (P × R × T) / 100
Step 6: Display the value of SI
Step 7: End

2. Flowcharts
A flowchart is a graphical representation of an algorithm using symbols to denote
different operations.

Common Flowchart Symbols:

Example: Flowchart to Add Two Numbers

Co
Start


Read A


Read B


Sum = A + B


Display Sum


Stop

Flowchart: Simple Interest Calculation

Start

Input Principal (P)

Input Rate of Interest (R)

Input Time (T)

Calculate Simple Interest: SI = (P × R × T) / 100

Display SI

End
Differences Between Algorithm & Flowchart
Algorithm Flowchart
Text-based representation. Graphical representation.
Uses natural language or pseudocode. Uses symbols and arrows.
Easier to debug and analyze logic. Easier to visualize the flow of control.
No strict rules for writing. Follows standardized symbols.

4. When to Use Which?

• Use algorithms when:


o You need a clear, step-by-step explanation.
o You are working on complex logic before coding.
• Use flowcharts when:
o You want to visualize the program flow.
o Explaining the logic to non-programmers.

Procedural Programming vs. Object-Oriented


Programming (OOP)
Both Procedural Programming and Object-Oriented Programming (OOP) are
programming paradigms used to structure code, but they follow different approaches.
Below is a detailed comparison:

1. Procedural Programming (PP)


Procedural Programming is based on the concept of procedures (functions) that
operate on data.

• Programs are divided into functions (or subroutines).


• Follows a top-down approach (breaks problems into smaller functions).
• Data and functions are separate.

Key Features:

✔ Focuses on procedures/functions rather than data.


✔ Uses global data (variables can be accessed by any function).
✔ No access modifiers (like private, public).
✔ Less code reusability (functions are written for specific tasks).
✔ Examples: C, Pascal, BASIC, FORTRAN.

Example in C:
#include <stdio.h>

// Function to add two numbers (Procedural approach)


int add(int a, int b) {
return a + b;
}

int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2);
printf("Sum: %d", sum);
return 0;
}

Explanation:

• add() is a function that performs an operation.


• Data (num1, num2) and functions (add()) are separate.

2. Object-Oriented Programming (OOP)


OOP is based on objects that contain data (attributes) and methods (functions).

• Programs are divided into classes & objects.


• Follows a bottom-up approach (builds small components first).
• Combines data + functions into a single unit (object).

Key Features:

✔ Encapsulation – Bundles data & methods into a class.


✔ Inheritance – Allows classes to inherit properties from other classes.
✔ Polymorphism – One method can behave differently in different contexts.
✔ Abstraction – Hides complex details and shows only essential features.
✔ Examples: Java, C++, Python, C#.
3. Key Differences
Procedural Programming Object-Oriented Programming
Feature
(PP) (OOP)
Approach Top-down (functions first) Bottom-up (objects first)
Data &
Separated Combined in a class (Encapsulation)
Functions
Reusability Low (functions are standalone) High (Inheritance & Polymorphism)
Security Less secure (global data) More secure (private data)
Complexity Good for small programs Better for large-scale applications
Examples C, Pascal, FORTRAN Java, C++, Python, C#

4. When to Use Which?


• Use Procedural Programming when:
o The program is small and simple.
o Performance is critical (e.g., embedded systems).
o No need for complex data structures.
• Use OOP when:
o The program is large and complex.
o Code reusability is important.
o Working with real-world entities (e.g., GUI apps, games, databases).

Generations of Programming Languages


Programming languages have evolved over time, categorized into five generations,
each improving abstraction, efficiency, and ease of use. Below is a breakdown:

1. First Generation (1GL) – Machine Language (1940s-


1950s)
• Description: Binary code (0s and 1s) understood directly by the CPU.
• Example:
binary
01001000 01101001 (Represents "Hi" in some architectures)
• Characteristics:
o Fast execution (no translation needed).
o Extremely difficult for humans to read/write.
o Machine-dependent (not portable).

2. Second Generation (2GL) – Assembly Language


(1950s-1960s)
• Description: Uses mnemonics (e.g., MOV, ADD) instead of binary.
• Example (x86 Assembly):
assembly

MOV AX, 5 ; Load 5 into register AX


ADD AX, 3 ; Add 3 to AX
• Characteristics:
o Slightly more human-readable than machine code.
o Requires an assembler to convert to machine code.
o Still hardware-specific.

3. Third Generation (3GL) – High-Level Languages


(1960s-Present)
• Description: English-like syntax, portable across machines.
• Examples:
o Procedural: C, Pascal, Fortran.
o OOP: C++, Java, Python.
• Example (C++):
int sum = 5 + 3; // Human-readable
• Characteristics:
o Requires a compiler/interpreter.
o Focus on logic rather than hardware.
o Used for most modern software (e.g., apps, OS).
4. Fourth Generation (4GL) – Very High-Level
Languages (1980s-Present)
• Description: Designed for specific domains (e.g., databases, reports).
• Examples:
o SQL: SELECT * FROM users;
o MATLAB: A = [1 2; 3 4]; (Matrix operations)
• Characteristics:
o Closer to human language.
o Reduces code volume (e.g., 10 lines of SQL ≈ 100 lines of C).
o Used in data analysis, business apps.

5. Fifth Generation (5GL) – AI & Natural Language


(1990s-Present)
• Description: Focuses on constraint-based and AI-driven programming.
• Examples:
o Prolog (Logic programming):

prolog

father(john, bob). % Fact


?- father(john, X). % Query: Who is John's child?
o AI Tools: ChatGPT (natural language to code).
• Characteristics:
o Solves problems using rules/constraints.
o Used in AI, machine learning, robotics.

Comparison Table
Generation Example Languages Key Features Use Case
1GL Machine Code Binary, hardware-specific Early computers
2GL Assembly Mnemonics, assembler Firmware, drivers
Generation Example Languages Key Features Use Case
3GL C, Java, Python Portable, high-level syntax Modern software
4GL SQL, MATLAB Domain-specific, minimal code Databases, analytics
5GL Prolog, AI tools Natural language, AI-driven AI, expert systems

C++ First Program


#include <iostream>

using namespace std;

int main() {

int a = 5, b = 3;

cout << "Sum: " << a + b;

return 0;

#include <iostream>

using namespace std;

int main() {

int a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

cout << "Sum: " << a + b;

return 0;

}
This is a simple C++ program that calculates the sum of two numbers and prints the
result. Below is a line-by-line breakdown:

1. #include <iostream>
• Purpose: Includes the Input/Output Stream library, which allows the program to
use functions like cin (input) and cout (output).
• Example: Without this, cout and cin won’t work.

2. using namespace std;


• Purpose: Tells the compiler to use the standard namespace (std) so we don’t
have to write std::cout every time.
• Alternative: Without this, we’d need to write std::cout << "Sum: " << a + b;.

3. int main() { ... }


• Purpose: The main function is where program execution begins.
• int return type: Indicates the function returns an integer (usually 0 for success).

4. int a = 5, b = 3;
• Purpose: Declares two integer variables (a and b) and assigns them values
(5 and 3).
• Key Points:
o int means integer (whole numbers).
o Variables can be modified later (e.g., a = 10;).

5. cout << "Sum: " << a + b;


• Purpose: Prints the output to the console.
• Breakdown:
o cout → Standard output stream (prints to screen).
o << → Insertion operator (sends data to cout).
o "Sum: " → A string literal (text displayed as-is).
o a + b → Computes the sum of a and b (5 + 3 = 8).
• Output: Sum: 8
6. return 0;
• Purpose: Indicates successful program termination.

Full Program Flow


1. Starts at main().
2. Declares a = 5 and b = 3.
3. Computes a + b (which is 8).
4. Prints Sum: 8 to the console.
5. Exits with return 0.

Possible Modifications
1. User Input Version (Dynamic Values):
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Sum: " << a + b;
return 0;
}
Now, the user can input any two numbers.
o
2. Using Functions (Modular Approach):
#include <iostream>
using namespace std;

int add(int x, int y) {


return x + y;
}

int main() {
int a = 5, b = 3;
cout << "Sum: " << add(a, b);
return 0;
}
#
include <iostream> → Needed for input/output.
using namespace std; → Simplifies code (avoids std:: prefix).
int main() → Mandatory entry point.
cout << → Prints output.
return 0; → Indicates successful execution.
Variables

A variable is a named memory location used to store data during program execution. It
has a data type, name, and value.

• Declaration: You must declare a variable before using it.


• Initialization: Assigning a value to a variable when declaring it is optional (but good
practice).

Example:

int age = 25; // 'int' is the data type, 'age' is the variable name, 25
is the value.
float salary = 50000.50;
char grade = 'A';

Rules for Naming Variables:

1. Can include letters, digits, and underscores (_).


2. Cannot start with a digit (e.g., 2var is invalid).
3. Case-sensitive (e.g., Age and AGE are different).
4. Cannot use keywords (e.g., int, return) as variable names.
5. Use meaningful names (e.g., totalScore instead of ts).

Invalid Examples:

int 2var; // Error: Starts with a digit


float return; // Error: 'return' is a keyword
Keywords

Keywords (reserved words) are predefined tokens in C++ that have special meanings.
They are part of the language syntax and cannot be used as variable names or
identifiers.

Common C++ Keywords:

• Data types: int, float, double, char, bool, void


• Control flow: if, else, switch, case, for, while, do
• Functions: return, void, auto
• Memory management: new, delete
• Access modifiers: public, private, protected
• Other: class, namespace, template, try, catch, throw

Example:

int main() {
return 0; // 'int', 'main', and 'return' are keywords.
}

• Keywords are reserved by the compiler for specific purposes.


• Using a keyword as a variable name causes a compilation error.
Example:
int class = 5; // Error: 'class' is a keyword

Difference Between Variables and Keywords

Variables Keywords

Defined by the programmer. Predefined by the C++ language.

Store data in memory. Define syntax/behavior of the code.

Follow naming rules (e.g., no keywords). Cannot be redefined or used as names.


Conditional Constructs in C++
Conditional constructs allow a program to make decisions based on certain conditions.
They execute different blocks of code depending on whether a condition
is true or false.

2. Types of Conditional Constructs in C++


C++ provides several conditional constructs:

1. if statement
2. if-else statement
3. else-if
4. switch statement
5. Ternary (Conditional) Operator (? :)

3. if Statement
• Executes a block of code only if the condition is true.

Syntax:

if (condition) {
// Code to execute if condition is true
}

Example:

int age = 18;


if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
4. if-else Statement
• Executes one block if the condition is true and another if it is false.

Syntax:

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}

Example:

int num = 10;


if (num % 2 == 0) {
cout << "Even number." << endl;
} else {
cout << "Odd number." << endl;
}

5. else-if
• Checks multiple conditions in sequence.

Syntax:

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}
Example:

int marks = 85;


if (marks >= 90) {
cout << "Grade A" << endl;
} else if (marks >= 80) {
cout << "Grade B" << endl;
} else if (marks >= 70) {
cout << "Grade C" << endl;
} else {
cout << "Grade D" << endl;
}

6. switch Statement
• Used for multi-way branching based on a single variable.

Syntax:

switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}

Example:

char choice = 'B';


switch (choice) {
case 'A':
cout << "Option A selected." << endl;
break;
case 'B':
cout << "Option B selected." << endl;
break;
default:
cout << "Invalid choice." << endl;
}

Note:

• break is crucial to exit the switch block.

• default runs if no cases match.

8. Key Differences
Feature if-else switch

Condition Type Any logical condition Only equality checks

Performance Slower for multiple conditions Faster for many cases

Readability Better for ranges Better for fixed values

9. Best Practices
1. Use switch when checking multiple fixed values.
2. Use if-else for range-based conditions.
3. Always use break in switch to avoid fall-through.
4. Keep conditions simple for readability.

10. Practice Questions


1. Write a program to check if a number is positive, negative, or zero.
2. Write a program to print the day of the week using switch.
A loop in programming is a control structure that repeatedly executes a block of code
as long as a specified condition remains true. Loops streamline repetitive tasks,
enhancing efficiency, readability, and maintainability of code Types of Loops:

1. for Loop

Used when the number of iterations is known in advance.


Syntax:

for (initialization; condition; update) {


// code to execute
}

Example:

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " "; // Output: 1 2 3 4 5
}
return 0;
}

2. while Loop

Repeats code as long as a condition is true. The condition is checked before each
iteration.
Syntax:

while (condition) {
// code to execute
}

Example:
#include <iostream>
using namespace std;
int main() {
int i = 5;
while (i > 0) {
cout << i << " "; // Output: 5 4 3 2 1
i--;
}
return 0;
}

3. do-while Loop

Similar to while, but the code is executed at least once before checking the condition.
Syntax:

do {
// code to execute
} while (condition);

Example:

#include <iostream>
using namespace std;

int main() {
int num;
do {
cout << "Enter a positive number: ";
cin >> num;
} while (num <= 0); // Repeats until a positive number is entered
return 0;
}

4. Range-based for Loop (C++11)


Iterates over elements in a container (e.g., arrays, vectors).
Syntax:

for (element_declaration : container) {


// code to execute
}

Example:

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 20, 30, 40, 50};
for (int num : arr) {
cout << num << " "; // Output: 10 20 30 40 50
}
return 0;
}

Loop Control Statements

• break: Exits the loop immediately.


for (int i = 1; i <= 10; i++) {
if (i == 5) break; // Loop stops at i=5
cout << i << " ";
}
// Output: 1 2 3 4

• continue: Skips the current iteration and proceeds to the next.


for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skips i=3
cout << i << " ";
}
// Output: 1 2 4 5

Infinite Loop

A loop that runs indefinitely (use with caution!):

while (true) {
// Code runs forever unless a 'break' is used
Functions in C++
1. Introduction
A function in C++ is a reusable block of code that performs a specific task. Functions
help in modularizing code, improving readability, and reducing redundancy.

2. Types of Functions
1. Standard Library Functions (Built-in, e.g., sqrt(), strlen()).
2. User-Defined Functions (Created by the programmer).

3. Function Syntax
General Structure:

return_type function_name(parameters) {
// Function body (code)
return value; // (if return_type is not void)
}

Example:

int add(int a, int b) {


return a + b;
}

4. Components of a Function
Component Description

Return Type The data type of the value returned (void if no return).
Component Description

Function Name Identifier used to call the function.

Parameters Input variables (optional).

Function Body The code executed when the function is called.

Return Statement Sends a value back to the caller (mandatory unless void).

5. Function Declaration & Definition


• Declaration (Prototype): Tells the compiler about the function (before main()).
• Definition: Implements the function.

Example:

#include <iostream>
using namespace std;

// Function Declaration
int multiply(int x, int y);

int main() {
cout << multiply(5, 3); // Output: 15
return 0;
}

// Function Definition
int multiply(int x, int y) {
return x * y;
}

6. Function Parameters
1. Pass by Value (Default) → Creates a copy of the argument.
2. Pass by Reference → Modifies the original variable.
3. Pass by Pointer → Uses memory addresses.

Example (Pass by Reference):

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

int main() {
int x = 10, y = 20;
swap(x, y); // Original values swapped
cout << x << " " << y; // Output: 20 10
return 0;
}

7. Default Arguments
• Parameters can have default values if no argument is passed.
• Rule: Default parameters must be at the end of the parameter list.

Example:

void greet(string name = "User") {


cout << "Hello, " << name << "!" << endl;
}

int main() {
greet(); // Output: Hello, User!
greet("Alice"); // Output: Hello, Alice!
return 0;
}

8. Function Overloading
• Multiple functions can have the same name but different parameters.

Example:

int add(int a, int b) { return a + b; }


double add(double a, double b) { return a + b; }

int main() {
cout << add(5, 3) << endl; // Output: 8 (int version)
cout << add(2.5, 3.7) << endl; // Output: 6.2 (double version)
return 0;
}

9. Recursion
• A function calling itself (must have a base case to avoid infinite loops).

Example (Factorial):

int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1);
}

int main() {
cout << factorial(5); // Output: 120
return 0;
}

10. Inline Functions


• Suggests the compiler to insert code directly (avoid function call overhead).
• Best for small, frequently used functions.

Example:
inline int square(int x) {
return x * x;
}

int main() {
cout << square(5); // Output: 25
return 0;
}

You might also like