DEV Community

Munin 🌝
Munin 🌝

Posted on

Day 3 / 100 (C++)

πŸ–₯️ 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
Enter fullscreen mode Exit fullscreen mode
  • Floats (float or double) 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
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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
Enter fullscreen mode Exit fullscreen mode

This is super useful for things like checking if a number is even:

if (x % 2 == 0) {
    cout << "Even";
} else {
    cout << "Odd";
}
Enter fullscreen mode Exit fullscreen mode

πŸ’» 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;
}
Enter fullscreen mode Exit fullscreen mode

πŸ”‘ 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)