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

1.

Write a C++ program that takes an array of integers as input and finds the maximum element

along with its position in the array.

#include <iostream>

#include <vector>

using namespace std;

pair<int, int> findMaxElement(const vector<int>& arr) {

int maxElement = arr[0];

int maxPosition = 0;

for (int i = 1; i < arr.size(); i++) {

if (arr[i] > maxElement) {

maxElement = arr[i];

maxPosition = i;

return make_pair(maxElement, maxPosition);

int main() {

vector<int> arr = {1, 5, 3, 9, 2};

pair<int, int> maxElement = findMaxElement(arr);

cout << "The maximum element is: " << maxElement.first << endl;

cout << "Its position in the array is: " << maxElement.second << endl;
return 0;

2.Write a C++ program that takes a string as input and outputs the reversed version of the

string. Forexample, if the input is "hello," the program should output "olleh".

#include <iostream>

#include <string>

using namespace std;

string reverseString(string input) {

string reversed = "";

for (int i = input.length() - 1; i >= 0; i--) {

reversed += input[i];

return reversed;

int main() {

string input;

cout << "Enter a string: ";

cin >> input;

cout << "Reversed string: " << reverseString(input) << endl;

return 0;

3.Write a C++ program that defines a function to calculate and return the sum of two numbers.
The program should take input from the user, call the function, and then output the result.

#include <iostream>

using namespace std;

int sum(int a, int b) {

return a + b;

int main() {

int num1, num2;

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

int result = sum(num1, num2);

cout << "The sum is: " << result << endl;

return 0;

4.Create a C++ program that uses a pointer to calculate the square of a given number. The program
should take input from the user, calculate the square using a function with a pointer, and then output
the result

#include <iostream>

using namespace std;

void calculateSquare(int* num) {

*num = (*num) * (*num);


}

int main() {

int number;

cout << "Hey, what number would you like to calculate the square of? ";

cin >> number;

calculateSquare(&number);

cout << "The square of the number is: " << number <<endl;

You might also like