c++ assign
c++ assign
#include <iostream>
#include <cmath>
using namespace std;
// Function to calculate the volume of a sphere
double volumeOfSphere(double radius) {
return (4.0 / 3.0) * M_PI * pow(radius, 3);
}
// Function to calculate the volume of a cube
double volumeOfCube(double side) {
return pow(side, 3);
}
// Function to calculate the volume of a cylinder
double volumeOfCylinder(double radius, double height) {
return M_PI * pow(radius, 2) * height;
}
int main() {
double radius, side, height;
// Input for the sphere
cout << "Enter the radius of the sphere: ";
cin >> radius;
cout << "Volume of the sphere: " << volumeOfSphere(radius) << endl;
// Input for the cube
cout << "Enter the side length of the cube: ";
cin >> side;
cout << "Volume of the cube: " << volumeOfCube(side) << endl;
// Input for the cylinder
cout << "Enter the radius of the cylinder: ";
cin >> radius;
cout << "Enter the height of the cylinder: ";
cin >> height;
cout << "Volume of the cylinder: " << volumeOfCylinder(radius, height)
<< endl;
return 0;
}
This program includes:
volumeOfSphere() calculates the volume of a sphere with a given rad
ius.
volumeOfCube() calculates the volume of a cube with a given side le
ngth.
volumeOfCylinder() calculates the volume of a cylinder with a given r
adius and height.
No 2
#include <iostream>
using namespace std;
// Function to convert Celsius to Fahrenheit
double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32.0;
}
// Function to convert Fahrenheit to Celsius
double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32.0) * 5.0 / 9.0;
}
int main() {
double temperature;
char choice;
cout << "Enter 'C' to convert Celsius to Fahrenheit or 'F' to convert
Fahrenheit to Celsius: ";
cin >> choice;
if (choice == 'C' || choice == 'c') {
cout << "Enter temperature in Celsius: ";
cin >> temperature;
cout << "Temperature in Fahrenheit: " <<
celsiusToFahrenheit(temperature) << endl;
} else if (choice == 'F' || choice == 'f') {
cout << "Enter temperature in Fahrenheit: ";
cin >> temperature;
cout << "Temperature in Celsius: " <<
fahrenheitToCelsius(temperature) << endl;
} else {
cout << "Invalid choice. Please enter 'C' or 'F'." << endl;
}
return 0;
}
This program includes:
celsiusToFahrenheit(): Converts a given Celsius temperature to Fahr
enheit.
fahrenheitToCelsius(): Converts a given Fahrenheit temperature to C
elsius.
The main() function allows the user to choose the type of conversion and t
hen enter the temperature to be converted. The appropriate function is th
en called based on the user's choice.
No3
#include <iostream>
using namespace std;
// Function to evaluate and print the message based on income
void evaluateIncome(double income) {
if (income > 50000) {
cout << "Congratulations on making more than $50,000 annually!"
<< endl;
} else {
cout << "Keep going! You're on your way to achieving your financial
goals!" << endl;
}
}
int main() {
double income;
cout << "Enter your annual income: $";
cin >> income;
evaluateIncome(income);
return 0;
}
In this program:
evaluateIncome() is the second function that takes the user's annual
income as an argument and prints a message based on whether the i
ncome is greater than $50,000.
main() function asks the user for their annual income and then calls
the evaluateIncome() function with the income.
No4
#include <iostream>
using namespace std;
// Function to fill the array with letters A through J
void fun1(char arr[]) {
for (int i = 0; i < 10; ++i) {
arr[i] = 'A' + i;
}
}
// Function to print the array backwards
void fun2(char arr[]) {
for (int i = 9; i >= 0; --i) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
char arr[10]; // Declare a 10-element character array
fun1(arr); // Fill the array with letters A through J
fun2(arr); // Print the array backwards
return 0;
}
In this program:
fun1() fills the array with letters A through J.
fun2() prints the array backwards.
main() function declares the 10-element character array and calls fu
n1() to fill it and fun2() to print it in reverse.
No5
#include <iostream>
#include <string>
using namespace std;
// Function to reverse the sentence using recursion
void reverseSentence(const string &sentence, int index) {
if (index >= 0) {
cout << sentence[index];
reverseSentence(sentence, index - 1);
}
}
int main() {
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
cout << "Reversed sentence: ";
reverseSentence(sentence, sentence.length() - 1);
cout << endl;
return 0;
}
In this program:
reverseSentence() is a recursive function that takes the sentence an
d the current index as parameters. It prints the character at the curr
ent index and then calls itself with the index decremented by 1.
main() function reads the sentence from the keyboard using getline(
), then calls reverseSentence() to print the sentence in reverse.
No6
#include <iostream>
#include <cctype> // for isalpha, isdigit, and isspace functions
using namespace std;
void analyzeString(const char str[], int &vowels, int &consonants, int
&digits, int &whitespaces) {
vowels = consonants = digits = whitespaces = 0;
for (int i = 0; str[i] != '\0'; ++i) {
char ch = tolower(str[i]);
if (isalpha(ch)) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
} else if (isdigit(ch)) {
digits++;
} else if (isspace(ch)) {
whitespaces++;
}
}
}
int main() {
const int SIZE = 100;
char str[SIZE];
cout << "Enter a string: ";
cin.getline(str, SIZE);
int vowels, consonants, digits, whitespaces;
analyzeString(str, vowels, consonants, digits, whitespaces);
cout << "Number of vowels: " << vowels << endl;
cout << "Number of consonants: " << consonants << endl;
cout << "Number of digits: " << digits << endl;
cout << "Number of white-spaces: " << whitespaces << endl;
return 0;
}
This program includes:
analyzeString(): A function that takes a C-style string and reference
variables for counting vowels, consonants, digits, and white spaces.
It iterates through the string, updating the counts based on the char
acter type.
main(): The function that prompts the user to enter a string, calls an
alyzeString() to analyze the string, and prints the results.
No7
#include <iostream>
#include <cstring> // for strlen function
using namespace std;
int countCharacterFrequency(const char str[], char ch) {
int count = 0;
for (int i = 0; i < strlen(str); ++i) {
if (str[i] == ch) {
count++;
}
}
return count;
}
int main() {
const int SIZE = 100;
char str[SIZE];
char ch;
cout << "Enter a string: ";
cin.getline(str, SIZE);
cout << "Enter the character to count its frequency: ";
cin >> ch;
int frequency = countCharacterFrequency(str, ch);
cout << "The character '" << ch << "' appears " << frequency << "
times in the string." << endl;
return 0;
}
This program works as follows:
countCharacterFrequency(): This function takes a C-style string and
a character, counting how many times the character appears in the s
tring.
main(): It prompts the user to enter a string and a character, calls th
e countCharacterFrequency() function, and prints the result.
No8
#include <iostream>
#include <cstring> // for strlen function
using namespace std;
bool isPalindrome(const char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; ++i) {
if (str[i] != str[length - i - 1]) {
return false;
}
}
return true;
}
int main() {
const int SIZE = 100;
char str[SIZE];
cout << "Enter a string/word: ";
cin.getline(str, SIZE);
if (isPalindrome(str)) {
cout << "The string/word is a palindrome." << endl;
} else {
cout << "The string/word is not a palindrome." << endl;
}
return 0;
}
This program includes:
isPalindrome(): This function checks whether the given C-style string
is a palindrome by comparing characters from both ends moving tow
ards the center.
main(): It prompts the user to enter a string, calls the isPalindrome()
function, and prints whether the string is a palindrome or not.
No9
#include <iostream>
#include <conio.h> // for _getch()
using namespace std;
int main() {
char key;
cout << "Press any key: ";
key = _getch(); // Wait for a key press
cout << "\nYou pressed: " << key << endl;
cout << "ASCII code: " << static_cast<int>(key) << endl;
return 0;
}
In this program:
_getch() waits for a key press and returns the character correspondi
ng to the pressed key without printing it to the console.
The program then prints the pressed key and its ASCII code using st
atic_cast<int> to convert the character to its ASCII value.
No10
#include <iostream>
#include <string>
using namespace std;
// Define a structure to hold employee information
struct Employee {
int id;
string name;
string position;
double salary;
};
int main() {
// Create an array of 20 Employee structures
Employee employees[20];
// Input employee information
for (int i = 0; i < 20; ++i) {
cout << "Enter information for employee " << (i + 1) << ": " << endl;
cout << "ID: ";
cin >> employees[i].id;
cin.ignore(); // Ignore newline character left in buffer
cout << "Name: ";
getline(cin, employees[i].name);
cout << "Position: ";
getline(cin, employees[i].position);
cout << "Salary: ";
cin >> employees[i].salary;
cin.ignore(); // Ignore newline character left in buffer
cout << endl;
}
// Print employee information in list form
cout << "Employee Information List:" << endl;
for (int i = 0; i < 20; ++i) {
cout << "Employee " << (i + 1) << ": " << endl;
cout << "ID: " << employees[i].id << endl;
cout << "Name: " << employees[i].name << endl;
cout << "Position: " << employees[i].position << endl;
cout << "Salary: " << employees[i].salary << endl;
cout << "-------------------------" << endl;
}
return 0;
}
Explanation:
Structure Definition: We define a structure Employee to hold employ
ee information like id, name, position, and salary.
Array of Structures: We create an array of 20 Employee structures to
store the information of 20 employees.
Input: We use a for loop to input details for each employee.
Output: Another for loop is used to print out each employee's inform
ation.
Assignment two
#include <iostream>
#include <fstream>
#include <sstream> // for istringstream
#include <string>
using namespace std;
const string paragraph = "For a long time it puzzled me how something so
expensive, so leading edge, could be so useless. "
"And then it occurred to me that a computer is a stupid
machine with the ability to do incredibly smart things, "
"while computer programmers are smart people with the
ability to do incredibly stupid things. "
"They are, in short, a perfect match.";
int main() {
// Step 1: Create and open a file
ofstream outFile("paragraph.txt");
// Step 2: Write the paragraph to the file
if (outFile.is_open()) {
outFile << paragraph;
outFile.close();
} else {
cerr << "Unable to open file for writing." << endl;
return 1;
}
// Step 3: Read the file and print the contents
ifstream inFile("paragraph.txt");
string line;
int lineCount = 0, wordCount = 0, charCount = 0;
if (inFile.is_open()) {
cout << "The paragraph content:" << endl;
while (getline(inFile, line)) {
cout << line << endl;
lineCount++;
// Count words and characters in each line
istringstream iss(line);
string word;
while (iss >> word) {
wordCount++;
}
charCount += line.length();
}
inFile.close();
} else {
cerr << "Unable to open file for reading." << endl;
return 1;
}
// Print the counts
cout << "\nNumber of lines: " << lineCount << endl;
cout << "Number of words: " << wordCount << endl;
cout << "Number of characters: " << charCount << endl;
return 0;
}
Explanation:
1. File Creation and Writing:
The program creates and opens a file named paragraph.txt and
writes the paragraph to the file.
2. File Reading and Analysis:
The program reads the file line by line. It counts the number of
lines, words, and characters.
Each line's words are counted using an istringstream.
The number of characters is summed from the length of each li
ne.