Skip to content

[C++] Tutorial(2): Arithmetic Expression

Last Updated on 2021-05-06 by Clay

In programming, there are so-called arithmetic operators, such as addition (+), subtraction (-), multiplication (*) and division (/). In addition, the commonly used operator include the % symbol for calculating the remainder.

Through these different operators, we can let the computer help us perform calculations and handle all kinds of tasks.


Arithmetic Expression

Addition (+)

#include <iostream>
using namespace std;


int main() {

    cout << 1+2 << endl;

    return 0;
}



Output:

3


subtraction (-)

#include <iostream>
using namespace std;


int main() {

    cout << 7 - 5 << endl;

    return 0;
}



Output:

2


multiplication (*)

#include <iostream>
using namespace std;


int main() {

    cout << 7 * 5 << endl;

    return 0;
}



Output:

35


division (/)

#include <iostream>
using namespace std;


int main() {

    cout << 7 / 5 << endl;

    return 0;
}



Output:

1

There is only division's answer is not the same as in our ordinary lives. This is because the number we use is an integer (data-type is int), so the answer returned by the calculation can only be a integer.

If you want to see more accurate results of calculating decimals, we can convert 7 and 5 to float or double for calculation.

#include <iostream>
using namespace std;


int main() {

    cout << (float)7 / (float)5 << endl;

    return 0;
}



Output:

1.4


Remainder (%)

This is a rare calculation in daily life, which can help us find the remainder after dividing a value. For example, if 7 is divided by 5, the remainder is 2, we can use the operator to calculate.

#include <iostream>
using namespace std;


int main() {

    cout << 7 % 5 << endl;

    return 0;
}



Output:

2


Strings can also be added

It is worth mentioning that strings can actually be added together.

#include <iostream>
#include <string>
using namespace std;


int main() {
    string str_01 = "Today is a ";
    string str_02 = "nice day.";

    cout << str_01 + str_02 << endl;

    return 0;
}



Output:

Today is a nice day.

References


Read More

Tags:

Leave a Reply