C++
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C++
-
Section 4: Memory Management
-
Section 5: Templates and Generic Programming
-
Section 6: The Standard Template Library
-
Section 7: Modern C++ Features
-
Section 8: Error Handling
-
Section 9: Multithreading
-
Section 10: Operator Overloading and Type Conversion
-
Section 11: Advanced Topics
-
Section 12: Tooling and Build Systems
-
Section 13: Design Patterns in C++
-
Section 14: Interfacing with C and Systems Programming
-
Section 15: Networking and IPC Basics
-
Section 16: Graphics and Game Programming Basics
-
Section 17: The Boost Libraries
-
Section 18: Data Structures and Algorithms in C++
-
Section 19: Practical Projects
-
Section 20: More Concurrency Patterns
-
Section 21: More OOP and Design Practice
-
Section 22: File I/O and Streams
-
Section 23: More Standard Library
-
Section 24: Practice Exercises
-
Section 25: Interview and Algorithm Practice
-
Section 26: Compiler and Language Internals
-
Section 27: GUI and Application Frameworks Overview
-
Section 28: Testing and Quality Practices
-
Section 29: Numerics Library
-
Section 30: Concepts Library (C++20)
-
Section 31: Ranges Library (C++20) In Depth
-
Section 32: More Utility Library
13: For Loops
When people first encounter the for loop, they usually walk away with a very specific, limiting idea: that it's just a tool for counting from 0 to 10, or for stepping through every element in an array. I've seen countless juniors treat the for loop like a rigid template where you must use an integer that increments by one.
The "It's Just for Counting" Myth
If you think a for loop is just a fancy while loop for integers, you're missing the flexibility of the syntax. Look at this snippet. It doesn't count "up" in a linear fashion at all:
for (int power = 1; power <= 100; power *= 2) {
std::cout << power << " ";
}
// Output: 1 2 4 8 16 32 64
Notice how I'm multiplying power by 2 every time instead of adding 1? The loop doesn't care that we aren't "counting." It only cares that the condition power <= 100 eventually becomes false. You can put almost any expression in those three slots of the loop header, as long as they make logical sense together.
The Three-Part Control Engine
To really master this, you need to stop seeing the for loop as a single command and start seeing it as a control engine with three distinct phases. I like to visualize it as a cycle:
- Initialization: This happens exactly once, before the loop ever starts. This is where you set your starting state.
- Condition: This is checked before every single iteration. If it's true, the body runs. If it's false, the loop kills itself immediately.
- Update: This happens after the body of the loop finishes, but before the condition is checked again.
Here is a real-world pattern I use often: processing a string backwards. Most learners struggle with this because they try to force the loop to "count up," but it's much cleaner to just change the initialization and the update expression.
std::string message = "C++ is powerful";
for (int i = message.length() - 1; i >= 0; i--) {
std::cout << message[i];
}
// Output: lufrewop si ++C
I started at the last index, checked that I hadn't gone past the first character, and decremented i. Same engine, different configuration.
Avoiding the Off-By-One Trap
If there's one thing that will make you pull your hair out in C++, it's the "off-by-one" error. It usually happens because of a confusion between the < (less than) and <= (less than or equal to) operators.
Remember that C++ arrays and strings are zero-indexed. If you have an array of 5 elements, the indices are 0, 1, 2, 3, and 4. If you write for (int i = 0; i <= 5; i++), you're telling the program to look for index 5. But index 5 doesn't exist. You've just stepped outside the bounds of your memory, and in C++, that's a great way to trigger a segmentation fault or introduce a bug that only appears once every ten times you run the program.
My rule of thumb? If you're iterating through a container, stick to i = 0 and i < size. It's a pattern that's hard to mess up once it becomes muscle memory.
📋 Practical Task
Building a Compound Interest Projection Table
Write a program that simulates the growth of a savings account over a set number of years. You will need to use a for loop to calculate the balance for each year.
Requirements:
- Initialize a
double balancewith a starting amount (e.g., 1000.0). - Set an
annualRate(e.g., 0.05 for 5%). - Use a
forloop to iterate from year 1 up to year 10. - Inside the loop, update the balance by adding the interest:
balance += balance * annualRate; - Print the current year and the updated balance for that year.
- Ensure your loop terminates exactly at year 10, without attempting an 11th iteration.
There are no comments for now.