0% found this document useful (0 votes)
10 views10 pages

PST Assignment

The document contains multiple C and C++ programming tasks, including file handling for student records, explanations of storage classes, bitwise encryption, a bank account management system, and functions for finding maximum and minimum elements in an array. Each task is accompanied by code examples and test cases to validate functionality. Additionally, there are implementations for searching strings in files and removing duplicates from strings.

Uploaded by

abhishek rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

PST Assignment

The document contains multiple C and C++ programming tasks, including file handling for student records, explanations of storage classes, bitwise encryption, a bank account management system, and functions for finding maximum and minimum elements in an array. Each task is accompanied by code examples and test cases to validate functionality. Additionally, there are implementations for searching strings in files and removing duplicates from strings.

Uploaded by

abhishek rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Question 3: Write a C program for file handling that reads and writes

student records using structures. Implement functions to add, display, and


search records in the file.

Ans:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
int rollNo;
char name[50];
} Student;

void addRecord();
void displayRecords();
void searchRecord(int roll);

int main() {
addRecord();
displayRecords();
searchRecord(101);
return 0;
}

void addRecord() {
FILE *fptr = fopen("students.dat", "ab");
Student s = {101, "John"};
fwrite(&s, sizeof(Student), 1, fptr);
fclose(fptr);
}

void displayRecords() {
FILE *fptr = fopen("students.dat", "rb");
Student s;
while (fread(&s, sizeof(Student), 1, fptr)) {
printf("Roll No: %d, Name: %s\n", s.rollNo, s.name);
}
fclose(fptr);
}
Question 5: Explain different storage classes in
C. Discuss automatic, register, static, and extern with examples of their usage.

Ans:
Storage classes in C define the scope, visibility, and lifetime of variables. The four main
storage classes in C are:

1. Automatic (auto)
2. Register
3. Static
4. Extern

1. Automatic Storage Class (auto)

 Default storage class for local variables.


 Scope: Block-level (inside functions or code blocks {}).
 Lifetime: Exists only within the block, memory is deallocated after function exits.
 Storage: Stored in stack memory.

Example
#include <stdio.h>

void func() {
auto int x = 10;
printf("Value of x: %d\n", x);
}

int main() {
func();
return 0;
}

2. Register Storage Class (register)

 Stored in CPU registers instead of RAM (faster access).


 Scope: Block-level.
 Lifetime: Exists only within the function.
 Cannot access address using & operator (register variables don’t have a memory
address).
 Used for performance optimization.

Example
#include <stdio.h>
int main() {
register int i = 10;
printf("Register variable: %d\n", i);
return 0;
}
3. Static Storage Class (static)

 Scope:
o Inside a function → Retains value across multiple function calls.
o Outside a function (global) → Accessible only within the file (internal
linkage).
 Lifetime: Exists throughout program execution.
 Default value: 0 (if uninitialized).

Example 1: Static Variable Inside a Function


#include <stdio.h>

void counter() {
static int count = 0;
count++;
printf("Count: %d\n", count);
}

int main() {
counter();
counter();
counter();
return 0;
}
Example 2: Static Global Variable
#include <stdio.h>
static int num = 5;
void display() {
printf("Static global variable: %d\n", num);
}
int main() {
display();
return 0;
}

4. External Storage Class (extern)

 Scope: Global (accessible across multiple files).


 Lifetime: Exists throughout program execution.
 Used to reference global variables defined in another file.
 Does not allocate memory, just tells the compiler the variable exists elsewhere.

Example: extern Variable Across Two Files

File 1: file1.c (Define the variable)

#include <stdio.h>
int count = 10;
void show() {
printf("Count: %d\n", count);
}

File 2: file2.c (Use extern to reference it)


#include <stdio.h>
extern int count;
int main() {
printf("Count from file1: %d\n", count);
return 0;
}

Question 6: Develop a C program to perform bitwise operations to


encrypt and decrypt a string using XOR encryption.

Ans:
#include <stdio.h>
#include <string.h>
void xorEncryptDecrypt(char *input, char key) {
for (int i = 0; i < strlen(input); i++) {
input[i] ^= key;
}
}
int main() {
char str[] = "Hello";
char key = 'K';
xorEncryptDecrypt(str, key);
printf("Encrypted: %s\n", str);
xorEncryptDecrypt(str, key);
printf("Decrypted: %s\n", str);
return 0;
}

Question7:Program: Implement a C++ class for managing bank accounts


with features like deposit, withdraw, and balance check.

Test Cases:

1. Deposit: Initial Balance = 1000, Deposit 500, Expected Balance


= 1500.
2. Withdraw: Balance = 1500, Withdraw 2000, Expected Output:
"Insufficient funds".
3. Memory Test: Create and destroy multiple objects, Expected
Output: No memory leaks (use valgrind or similar tools).
4. Edge Case: Withdraw a negative amount, Expected Output:
"Invalid input".

Ans:
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double initialBalance) {
if (initialBalance < 0) {
cout << "Invalid initial balance. Setting to 0." << endl;
balance = 0;
} else {
balance = initialBalance;
}
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: " << amount << ", New Balance: " << balance << endl;
} else {
cout << "Invalid deposit amount." << endl;
}
}
void withdraw(double amount) {
if (amount < 0) {
cout << "Invalid input" << endl;
return;
}
if (amount > balance) {
cout << "Insufficient funds" << endl;
} else {
balance -= amount;
cout << "Withdrawn: " << amount << ", Remaining Balance: " << balance << endl;
}
}
double getBalance() const {
return balance;
}
};

