Lecture 4
Lecture 4
- Repetition
Repetition Structure
Repetition structures are often called ‘loops’
3. Initialize variables 2
4. While time is less than or
F print t, d
equal to 10 s
calculate d
print time while t = t +1
print distance loop
increment time
Stop
5. Stop
Solution Code
Implements the program for the freely falling
mass
while(1) {
printf(“this is an infinite loop);
}
1 is always true
do/while Loop
General form of a do/while loop:
do
statement1; /* execute this statement */
while (condition); /* while condition is TRUE */
When condition becomes false, looping stops, and the next
statement after the while is executed
Note: statement1 will be executed at least once
Remember: to DO more than one statement in the loop, enclose the
statements in curly braces { }
called a compound statement
do/while Structure – Flow Chart
statement is executed at least
once
statement
TRUE
condition
FALSE
Do-while Syntax
do { // Execute this block of code…
Statements
…
} while (expression is true);
F
Increments the
loop control
variable:
ex. i++
for Loop Example
Class Work: Use a for loop on Example 4.1
to achieve the same output
int x;
for(x=1; x<=10; x++)
{
if(x == 5)
break;
printf("%d ", x);
}
printf("Broke out at x == %d\n",x);
1 2 3 4 Broke out at x == 5
Class work
1 2 3 4 6 7 8 9 10 Skipped x == 5
Goto and return
go to is an unconditional jump which can be used
to a given LABEL anywhere inside the function.
The syntax is…..
go to LABEL;
…
LABEL : …
Example using goto
int num;
while (1) { // Infinite Loop…
printf(“Enter a number:\t”);
scanf(“%d”,&num);
if (num == 0) {
goto LABEL1;
}
printf(“Square of %d is %d\n”,num,num*num);
}
LABEL1:
printf(“Break on user request…\n”);
Return
Syntax…..
returnValue;