0% found this document useful (0 votes)
2 views36 pages

NAME:Vrutik Sankhesara 15934: Enroll/GR No

The document contains a practical assignment for a B.Tech CE program, detailing various programming tasks in Object Oriented Programming under the guidance of Mr. Bhavesh Chavda. It includes a list of practical exercises with corresponding dates, each requiring the student to write specific programs in C++. Additionally, sample code and outputs for several programs are provided, demonstrating basic programming concepts such as arithmetic operations, loops, conditionals, and array manipulations.

Uploaded by

lierhunter2468
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)
2 views36 pages

NAME:Vrutik Sankhesara 15934: Enroll/GR No

The document contains a practical assignment for a B.Tech CE program, detailing various programming tasks in Object Oriented Programming under the guidance of Mr. Bhavesh Chavda. It includes a list of practical exercises with corresponding dates, each requiring the student to write specific programs in C++. Additionally, sample code and outputs for several programs are provided, demonstrating basic programming concepts such as arithmetic operations, loops, conditionals, and array manipulations.

Uploaded by

lierhunter2468
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/ 36

NAME:Vrutik Sankhesara

Enroll/GR No: 15934

PROGRAM NAME:- B.TECH CE SEM-III

COURSE CODE: - CE302P

COURSE:- OBJECT ORIENTED PROGRAMMING


PRACTICAL

FACULTY NAME:- MR. BHAVESH CHAVDA


Sr.N
Date Practical Name Sign
o
19.07.202 Write A Program To Take Two Numbers As Input And Print Their
1
4 Sum And Average.
02.08.202 Write A Program To Swap Two Numbers Without Using A Third
2
4 Variable.
09.08.202 Write A Program To Check Whether The Number Provided Is Even
3
4 Or Odd.
16.08.202 Write A Program To Print The Largest Number Among Three
4
4 Numbers Given By The User
23.08.202 Write A Single Program That Provides The Sum, Difference,
5
4 Multiplication And Division Of Two Numbers.
06.09.202
6 Write A Program To Print Table Of Any Number Using A For Loop.
4
06.09.202
7 Write A Program To Print Table Of A Number Using Do While Loop.
4
13.09.202 Write A Program To Print Fibonacci Series (0, 1, 1, 2, 3, 5, 8, 13,
8
4 21,...).
13.09.202
9 Write A Program To Reverse A Number.
4
20.09.202 Write A Program To Check Whether A Number Is A Prime Number
10
4 Or Not.
20.09.202
11 Write A Program To Convert Binary Number To Decimal Number
4
20.09.202 Write A Program That Takes Values In An Array And Also Display
12
4 Them.
27.09.202
13 Write A Program To Print Length Of A String Provided
4
27.09.202
14 Write A Program To Check Whether A String Is Palindrome Or Not
4
27.09.202
15 Write A Program That Provides The Sum Of Two Matrices
4
04.10.202
16 Write A Program To Find Out The Product Of Two Matrices
4
04.10.202 Write A Program To Print ASCII Value Of Digits, Uppercase And
17
4 Lowercase Alphabets
04.10.202
18 Write A Program To Demonstrate The Use Of Class And Object
4
11.10.202
19 Write A Program To Demonstrate The Use Of Constructor In a Class
4
11.10.202 Write A Program To Demonstrate The Use Of Constructor And
20
4 Destructor In A Class
11.10.202
21 Write A Program To Demonstrate The Use Of Static Variable
4
18.10.202
22 Write A Program To Swap Two Numbers Using Class
4
23 18.10.202 Write A Program To Print Numbers From 1 To N Using Class
4
18.10.202
24 Write A Program To Overload A Sum Function
4
25.10.202 Write A Program To Calculate Area Of A Circle, A Rectangle Or A
25
4 Triangle Depending On Input Using Overloaded Calculate Function
25.10.202
26 Write A Program To Print Factorial Of A Given Number Using Class
4
25.10.202
27 Write A Program To Check Whether A Year Is Leap Year Or Not.
4
08.11.202
28 Write A C++ Program To Create A File (Data.Txt)
4
08.11.202
29 Write A Program For Creating And Writing On A Text File
4
08.11.202
30 Write A Program To Retrieve/Read Data From A Text File
4
Assignment - C++
Program 1: Write a program to take two numbers as
input and print their sum and average.

