Take a look at the following program :
// file : rect.C
// This program draws a rectangle of #'s and X's on the screen.
// Again, kinda lame, but who cares?
#include <iostream.h>
int main()
{
cout << "X#X#X#X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "# #" << endl;
cout << "X X" << endl;
cout << "X#X#X#X" << endl;
return(0);
}
Take note of all the repeated lines of code. It is silly to reproduce so many lines of code. There is a better way of doing it. Look at this :
// file : rect_while.C
// This program draws a rectangle of #'s and X's on the screen.
// Again, kinda lame, but who cares?
#include <iostream.h>
int main()
{
int i;
cout << "X#X#X#X" << endl;
i=0;
while (i<7)
{
cout << "# #" << endl;
cout << "X X" << endl;
i = i + 1;
}
cout << "X#X#X#X" << endl;
return(0);
}
So, what did I do? I replaced just about all of the repeated code
with a while loop. There is another way to make a loop. Check
this out :
// file : rect_do_while.C
// This program draws a rectangle of #'s and X's on the screen.
// Again, kinda lame, but who cares?
#include <iostream.h>
int main()
{
int i;
cout << "X#X#X#X" << endl;
i=0;
do
{
cout << "# #" << endl;
cout << "X X" << endl;
i = i + 1;
}
while (i<7);
cout << "X#X#X#X" << endl;
return(0);
}
And much to your surprise (or chagrin), here's a third way of doing it :
// file : rect_for.C
// This program draws a rectangle of #'s and X's on the screen.
// Again, kinda lame, but who cares?
#include <iostream.h>
int main()
{
int i;
cout << "X#X#X#X" << endl;
for (i=0 ; i<7 ; i=i+1)
{
cout << "# #" << endl;
cout << "X X" << endl;
}
cout << "X#X#X#X" << endl;
return(0);
}
What is different between these three methods of doing loops?