Looks like a continuation of
http://www.cplusplus.com/forum/beginner/137196/
what is the purpose of y=x here in this code? |
I suppose the simple answer would be that it fulfils the requirement of the box captioned
y = x
in the flowchart. So why is the flowchart that way? You'd have to ask the person who drew the chart, what is the purpose of this algorithm, it is a solution to what task?
In practical terms, y is the loop counter which controls the number of iterations of the inner loop. It is given an initial value x, and the loop executes so long as y is no larger than 5.
On a more mundane level, the above code, though expressed using the
for
loop syntax, is actually implementing the while loop, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 0;
int z = 1;
while (x > 0)
{
y = x;
while (y <= 5)
{
cout << z;
z = z + 1;
y = y + 1;
}
cout << endl;
x = x - 1;
z = 1;
}
cout<<"aw";
}
|
... but you could put the for loops to work, by using each of the three parts of the loop header. The same algorithm implemented using the
for
loop might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
using namespace std;
int main()
{
for (int x = 5, z = 1; x > 0; x--, z = 1)
{
for (int y = x; y <= 5; y++, z++)
cout << z;
cout << endl;
}
cout<<"aw";
}
|
or a slight variation, though this may be a somewhat more liberal interpretation of the flowchart:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
using namespace std;
int main()
{
for (int x = 5; x > 0; x--)
{
for (int y = x, z = 1; y <= 5; y++)
cout << z++;
cout << endl;
}
cout<<"aw";
}
|
You may want to refresh your understanding of these loop structures, see the tutorial page:
http://www.cplusplus.com/doc/tutorial/control/