capypad
0 Tage Serie
cpp / beginner
Snippet

While-Schleifen: Aktionen Wiederholen

Eine while-Schleife wiederholt einen Codeblock solange eine Bedingung wahr bleibt. Die Bedingung wird vor jeder Iteration geprüft, also wenn sie von Anfang an falsch ist, wird die Schleife nie ausgeführt. Hier zählen wir von 5 auf 1 herunter, dann geben wir Liftoff! aus.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
 
int main() {
int countdown = 5;
while (countdown > 0) {
cout << "Countdown: " << countdown << endl;
countdown = countdown - 1;
}
cout << "Liftoff!" << endl;
return 0;
}
Erklärung
1
int countdown = 5;
Zählervariable vor Schleifenstart initialisieren
2
while (countdown > 0) {
Schleifenbedingung - läuft weiter solange Countdown positiv ist
3
countdown = countdown - 1;
Zähler verringern um Schleife eventually zu beenden