Abdul Rafay CS Red 154

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Name:

Abdul Rafay
Class:
BS-CS(Red)
Roll no:
B23F0389CS154
Subject:
PROGRAMMING
FUNDAMENTALS
Real life examples
i. Array:

 Student Grades:
In this program, the grades are stored in an array
`studentGrades`, and the `calculateAverage` function is
used to find the average of these grades. The user is
prompted to input grades for each student, and the
program then calculates and displays the average grade.
Code:

#include <iostream>
Using namespace std;

Const int MAX_STUDENTS = 5;

// Function to calculate average


Double calculateAverage(const int grades[], int size) {
Int sum = 0;
For (int I = 0; I < size; ++i) {
Sum += grades[i];
}
Return static_cast<double>(sum) / size;
}

Int main() {
Int studentGrades[MAX_STUDENTS];

// Input student grades


Cout << “Enter grades for “ << MAX_STUDENTS << “
students:” << endl;
For (int I = 0; I < MAX_STUDENTS; ++i) {
Cout << “Student “ << I + 1 << “: “;
Cin >> studentGrades[i];
}

// Calculate and display average


Double average = calculateAverage(studentGrades,
MAX_STUDENTS);
Cout << “Average Grade: “ << average << endl;

Return 0;
}
```

 Array to track monthly expenses:


N this program, an array `monthlyExpenses` is used to
store the expenses for each month of the year. The user
inputs the expenses for each month, and the program
then calculates and displays the total expenses for the
year along with the average monthly expense. Arrays are
often employed in financial applications to organize and
analyze data, making it easier to manage and process
information over time.

#include <iostream>
#include <iomanip>
#include <string>
Using namespace std;

Const int NUM_MONTHS = 12;

Int main() {
// Array to store monthly expenses
Double monthlyExpenses[NUM_MONTHS];

// Input monthly expenses


Cout << “Enter monthly expenses for the year:” <<
endl;
For (int I = 0; I < NUM_MONTHS; ++i) {
Cout << “Month “ << I + 1 << “: $”;
Cin >> monthlyExpenses[i];
}

// Calculate total and average expenses


Double totalExpenses = 0;
For (int I = 0; I < NUM_MONTHS; ++i) {
totalExpenses += monthlyExpenses[i];
}

Double averageExpense = totalExpenses /


NUM_MONTHS;

// Display results
Cout << fixed << setprecision(2);
Cout << “\nTotal expenses for the year: $” <<
totalExpenses << endl;
Cout << “Average monthly expense: $” <<
averageExpense << endl;

Return 0;
}
```
I

ii. Functions:

 Data Validation:
In a web application a function might be responsible
for validating user input before inserting it to ensure
data integrity
Code:
#include <iostream>
#include <limits>
Using namespace std;

Int main() {
Int userInput;

// Prompt user until valid input is provided


While (true) {
Cout << “Enter a number: “;
Cin >> userInput;

// Check for valid input


If (cin.fail()) {
Cout << “Invalid input. Please enter a number.” <<
endl;
// Clear input buffer to prevent an infinite loop
Cin.clear();
Cin.ignore(numeric_limits<streamsize>::max(), ‘\
n’);
} else {
Break; // Valid input, exit the loop
}
}

Cout << “You entered: “ << userInput << endl;

Return 0;
}

 File Encryption Function:


A function can be implemented to encrypt sensitive
information before writing it to a file, enhancing
security.
#include <iostream>
#include <fstream>
#include <string>
Using namespace std;

// Function to encrypt/decrypt text using XOR cipher


String xorCipher(const string& input, char key) {
String result = input;
For (char &c : result) {
C ^= key;
}
Return result;
}

Int main() {
Ifstream inputFile(“input.txt”);
Ofstream outputFile(“encrypted.txt”);

If (inputFile.is_open() && outputFile.is_open()) {


// Key for XOR encryption
Char encryptionKey = ‘A’;

// Read from input file, encrypt, and write to


output file
String line;
While (getline(inputFile, line)) {
String encryptedLine = xorCipher(line,
encryptionKey);
outputFile << encryptedLine << endl;
}
Cout << “File encrypted successfully.” << endl;

inputFile.close();
outputFile.close();
} else {
Cout << “Unable to open files.” << endl;
}

Return 0;
}

iii. File Handling:

 Text File Reader:


A function can be used for file handling to read data
from a text file, extracting information for further
processing.
Code:
#include <iostream>
#include <fstream>
#include <string>
Using namespace std;

Int main() {
Ifstream inputFile(“example.txt”);

If (inputFile.is_open()) {
String line;

// Read and print each line from the file


While (getline(inputFile, line)) {
Cout << line << endl;
}

inputFile.close();
} else {
Cout << “Unable to open file.” << endl;
}
Return 0;
}
 To-do list:
In this program, file handling is used to read the
existing to-do list from a file, display it to the user,
and allow the user to add a new task. The updated
to-do list is then written back to the file. File
handling is a practical way to persistently store and
retrieve data, making it suitable for applications like
task management systems.
#include <iostream>
#include <fstream>
#include <cstring>

Using namespace std;

Const int MAX_TASKS = 10;


Const int MAX_TASK_LENGTH = 50;

// Function to display tasks


Void displayTasks(char tasks[][MAX_TASK_LENGTH],
int taskCount) {
Cout << “\nCurrent To-Do List:\n”;
For (int I = 0; I < taskCount; ++i) {
Cout << I + 1 << “. “ << tasks[i] << endl;
}
}

Int main() {
Char tasks[MAX_TASKS][MAX_TASK_LENGTH];
Int taskCount = 0;

// Read existing tasks from the file


Ifstream inputFile(“todolist.txt”);
If (inputFile.is_open()) {
While (inputFile.getline(tasks[taskCount],
MAX_TASK_LENGTH) && taskCount < MAX_TASKS) {
++taskCount;
}
inputFile.close();
}

// Display existing tasks


displayTasks(tasks, taskCount);

// Allow the user to add a new task


Cout << “\nEnter a new task (or ‘exit’ to quit): “;
Char newTask[MAX_TASK_LENGTH];
Cin.getline(newTask, MAX_TASK_LENGTH);

If (strcmp(newTask, “exit”) != 0) {
If (taskCount < MAX_TASKS) {
Strcpy(tasks[taskCount], newTask);
++taskCount;

// Update the file with the new task


Ofstream outputFile(“todolist.txt”);
If (outputFile.is_open()) {
For (int I = 0; I < taskCount; ++i) {
outputFile << tasks[i] << endl;
}
outputFile.close();
cout << “New task added successfully.\n”;
} else {
Cout << “Unable to update the to-do list.\
n”;
}
} else {
Cout << “To-do list is full. Cannot add more
tasks.\n”;
}
}

Return 0;
}

You might also like