Archived

This topic is now archived and is closed to further replies.

A simple question about for loops

Recommended Posts

Is there a simpler approach to writing this on the screen: 1 1 2 1 2 3 1 2 3 4 1 2 3 1 2 1 The program must be done using for loops as I''m not advanced enough to go into other topics at the moment... I solved the problem with two neste for loops but I was wondering if it could be solved with only one loop as there is symmetry here. This is my solution:

for (int i = 0; i < 4; i++)
{
for (int j = 0; j <= i; j++)
{
cout << j+1 << " ";
}
cout << endl;
}

for (i = 3; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
cout << j+1 << " ";
}
cout << endl;
}

Learning is the ultimate to me...

Share on other sites
BeerNutts    4401
POssible solution:

    char cString[5];int i;memset((void *)cString, 0, 5);for(i = 0; i < 4; i++){    cString[i] = ('0' + i+1);    printf("%s\n", cString);}for (i = 3; i > 0; i--){    cString[i] = 0;    printf("%s\n", cString);}

That should do it too (but I didn't test it).

EDIT: Fixed OOPS

[edited by - BeerNutts on June 7, 2002 4:08:57 PM]

Share on other sites
coelurus    259
#define ABS(x) (x < 0 ? -x : x)

for (i = 0; i < 7; i++) {
for (j = 1; j < 5 - ABS(3 - i); j++)
cout << j << " ";
cout << endl;
}

Dunno if it''s quicker...

Share on other sites
IndirectX    122
I don't think you can get any simpler than this, but if you want to collapse two loops into one:

      // Define absolute value functionint abs(int x) { if (x >= 0) return x; else return -x; }// ...for (int i = 0; i < 7; i++) {    for (int j = 0; j < 4-abs(3-i); j++)        cout << j+1 << " ";    cout << endl;}

If you don't want to use any functions, then you can do

       for (int i = 0; i < 7; i++) {    int k = 3-i;    if (k < 0) k = -k;    for (int j = 0; j < 4-k; j++)        cout << j+1 << " ";    cout << endl;}

I type too slow.

[edited by - IndirectX on June 7, 2002 4:20:30 PM]

Share on other sites
Jason Zelos    211
for (int Y=1;Y<4;Y++)    for (int X=1;X<=Y;X++)       {       // move to line Y       cout << X;       // move to line (4*2)-Y       if (Y<4) cout << (4*2)-X; //so we don't get 2 middle lines       }

As I don't know the operaters (if any) for moving the cursor about, this is of limited use. But recursion is the answer.

      void WriteLine(int X, int &OrigX) // pass by value X, by ref Orig X{   cout << X;  if (X<OrigX)    {    WriteLine(X+1);    }  cout << endl;}void WriteNumbers(int Y, int &OrigY) // pass by value Y, by ref Orig Y{  WriteLine(1,Y);   if(Y<OrigY)  {    WriteNumbers(Y+1,OrigY);    WriteLine(1,Y);  }}WriteNumbers(1,4); //start, finish

,Jay

Edit: changed code to source.

Edit: Pass by Reference gives address of varible, Pass by Value gives copy of varible for the duration of the function. If you change a by value var it has the effect of reverting to its pre-function state.

[edited by - Jason Zelos on June 7, 2002 4:45:59 PM]