#include <iostream>
using namespace std;

int main() {
double a, b;
cout << "Enter two numbers separated by space: ";
cin >> a >> b;
double sum = a + b;
double avg = sum / 2;
cout << "Sum: " << sum << endl;
cout << "Average: " << avg << endl;
return 0;
}

Output:
Enter two numbers separated by space: 10 20
Sum: 30
Average: 15

Program 2: Write a program to swap two numbers


without using a third Variable.
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers separated by space: ";
cin >> a >> b;

// Swap without a third variable


a = a + b;
b = a - b;
a = a - b;

cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}

Output:
Enter two numbers separated by space: 5 10
After swapping: a = 10, b = 5

Program 3: Write a program to check whether the


number provided is even or odd.

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num % 2 == 0)
cout << num << " is even." << endl;
else
cout << num << " is odd." << endl;

return 0;
}

Output:

Enter a number: 7
7 is odd.

Program 4: Write a program to print the largest number


among three numbers given by the user.

#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers separated by space: ";
cin >> a >> b >> c;

int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

cout << "The largest number is: " << largest << endl;
return 0;
}

Output:
Enter three numbers separated by space: 12 25 18
The largest number is: 25
Program 5: Write a single program that provides the
sum, difference, multiplication and division of two
numbers.

#include <iostream>
using namespace std;

int main() {
double a, b;
cout << "Enter two numbers separated by space: ";
cin >> a >> b;

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


cout << "Difference: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;

if (b != 0)
cout << "Division: " << a / b << endl;
else
cout << "Division: Undefined (cannot divide by zero)" << endl;

return 0;
}

Output:

Enter two numbers separated by space: 10 2


Sum: 12
Difference: 8
Multiplication: 20
Division: 5
Program 6: Write a program to print table of any number
using a for loop.

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number to print its table: ";
cin >> num;

for (int i = 1; i <= 10; i++) {


cout << num << " x " << i << " = " << num * i << endl;
}

return 0;
}

Output:

Enter a number to print its table: 5


5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Program 7: Write a program to print table of a number


using do while loop

#include <iostream>
using namespace std;

int main() {
int num, i = 1;
cout << "Enter a number to print its table: ";
cin >> num;

do {
cout << num << " x " << i << " = " << num * i << endl;
i++;
} while (i <= 10);

return 0;
}

Output:

Enter a number to print its table: 7


7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

Program 8: Write a program to print Fibonacci Series

#include <iostream>
using namespace std;

int main() {
int n, a = 0, b = 1, next;
cout << "Enter the number of terms: ";
cin >> n;

cout << "Fibonacci Series: " << a << " " << b << " ";
for (int i = 2; i < n; i++) {
next = a + b;
cout << next << " ";
a = b;
b = next;
}

return 0;
}

Output:

Enter the number of terms: 5


Fibonacci Series: 0 1 1 2 3

Program 9: Write a program to reverse a number.

#include <iostream>
using namespace std;

int main() {
int num, reversed = 0;
cout << "Enter a number to reverse: ";
cin >> num;

while (num != 0) {
int digit = num % 10; // Extract the last digit
reversed = reversed * 10 + digit; // Build the reversed number
num /= 10; // Remove the last digit
}

cout << "Reversed Number: " << reversed << endl;


return 0;
}

Output:
Enter a number to reverse: 12345
Reversed Number: 54321

Program 10: Write a program to check whether a number


is a prime number or not.

#include <iostream>
using namespace std;

