for
loop, the while
loop and the do-while
loop. Here are three loops that do the same thing; count from 1 to 10.
//for loop
for(int nNum1 = 1; nNum1 <= 10; nNum1++)
{
cout<<nNum1<<endl;
}
//do-while loop
int nNum2 = 1;
do
{
cout<<nNum2<<endl;
nNum2++;
}while(nNum2 <= 10);
//while loop
int nNum3 = 1;
while(nNum3 <= 10)
{
cout<<nNum3<<endl;
nNum3++;
}
You can also use other data types in a loop. The following for
loop will display the letters of the alphabet seperated by commas:
for(char cLetter = 'a'; cLetter<='z'; cLetter++)
cout<<cLetter<<", ";
Notice that you can declare and initialize a variable in a for
loop. Also notice that if you are only
including one line of code inside the loop, you don't need curly braces.
While all three loops perform the same
basic task, they each have their strengths. If you know how many times you want a loop to repeat, then use a
for
loop. If you don't know how many times it should repeat, then use a while
or a
do-while
. A do-while
loop will always execute at least one time, where a
while
loop may never execute.
Your assignment is to write four programs. Three of the programs will do exactly the same thing, but
each program will use one of the c++ repetition structures. You are to use the circle()
function from winbgim.h
to generate circles of different sizes and colors. The following program
produces a series of concentric magenta circles that appear to "grow". The circles have a center at (300, 250)
and a radius of nRadius. Try this out with different colors (BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN,
LIGHTGRAY, DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE
).
Make sure you read the handout on how to make a graphics program using Dev C++.
You can use this program as a starting point for your assignment.
#include "winbgim.h"
void DrawCircles ();
int main ()
{
initwindow(640, 480);
DrawCircles();
getch();
closegraph();
return 0;
}
void DrawCircles ()
{
setcolor(MAGENTA);
for (int nRadius = 0; nRadius<=200; nRadius = nRadius + 20)
{
delay(1000); //delay in milliseconds, 1000ms = 1 second
circle(300,250,nRadius); //make a circle with center 300,250 and radius nRadius
}
}