0% found this document useful (0 votes)
7 views9 pages

Loops

The document explains three types of loops in programming: For Loops, While Loops, and Do While Loops. It provides examples for each type, demonstrating their syntax and usage, such as printing a message multiple times and converting strings. The document also illustrates how to control loop execution based on conditions and variable updates.

Uploaded by

Lyall
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Loops

The document explains three types of loops in programming: For Loops, While Loops, and Do While Loops. It provides examples for each type, demonstrating their syntax and usage, such as printing a message multiple times and converting strings. The document also illustrates how to control loop execution based on conditions and variable updates.

Uploaded by

Lyall
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

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

for (int i = 0; i < 10; i++)


{
printf("This is CS50!\
n");
}
Example #2
Converts a lowercase string to
uppercase

char name[] = "milo";


for (int i = 0, j = strlen(name); i < j; i++)
{
name[i] = toupper(name[i]);
}
While Loops

while (condition)
{
execute this code
}

if false Check if true


condition

Execute code
Exit loop
in body
Example #3
Counts down from 10 to 0

int count = 10;


while (count >= 0)
{
printf("%i\n", count)
count--;
}
Example #4
Calculates string length

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);

You might also like