int main() {
int num, i;
bool isPrime = true;

cout << "Enter a number to check if it is prime: ";


cin >> num;

if (num <= 1) {
isPrime = false; // Numbers less than or equal to 1 are not prime
} else {
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
cout << num << " is a prime number." << endl;
else
cout << num << " is not a prime number." << endl;

return 0;
}
Output:

Enter a number to check if it is prime: 29


29 is a prime number.

Program 11: Write a program to convert binary number


to decimal number.

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

int main() {
long long binary;
int decimal = 0, base = 1, remainder;

cout << "Enter a binary number: ";


cin >> binary;

while (binary > 0) {


remainder = binary % 10; // Get the last digit
decimal = decimal + remainder * base;
binary = binary / 10; // Remove the last digit
base = base * 2; // Update the base (powers of 2)
}

cout << "Decimal equivalent: " << decimal << endl;

return 0;
}

Output:

Enter a binary number: 1101


Decimal equivalent: 13
Program 12: Write a program that takes values in an
array and also display them.

#include <iostream>
using namespace std;

int main() {
int n;

cout << "Enter the number of elements: ";


cin >> n;

int arr[n]; // Declare an array of size n

cout << "Enter " << n << " elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i]; // Take input for each element
}

cout << "The elements in the array are: ";


for (int i = 0; i < n; i++) {
cout << arr[i] << " "; // Display each element
}

cout << endl;

return 0;
}

Output:

Enter the number of elements: 5


Enter 5 elements:
10 20 30 40 50
The elements in the array are: 10 20 30 40 50

Program 13: Write a program to print length of a string


provided.

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

int main() {
string str;

cout << "Enter a string: ";


getline(cin, str); // Take input with spaces

cout << "The length of the string is: " << str.length() << endl;

return 0;
}

Output:

Enter a string: Hello, World!


The length of the string is: 13

Program 14:Write a program to check whether a string is


palindrome or not.

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

int main() {
string str, reversedStr;

cout << "Enter a string: ";


cin >> str; // Take input (single word without spaces)

reversedStr = string(str.rbegin(), str.rend()); // Reverse the string

if (str == reversedStr) {
cout << "The string is a palindrome!" << endl;
} else {
cout << "The string is not a palindrome." << endl;
}

return 0;
}

Output:
Enter a string: madam
The string is a palindrome!

Program 15: Write a program that provides the sum of


two matrices.

#include <iostream>
using namespace std;

int main() {
int rows, cols;

cout << "Enter the number of rows: ";


cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;

int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols];

// Input for Matrix 1


cout << "Enter elements of Matrix 1:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix1[i][j];
}
}

// Input for Matrix 2


cout << "Enter elements of Matrix 2:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix2[i][j];
}
}

// Calculating Sum
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Displaying the Sum Matrix


cout << "Sum of the matrices:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << sum[i][j] << " ";
}
cout << endl;
}

return 0;
}
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of Matrix 1:
1 2
3 4
Enter elements of Matrix 2:
5 6
7 8
Sum of the matrices:
6 8
10 12

Program 16: Write a program to find out the product of


two matrices.
#include <iostream>
using namespace std;

int main() {
int rows1, cols1, rows2, cols2;

// Input dimensions of matrices


cout << "Enter rows and columns for Matrix 1: ";
cin >> rows1 >> cols1;
cout << "Enter rows and columns for Matrix 2: ";
cin >> rows2 >> cols2;

// Check if multiplication is possible


if (cols1 != rows2) {
cout << "Matrix multiplication not possible. Number of columns in
Matrix 1 must equal rows in Matrix 2." << endl;
return 0;
}
int matrix1[rows1][cols1], matrix2[rows2][cols2],
product[rows1][cols2] = {0};

// Input for Matrix 1


cout << "Enter elements of Matrix 1:" << endl;
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cin >> matrix1[i][j];
}
}

// Input for Matrix 2


cout << "Enter elements of Matrix 2:" << endl;
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
cin >> matrix2[i][j];
}
}

// Multiplying matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Displaying the Product Matrix


cout << "Product of the matrices:" << endl;
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
cout << product[i][j] << " ";
}
cout << endl;
}

