Unit 2 Cpp(Bt205)
Unit 2 Cpp(Bt205)
1. Start
2. Read first number (A)
3. Read second number (B)
4. Compute Sum = A + B
5. Display Sum
6. Stop
2. Flowcharts
A flowchart is a graphical representation of an algorithm using symbols to denote
different operations.
Co
Start
│
▼
Read A
│
▼
Read B
│
▼
Sum = A + B
│
▼
Display Sum
│
▼
Stop
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.
Key Features:
Example in C:
#include <stdio.h>
int main() {
int num1 = 5, num2 = 10;
int sum = add(num1, num2);
printf("Sum: %d", sum);
return 0;
}
Explanation:
Key Features:
prolog
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
int main() {
int a = 5, b = 3;
return 0;
#include <iostream>
int main() {
int 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.
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;).
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 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.
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';
Invalid Examples:
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.
Example:
int main() {
return 0; // 'int', 'main', and 'return' are keywords.
}
Variables Keywords
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:
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
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:
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:
Note:
8. Key Differences
Feature if-else switch
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.
1. for Loop
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;
}
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;
}
Infinite Loop
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:
4. Components of a Function
Component Description
Return Type The data type of the value returned (void if no return).
Component Description
Return Statement Sends a value back to the caller (mandatory unless void).
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.
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:
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 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;
}
Example:
inline int square(int x) {
return x * x;
}
int main() {
cout << square(5); // Output: 25
return 0;
}