Saturday, April 19, 2025

C++ Basic Math Operations

In this tutorial we are dealing with basic math operations. It's easy. Just run this code, and than we will explain:

#include <iostream>

using namespace std;

int main() {

    int a = 81;
    int b = 20;

    int add = a + b;
    int sub = a - b;
    int mul = a * b;
    int div = a / b;

    int rem = a % b;

    cout << "---------------------------" << endl;
    cout << "Add: " << add << endl;
    cout << "Sub: " << sub << endl;
    cout << "Mul: " << mul << endl;
    cout << "Div: " << div << endl;
    cout << "---------------------------" << endl;

    cout << "Remainder: " << rem<< endl;

    cout << "---------------------------" << endl;

    return 0;

}

Result:

---------------------------
Add: 101
Sub: 61
Mul: 1620
Div: 4
---------------------------
Remainder: 1
---------------------------

Process returned 0 (0x0)   execution time : 0.054 s
Press any key to continue.

First we have 2 variables that will hold some values, in this case integers 81 and 20 stored in a and b:

int a = 81;
int b = 20;

Then basic math operations. Integers will be data type for all results:

int add = a + b;
int sub = a - b;
int mul = a * b;
int div = a / b;

Also we have modulo operations, which just means remainder of division. We use percent simbol here:

int rem = a % b;

Then our source to print results:

cout << "---------------------------" << endl;
cout << "Add: " << add << endl;
cout << "Sub: " << sub << endl;
cout << "Mul: " << mul << endl;
cout << "Div: " << div << endl;
cout << "---------------------------" << endl;

cout << "Remainder: " << rem<< endl;

cout << "---------------------------" << endl;

Only thing here that's interesting is modulo operation that return remainder after one number is devided by another.

For example if we say 5 % 2, remainder will be 1, because 2 * 2 is 4 and to get to 5 we need to add 1.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...