return 0;
}
Output:
Enter rows and columns for Matrix 1: 2 3
Enter rows and columns for Matrix 2: 3 2
Enter elements of Matrix 1:
1 2 3
4 5 6
Enter elements of Matrix 2:
7 8
9 10
11 12
Product of the matrices:
58 64
139 154

Program 17: Write a program to print ASCII value of


digits, uppercase and lowercase alphabets.

#include <iostream>
using namespace std;

int main() {
// Print ASCII values of digits
cout << "ASCII values of digits:" << endl;
for (char digit = '0'; digit <= '9'; digit++) {
cout << digit << ": " << int(digit) << endl;
}

// Print ASCII values of uppercase alphabets


cout << "\nASCII values of uppercase alphabets:" << endl;
for (char upper = 'A'; upper <= 'Z'; upper++) {
cout << upper << ": " << int(upper) << endl;
}

// Print ASCII values of lowercase alphabets


cout << "\nASCII values of lowercase alphabets:" << endl;
for (char lower = 'a'; lower <= 'z'; lower++) {
cout << lower << ": " << int(lower) << endl;
}

return 0;
}

Output:
ASCII values of digits:
0: 48
1: 49
2: 50
3: 51
4: 52
5: 53
6: 54
7: 55
8: 56
9: 57

ASCII values of uppercase alphabets:


A: 65
B: 66
C: 67
...
Z: 90

ASCII values of lowercase alphabets:


a: 97
b: 98
c: 99
...
z: 122

Program 18: Write a program to demonstrate the use of


class and object.
#include <iostream>
using namespace std;

// Define a class
class Student {
public:
string name; // Data member to store name
int age; // Data member to store age

// Member function to input student details


void inputDetails() {
cout << "Enter student's name: ";
cin >> name;
cout << "Enter student's age: ";
cin >> age;
}

// Member function to display student details


void displayDetails() {
cout << "Student's Name: " << name << endl;
cout << "Student's Age: " << age << endl;
}
};

int main() {
Student s1; // Create an object of the Student class

// Call member functions using the object


s1.inputDetails();
cout << "Displaying Student Details:" << endl;
s1.displayDetails();

return 0;
}

Output:
Enter student's name: John
Enter student's age: 20
Displaying Student Details:
Student's Name: John
Student's Age: 20

Program 19: Write a program to demonstrate the use of


constructor in a class.

#include <iostream>
using namespace std;

// Define a class
class Student {
private:
string name;
int age;

public:
// Constructor to initialize data members
Student(string studentName, int studentAge) {
name = studentName;
age = studentAge;
}

// Member function to display student details


void displayDetails() {
cout << "Student's Name: " << name << endl;
cout << "Student's Age: " << age << endl;
}
};

int main() {
// Create an object of Student class and pass values to the
constructor
Student s1("John", 20);
// Display details using the object
cout << "Displaying Student Details:" << endl;
s1.displayDetails();

return 0;
}

Output:

Displaying Student Details:


Student's Name: John
Student's Age: 20

Program 20: Write a program to demonstrate the use of


constructor and destructor in a class.

#include <iostream>
using namespace std;

// Define a class
class Student {
private:
string name;
int age;

public:
// Constructor to initialize data members
Student(string studentName, int studentAge) {
name = studentName;
age = studentAge;
cout << "Constructor called: Object created and initialized." <<
endl;
}

// Member function to display student details


void displayDetails() {
cout << "Student's Name: " << name << endl;
cout << "Student's Age: " << age << endl;
}

// Destructor to clean up when the object is destroyed


~Student() {
cout << "Destructor called: Object destroyed." << endl;
}
};

int main() {
// Create an object of Student class
Student s1("Alice", 22);

// Display details using the object


cout << "Displaying Student Details:" << endl;
s1.displayDetails();

return 0; // Destructor is automatically called here


}

Output:
Constructor called: Object created and initialized.
Displaying Student Details:
Student's Name: Alice
Student's Age: 22
Destructor called: Object destroyed.

Program 21: Write a program to demonstrate the use of


static variable.

#include <iostream>
using namespace std;

