APS105 L09 - For Loops
#APS105 Slides Lecture Link to web notes
Syntax of for loop is:
for (<initialisation statement>; <conditional expression>; <increment expression>) {
<statements>
}
Example:
// example to print out numbers 1 to 9.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
for (int i = 0; i < 10; ++i) {
printf("%d\n", i);
}
return 0;
}
Example:
// example to print out 15 stars in a line
#include <stdio.h>
#include <stdlib.h>
int main(void) {
for (int i=0; i<15; ++i) {
printf("*");
}
}
Example:
// example to print a triangle of stars.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
for (int i=0; i<5; ++i) {
for (int k=0; k<=i; ++k) {
printf("*");
}
printf("\n");
}
return 0;
}
Using Continue and Break in a For Loop
This is the same as in Python.
A continue will cause the current iteration of the loop to restart, causing the loop to check the condition again.
A break will break out of the loop and go to the next line outside of the loop.
Warning
The use ofcontinueandbreakare not encouraged for this course?