C++ Basic Modular Programming Practice Questions (Pass by Value)
1. Simple Calculator
Write a C++ program that implements a simple calculator using functions for
addition, subtraction, multiplication, and division. Each function should take
two integers as input (passed by value) and return the result.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
if (b != 0)
return a / b;
else {
cout << "Division by zero error!" << endl;
return 0;
}
}
int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Addition: " << add(x, y) << endl;
cout << "Subtraction: " << subtract(x, y) << endl;
cout << "Multiplication: " << multiply(x, y) << endl;
cout << "Division: " << divide(x, y) << endl;
return 0;
}
2. Swap Numbers
Write a function that attempts to swap two numbers using pass-by-value.
#include <iostream>
using namespace std;
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "Inside swap function: a = " << a << ", b = " << b << endl;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap (in main): x = " << x << ", y = " << y << endl;
return 0;
}
3. Circle Calculations
Write a program with functions to calculate the area and circumference of a
circle.
#include <iostream>
using namespace std;
const float PI = 3.14159;
float calculateArea(float radius) {
return PI * radius * radius;
}
float calculateCircumference(float radius) {
return 2 * PI * radius;
}
int main() {
float radius;
cout << "Enter radius of the circle: ";
cin >> radius;
cout << "Area: " << calculateArea(radius) << endl;
cout << "Circumference: " << calculateCircumference(radius) << endl;
return 0;
}
4. Maximum of Three Numbers
Write a function to find the largest of three numbers passed by value.
#include <iostream>
using namespace std;
int findMax(int a, int b, int c) {
if (a >= b && a >= c)
return a;
else if (b >= a && b >= c)
return b;
else
return c;
}
int main() {
int x, y, z;
cout << "Enter three numbers: ";
cin >> x >> y >> z;
cout << "Maximum: " << findMax(x, y, z) << endl;
return 0;
}
5. Number Power
Write a program that calculates the power of a number using a function.
#include <iostream>
using namespace std;
int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
int base, exponent;
cout << "Enter base and exponent: ";
cin >> base >> exponent;
cout << base << "^" << exponent << " = " << power(base, exponent) << endl;
return 0;
}