class Counter {
private:
static int count; // Static variable to keep track of object count
public:
// Constructor to increment count when an object is created
Counter() {
count++;
}

// Member function to display the count


void displayCount() {
cout << "Number of objects created: " << count << endl;
}
};

// Initialize the static variable


int Counter::count = 0;

int main() {
Counter c1; // First object
c1.displayCount();

Counter c2; // Second object


c2.displayCount();

Counter c3; // Third object


c3.displayCount();

return 0;
}

Output:
Number of objects created: 1
Number of objects created: 2
Number of objects created: 3

Program 22: Write a program to swap two numbers


using class
#include <iostream>
using namespace std;

class Swapper {
private:
int a, b;

public:
// Constructor to initialize numbers
Swapper(int num1, int num2) {
a = num1;
b = num2;
}

// Member function to swap the numbers


void swapNumbers() {
int temp = a;
a = b;
b = temp;
}

// Member function to display the numbers


void displayNumbers() {
cout << "a: " << a << ", b: " << b << endl;
}
};

int main() {
int num1, num2;

cout << "Enter two numbers:" << endl;


cin >> num1 >> num2;

// Create an object of Swapper class


Swapper swapper(num1, num2);

cout << "Before swapping:" << endl;


swapper.displayNumbers();

// Call the function to swap numbers


swapper.swapNumbers();

cout << "After swapping:" << endl;


swapper.displayNumbers();

return 0;
}

Output:
Enter two numbers:
5 10
Before swapping:
a: 5, b: 10
After swapping:
a: 10, b: 5

Program 23: Write a Program to Print Numbers from 1 to


n using class

#include <iostream>
using namespace std;

class NumberPrinter {
private:
int n; // Member to store the upper limit

public:
// Constructor to initialize n
NumberPrinter(int limit) {
n = limit;
}

// Member function to print numbers from 1 to n


void printNumbers() {
cout << "Numbers from 1 to " << n << " are:" << endl;
for (int i = 1; i <= n; i++) {
cout << i << " ";
}
cout << endl;
}
};

int main() {
int limit;

cout << "Enter the value of n: ";


cin >> limit;

// Create an object of NumberPrinter class


NumberPrinter printer(limit);

// Call the function to print numbers


printer.printNumbers();

return 0;
}

Output:

Enter the value of n: 10


Numbers from 1 to 10 are:
1 2 3 4 5 6 7 8 9 10

Program 24: Write a program to overload a sum function.

#include <iostream>
using namespace std;

// Function to calculate the sum of two integers


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

// Function to calculate the sum of two floating-point numbers


float sum(float a, float b) {
return a + b;
}

// Function to calculate the sum of three integers


int sum(int a, int b, int c) {
return a + b + c;
}

int main() {
// Calling the sum function for two integers
cout << "Sum of 10 and 20 (integers): " << sum(10, 20) << endl;

// Calling the sum function for two floats


cout << "Sum of 5.5 and 2.5 (floats): " << sum(5.5f, 2.5f) << endl;

// Calling the sum function for three integers


cout << "Sum of 1, 2, and 3 (integers): " << sum(1, 2, 3) << endl;

return 0;
}

Output:
Sum of 10 and 20 (integers): 30
Sum of 5.5 and 2.5 (floats): 8
Sum of 1, 2, and 3 (integers): 6

Program 25 : Write a program to calculate area of a circle,


a rectangle or a triangle depending on input using
overloaded calculate function.

#include <iostream>
using namespace std;
// Function to calculate the area of a circle
float calculate(float radius) {
return 3.14159 * radius * radius;
}

// Function to calculate the area of a rectangle


float calculate(float length, float breadth) {
return length * breadth;
}

// Function to calculate the area of a triangle


float calculate(float base, float height, int) {
return 0.5 * base * height;
}

