π₯οΈ What I Learned
1. Basic Arithmetic Operators
C++ gives us standard math operators:
-
+
β addition -
-
β subtraction -
*
β multiplication -
/
β division -
%
β modulus (remainder)
2. Integers vs Floats
Hereβs where it gets interesting:
-
Integers (
int
) only store whole numbers. If you divide two integers, you get an integer result (the decimal part is cut off).
cout << 7 / 2; // prints 3, not 3.5
-
Floats (
float
ordouble
) can store decimals. If at least one number is a float, youβll get a more precise result:
cout << 7.0 / 2; // prints 3.5
cout << 7 / 2.0; // also prints 3.5
π Key insight: The type of your variables changes the type of your results.
3. The Modulus Operator %
-
%
only works with integers. - It gives the remainder after division.
cout << 7 % 2; // prints 1 (since 7 = 2*3 + 1)
cout << 10 % 3; // prints 1
This is super useful for things like checking if a number is even:
if (x % 2 == 0) {
cout << "Even";
} else {
cout << "Odd";
}
π» Example Code
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 2;
float c = 7.0, d = 2.0;
// Integer operations
cout << "Integer addition: " << a + b << endl;
cout << "Integer division: " << a / b << endl; // 3
// Float operations
cout << "Float division: " << c / d << endl; // 3.5
// Modulus
cout << "Modulus (remainder): " << a % b << endl; // 1
return 0;
}
π Takeaway
- Integers cut off decimals when dividing.
- Floats keep decimals for more accurate results.
-
Modulus (
%
) gives the remainder and only works with integers.
just smile π, and start coding!
#100DaysOfCode #LearnInPublic #CodeNewbie #C++ #CodingChallenge #Programming
Top comments (0)