Loops
Loops
For Loops
for (initialization; condition; update)
{
execute this code
}
Initialize Update
variable(s) variable(s)
Check
condition
Execute code
Exit loop
in body
if false if true
Example #1
Prints “This is CS50!” ten times
while (condition)
{
execute this code
}
Execute code
Exit loop
in body
Example #3
Counts down from 10 to 0
string s = get_string();
int length = 0;
while (s[length] != '\0')
length++;
Do While Loops
do
{
execute this code
}
while (condition);
if true
if false
Execute code Check Exit loop
in body condition
Example #5
Reprompts until user enters a
positive number
int input;
do
{
input = GetInt("Enter a positive number:");
}
while (input < 1);