CS1 Lecture 3(?)
Thursday, the 1th of August, 2024
std::cout
and std::cin
)Say we have our basic hello world program (compiled with gcc main.cpp -lstdc++ -o a.out
):
What if we want to print Hello World!
:
#include <iostream>
int main() {
std::cout << "Hello World!\n";
std::cout << "Hello World!\n";
std::cout << "Hello World!\n";
// ...
std::cout << "Hello World!\n";
std::cout << "Hello World!\n";
return 0;
}
What’s wrong with this approach?
Lets take a look as a while loop that prints Hello World
5 times:
#include <iostream>
int main() {
int n = 5;
start: // goto label
{
if (n > 0) // <-- While loop condition -->
{
// <-- While loop statement
std::cout << "Hello World!\n";
n--;
// -->
goto start;
}
}
return 0;
}
Notice that this is:
goto
statement - these should be used sparingly#include <iostream>
int main() {
int n = 0;
while(true)
{
n++;
if (n == 4)
{
continue; // <-- skip back to the start of the loop
}
std::cout << "Counting..." << n << "\n";
if (n == 10)
{
break; // <-- exit the loop, resume control flow
}
}
return 0;
}
Continue / break is not unique to this style of loop, and is applicable to all loops.
Lets do a side-by-side conparison of the while and do-while loop styles:
Both programs produce the same output, and use roughly the same lines of code.
From this SO post:
I’ve been programming for a while now (2 years work + 4.5 years degree + 1 year pre-college), and I’ve never used a do-while loop short of being forced to in the Introduction to Programming course. I have a growing feeling that I’m doing programming wrong if I never run into something so fundamental.
So, when should we use a do-while loop?
Here is our same “Hello World” program using a traditional C++ for loop:
#include <iostream>
int main() {
for (int i = 0; i < 5; i++)
{
std::cout << "Hello World!\n";
}
return 0;
}
Notice the different components separated via ;
: - Init-statement - Condition - Expression - Loop body / statement
You can include multiple / zero expressions within each component. Expressions are separated via ,
(;;)
kind of looks like a spider…TODO
TODO