开发者

array questions (homework)

I am stuck on the last few problems of an array exercise. Could anyone lend a hand?

Writ开发者_运维知识库e C++ statements that do the following:

  1. store 5 in the first column of an array and make sure that the value in each subsequent column is twice the value in the previous column.

  2. print the array one row per line.

  3. print the array one column per line.

I think this will work for question #2:

for (row = 0; row < 10; row++)
     {
         for (col = 0; col < 20; col++)
             cout << alpha[row][col] << " ";

             cout << endl;
     }     

but question 1 and 3 have me stumped. thanks

Here's what i came up with after your tips. thanks everyone

3.

for (col = 0; col < 20; ++col)
     {
         for (row = 0; row < 20; ++row)
             cout << alpha[row][col] << " ";

             cout << endl;
     }     

1.

for (row = 0; row < 10; row++)
   alpha[row][0] = 5;

   for (col = 1; col < 20; col++)
       for (row = 0; row < 10; row++)
       alpha[row][col]=alpha[row][col-1]*2;


For #1, run a loop that starts at zero and goes until the number of rows. In each iteration just assign 5 to array[row][0]=5 (since coloumn 0 is the first coloumn).

Now run a loop from 1 to the number of coloumns. Inside, run another loop for each row. just assign array[row][col]=array[row][col-1]*2.

For #3, simply reverse the order of the loops. We iterate over all coloumns, and for each coloumns we have to iterate over all rows and print a newline after that.

I would post code, but it is better for you to try to understand and write the code yourself.


  1. for each row, insert 5 into the first column (index 0), then in a loop, iterate from 1 through the number required, and the value at the current column index = 2 * value at previous column index (i.e. col - 1).

  2. re-arrange the row, col loops.


Well for 1, just take the previous col and multiple by 5. So when your going through a loop, it'd be like col[position your at now] = col[prev pos]*2


For question #3, just reverse the order of loops, as

 for (col = 0; col < 20; col++)
 {
     for (row = 0; row < 10; row++)
         cout << alpha[row][col] << " ";
     cout << endl;
 }   

Isn't it simple?

For question #1, just use the same reverse order of loops, and do this

 int value = 5;
 for (col = 0; col < 20; col++)
 {
     for (row = 0; row < 10; row++)
         alpha[row][col] = value;
     value = 2 * value;
 }   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