int main() {
int choice;
cout << "Choose the shape to calculate area:" << endl;
cout << "1. Circle" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Triangle" << endl;
cin >> choice;

switch (choice) {
case 1: {
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "Area of the circle: " << calculate(radius) << endl;
break;
}
case 2: {
float length, breadth;
cout << "Enter the length and breadth of the rectangle: ";
cin >> length >> breadth;
cout << "Area of the rectangle: " << calculate(length,
breadth) << endl;
break;
}
case 3: {
float base, height;
cout << "Enter the base and height of the triangle: ";
cin >> base >> height;
cout << "Area of the triangle: " << calculate(base, height, 0)
<< endl;
break;
}
default:
cout << "Invalid choice!" << endl;
}

return 0;
}

Output:
Choose the shape to calculate area:
1. Circle
2. Rectangle
3. Triangle
1
Enter the radius of the circle: 5
Area of the circle: 78.5398

Program 26 : Write a program to print factorial of a given


number using class.
#include <iostream>
using namespace std;

class Factorial {
private:
int number;

public:
// Constructor to initialize the number
Factorial(int num) {
number = num;
}

// Member function to calculate the factorial


long long calculateFactorial() {
long long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
return factorial;
}

// Member function to display the factorial


void displayFactorial() {
cout << "The factorial of " << number << " is: " <<
calculateFactorial() << endl;
}
};

int main() {
int num;

cout << "Enter a number to calculate its factorial: ";


cin >> num;

// Create an object of the Factorial class


Factorial fact(num);

// Display the factorial


fact.displayFactorial();

return 0;
}

Output:
Enter a number to calculate its factorial: 5
The factorial of 5 is: 120
Program 27 : Write a program to check whether a year is
leap year or not.

#include <iostream>
using namespace std;

int main() {
int year;

cout << "Enter a year: ";


cin >> year;

// Check leap year conditions


if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
cout << year << " is a leap year." << endl;
} else {
cout << year << " is not a leap year." << endl;
}

return 0;
}

Output:
Enter a year: 2000
2000 is a leap year.

Program 28 : Write a C++ program to create a file


(data.txt).

#include <iostream>
#include <fstream> // Required for file handling
using namespace std;

int main() {
// Create an ofstream object to write to a file
ofstream outFile("data.txt");

// Check if the file is successfully created


if (outFile.is_open()) {
cout << "File 'data.txt' created successfully!" << endl;

// Write data to the file


outFile << "Hello, this is a test file.\n";
outFile << "File handling in C++ is easy and powerful.\n";

// Close the file


outFile.close();

cout << "Data written to 'data.txt' successfully!" << endl;


} else {
cout << "Failed to create the file!" << endl;
}

return 0;
}

Output:
File 'data.txt' created successfully!
Data written to 'data.txt' successfully!

Program 29 : Write a program for creating and writing on


a text file.
#include <iostream>
#include <fstream> // For file handling
using namespace std;

int main() {
string fileName = "output.txt"; // File name
string data; // Variable to store user input

// Create and open a file for writing


ofstream outFile(fileName);

// Check if the file is successfully created


if (outFile.is_open()) {
cout << "File '" << fileName << "' created successfully!" << endl;

// Ask user for data to write


cout << "Enter data to write into the file: ";
getline(cin, data);

// Write the input data into the file


outFile << data << endl;

// Close the file


outFile.close();
cout << "Data written to '" << fileName << "' successfully!" <<
endl;
} else {
cout << "Failed to create the file!" << endl;
}

return 0;
}

Output:
File 'output.txt' created successfully!
Enter data to write into the file: This is a sample text.
Data written to 'output.txt' successfully!

Program 30 : Write a program to retrieve/read data from a


text file
#include <iostream>
#include <fstream> // For file handling
using namespace std;

int main() {
string fileName = "output.txt"; // File to read from
string line; // Variable to store each line read

// Open the file for reading


ifstream inFile(fileName);

// Check if the file exists and is open


if (inFile.is_open()) {
cout << "Reading data from '" << fileName << "':" << endl;

// Read and display the file line by line


while (getline(inFile, line)) {
cout << line << endl;
}

// Close the file


inFile.close();
} else {
cout << "Failed to open the file '" << fileName << "'!" << endl;
}

return 0;
}

Output:
This is a sample text.
File handling in C++ is simple.

You might also like