Basic
Practice Problems based on chapter which you learn in previous Tutorials.
1. Length of String
#include <iostream>
Copy Code
int
main
() {
double
num1, num2;
std::cout
<< "Enter the first number: ";
std::cin
>> num1;
std::cout
<< "Enter the second number: ";
std::cin
>> num2;
double
sum = num1 + num2;
std::cout
<< "Sum: " << sum << std::endl;
return
0;
}
The length() member function is used to calculate and display the length of the string.
Alternatively, you can use size() instead of length() to achieve the same result.
2. Concatenate of Two Strings
#include <iostream>
Copy Code
#include <string>
int
main
() {
std::string
str1, str2;
std::cout
<< "Enter the first string: ";
std::getline
(std::cin, str1);
std::cout
<< "Enter the second string: ";
std::getline
(std::cin, str2);
std::string
result1 = str1 + str2;
std::string
result2 = str1;
result2.append
(str2);
std::cout
<< "Concatenated string using + operator: " << result1 << std::endl;
std::cout
<< "Concatenated string using append(): " << result2 << std::endl;
return
0;
}
3. Transpose of Matrix
#include <iostream>
Copy Code
const
int
MAX_SIZE = 10;
int
main
() {
int
matrix[MAX_SIZE][MAX_SIZE], transposed[MAX_SIZE][MAX_SIZE];
int
rows, cols;
std::cout
<< "Enter the number of rows in the matrix: ";
std::cin
>> rows;
std::cout
<< "Enter the number of columns in the matrix: ";
std::cin
>> cols;
std::cout
<< "Enter the elements of the matrix:" << std::endl;
for
(
int
i = 0; i < rows; ++i) {
for
(
int
j = 0; j < cols; ++j) {
std::cout
<< "Enter element at position (" << i + 1 << ", " << j + 1 << "): ";
std::cin
>> matrix[i][j];
}
}
std::cout
<< "
Original Matrix:" << std::endl;
for
(
int
i = 0; i < rows; ++i) {
for
(
int
j = 0; j < cols; ++j) {
std::cout
<< matrix[i][j] << " ";
}
std::cout
<< std::endl;
}
std::cout
<< "
Transpose of the Matrix:" << std::endl;
for
(
int
j = 0; j < cols; ++j) {
for
(
int
i = 0; i < rows; ++i) {
std::cout
<< matrix[i][j] << " ";
}
std::cout
<< std::endl;
}
return
0;
}
4. Method to Find Standard Deviation
Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40.
#include <iostream>
Copy Code
int
main
() {
int
n;
std::cout
<< "Enter the number of elements: ";
std::cin
>> n;
std::vector<double>
numbers(n);
std::cout
<< "Enter the elements:
";
for
(double& num : numbers) {
std::cin
>> num;
}
double
mean =
std::accumulate
(numbers.begin(), numbers.end(), 0.0) / n;
double
deviation =
sqrt
(
std::accumulate
(numbers.begin(), numbers.end(), 0.0,
[mean](double acc, double num) {
return
acc +
pow
(num - mean, 2.0); }) / n);
std::cout
<< "Standard Deviation: " << deviation << std::endl;
return
0;
}