Informatics - Addition & Substraction (Week 19)
Hola! Como estas?
In this blog I will show you a really simple code about addition and subtraction between two numbers. It's really simple and I'm sure every new programmer can do this!
Here's the code!
// Program: AdditionSubtraction.cpp
#include <iostream>
using namespace std;
int val1, val2;
void add() {
cout << "Enter first number: ";
cin >> val1;
cout << "Enter second number: ";
cin >> val2;
int result = val1 + val2;
cout << val1 << " plus " << val2 << " is: " << result << endl;
}
void subs() {
cout << "Enter first number: ";
cin >> val1;
cout << "Enter second number: ";
cin >> val2;
int result = val1 - val2;
cout << val1 << " minus " << val2 << " is: " << result << endl;
}
int main() {
int choice;
cout << "Choose the math operation! \n";
cout << "1. Addition \n";
cout << "2. Subtraction \n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
add();
break;
case 2:
subs();
break;
default:
cout << "CAN'T OPERATE ANYTHING, INVALID CHOICE!" << endl;
}
return 0;
}
This program is a simple calculator that performs either addition or subtraction based on the user's choice. It first defines two global variables, val1 and val2, which store the numbers the user wants to add or subtract. There are two separate functions: add() and subs(). The add() function asks the user to enter two numbers, adds them together, and displays the result. Similarly, the subs() function prompts the user for two numbers, subtracts the second number from the first, and displays the answer.
The main() function serves as the control center of the program. It first asks the user to choose between addition and subtraction by entering either 1 or 2. A switch statement is then used to execute the corresponding function based on the user's input. If the user enters 1, the program calls the add() function, and if they enter 2, it calls the subs() function. If the user enters anything other than 1 or 2, the program displays an error message indicating an invalid choice. The program is simple, user-friendly, and ensures the user selects a valid operation before performing any calculations.
That's the output of the program. I chose 1 which it'll run addition then I input 5 as my first number then I input 7 as my second number. So the result will be 5 + 7 is 12.
It's so simple isn't it? Well good luck when you try it!
.png)
Komentar
Posting Komentar