int main() {
double initialBalance, amount;
char choice;
cout << "Enter initial balance: ";
cin >> initialBalance;
BankAccount account(initialBalance);

do {
cout << "\nChoose an operation:\n";
cout << "1. Deposit\n";
cout << "2. Withdraw\n";
cout << "3. Check Balance\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case '1':
cout << "Enter amount to deposit: ";
cin >> amount;
account.deposit(amount);
break;
case '2':
cout << "Enter amount to withdraw: ";
cin >> amount;
account.withdraw(amount);
break;
case '3':
cout << "Current Balance: " << account.getBalance() << endl;
break;
case '4':
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != '4');

for (int i = 0; i < 1000; ++i) {


BankAccount *temp = new BankAccount(100);
delete temp;
}
cout << "Memory test completed successfully." << endl;
return 0;
}

Question 8: Function to find the maximum and minimum elements in an array.

Test Cases:

i. Input Array: [3, 5, 7, 2, 8], Expected Output: Max = 8, Min = 2.

ii. Edge Case: Empty array, Expected Output: Error message "Array is empty".

iii. Edge Case: Single element array [4], Expected Output: Max = 4, Min = 4.

iv. Large Input: Array with 1000+ elements, Expected Output: No performance issues.

Ans:

#include <iostream>
#include <vector>
#include <limits>
using namespace std;
pair<int, int> findMaxMin(const vector<int>& arr) {
if (arr.empty()) {
throw runtime_error("Array is empty");
}
int maxVal = numeric_limits<int>::min();
int minVal = numeric_limits<int>::max();
for (int num : arr) {
if (num > maxVal) maxVal = num;
if (num < minVal) minVal = num;
}
return {maxVal, minVal};
}
int main() {
try {
vector<int> arr1 = {3, 5, 7, 2, 8};
auto [max1, min1] = findMaxMin(arr1);
cout << "Test Case 1: Max = " << max1 << ", Min = " << min1 << endl;
vector<int> arr2;
try {
auto [max2, min2] = findMaxMin(arr2);
} catch (const runtime_error& e) {
cout << "Test Case 2: " << e.what() << endl;
}
vector<int> arr3 = {4};
auto [max3, min3] = findMaxMin(arr3);
cout << "Test Case 3: Max = " << max3 << ", Min = " << min3 << endl;
vector<int> arr4(1000, 5);
auto [max4, min4] = findMaxMin(arr4);
cout << "Test Case 4: Max = " << max4 << ", Min = " << min4 << endl;
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}

Question 13: Implement a program that searches for a specific string in a file.
The file name and the search string should be provided via command line
arguments.

Ans:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 3) {
cerr << "Usage: " << argv[0] << " <filename> <search_string>" << endl;
return 1;
}
string filename = argv[1];
string searchString = argv[2];
ifstream file(filename);
if (!file) {
cerr << "Error opening file: " << filename << endl;
return 1;
}
string line;
int lineNumber = 0;
bool found = false;

while (getline(file, line)) {


lineNumber++;
if (line.find(searchString) != string::npos) {
cout << "Found at line " << lineNumber << ": " << line << endl;
found = true;
}
}
if (!found) {
cout << "String not found in file." << endl;
}
file.close();
return 0;
}

Question 14: Remove Duplicates from a String without using additional


data structures.

Ans:

#include <iostream>
using namespace std;
void removeDuplicates(char* str) {
if (!str) return;
int len = 0;
while (str[len] != '\0') len++;
if (len < 2) return;

int index = 1;
for (int i = 1; i < len; i++) {
int j;
for (j = 0; j < index; j++) {
if (str[i] == str[j]) break;
}
if (j == index) {
str[index] = str[i];
index++;
}
}
str[index] = '\0';
}
int main() {
char str[] = "programming";
removeDuplicates(str);
cout << "String after removing duplicates: " << str << endl;
return 0;
}

Question 15: Program: Student Management System using Arrays, Pointers, and
Structures.

Ans:

#include <iostream>
#include <string>
using namespace std;

struct Student {
int id;
string name;
float marks;
};

void addStudent(Student* students, int& count, int id, string name, float marks) {
students[count].id = id;
students[count].name = name;
students[count].marks = marks;
count++;
}

void displayStudents(const Student* students, int count) {


cout << "\nStudent Records:" << endl;
for (int i = 0; i < count; i++) {
cout << "ID: " << students[i].id << ", Name: " << students[i].name << ", Marks: " <<
students[i].marks << endl;
}
}

int main() {
const int MAX_STUDENTS = 100;
Student students[MAX_STUDENTS];
int count = 0;
int choice;

do {
cout << "\nStudent Management System" << endl;
cout << "1. Add Student" << endl;
cout << "2. Display Students" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;

if (choice == 1) {
int id;
string name;
float marks;
cout << "Enter ID: ";
cin >> id;
cout << "Enter Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter Marks: ";
cin >> marks;
addStudent(students, count, id, name, marks);
} else if (choice == 2) {
displayStudents(students, count);
}
} while (choice != 3);

cout << "Exiting Student Management System..." << endl;


return 0;
}

You might also like