1. Can every while loop be re-written as a for loop? If
yes, please describe how you would convert a generic while loop into a
for loop. If no, give an example of a while loop that cannot be re-written
as a for loop.
2. Can every for loop be re-written as a while loop? (Hint:
recall today's lecture) If yes, please describe how you would convert
a generic for loop into a while loop. If no, give an example of a
for loop that cannot be re-written as a while loop.
3. Let's define a new language called C-. C- is the C language
with no for loops. Do C and C- have the same expressive power?
(Expressive power means that if you can write a program in C then you can
write a program in C- and if you can write a program in C- you can write
a program in C.) Why or why not?
while (condition) {
statement;
}
can be re-written as:
for ( ; condition; ) {
statement;
}
(The instructor might need to help the students with this since having an empty initialization and an empty update might confuse the students.)
2. Yes, every for loop can be re-written as a while loop.
for (initialization; condition; update) {
statement;
}
can be re-written as:
initialization;
while (condition) {
statement;
update;
}
3. Yes, C and C- have the same expressive power. We just showed that every for loop can be re-written as a while loop, so this is how one would convert a C program to a C- program. A C- program is a valid C program since C- is a subset of the C language.