开发者

How do I display this number pattern in C++?

开发者 https://www.devze.com 2023-03-03 19:58 出处:网络
I have to display this number pattern: -3159 71217 15 21 using: int number = __________________; // assign correct initial value

I have to display this number pattern:

-3  1  5  9
7  12  17
15 21

using:

int number = __________________; // assign correct initial value
int row, col;

for (row = 1; row <= 3; row++)
{
    // adjust number so it displays the correct first value in the row
    ________________________________________________
    for (col = 1; col <= ___5 - row___; col++)
    {
      cout << setw (5) << number;

     // adjust number so it displays the next correct value in this row 
    ______________________number + row + 3;_________________________________ 
        } / /end inner for loop
 cout << endl;
 } // end outer for loop

I know number + row + 3 gets the correct numbers across but I cannot seem开发者_如何学编程 to get the correct start value.


Try this

number = -3

for(row = 1; row <= 3; row++){
   for (col = 0; col < 5 - row; col ++){
       display (number + col * (3 + row));
   }
   number += 12 - row * 2;
}

With your restrictions, that would be:

int number = 0; // assign correct initial value
int row, col;

for (row = 1; row <= 3; row++)
{
    // adjust number so it displays the correct first value in the row
    number += 12 - (row-1) * 2 - (row+2) * (6 - row);

    for (col = 1; col <= 5 - row; col++)
    {
        cout << setw (5) << number;

        // adjust number so it displays the next correct value in this row 
        number = number + row + 3;
    } / /end inner for loop
    cout << endl;
 } // end outer for loop

Explanation:

(not a bullet) + [12 - (row-1)*2] is for moving between -3, 7 and 15

(not a bullet) - [ ((row-1) + 2) * (5 - (row - 1))] is for compensating growth of the number in the internal loop

Since the result of the right part with row = 1 is -3, initial number is chosen as 0.


int number = -1; // assign correct initial value 
int row, col;  
for (row = 1; row <= 3; row++) {     
// adjust number so it displays the correct first value in the row
    number -=2;
    for (col = 1; col <= ___5 - row___; col++){       
        cout << setw (5) << number;       
        // adjust number so it displays the next correct value in this row
        ______________________number + row + 3;
    } / /end inner for loop  
    cout << endl;  
} // end outer for loop


#include<iostream>
using namespace std;

int main()
{ 
  int i,j; 
  int temp=-3;

  for(i=0;i<3;++i)
  {    
      for(j=0;j<4-i;++j)
      {
          cout<<temp<<" ";
          temp=temp+4+i;
      }

      temp=temp-(4+i);
      temp=temp-2;
      cout<<"\n";
  }

  char dd;
  cin>>dd;
  return 2;
}
0

精彩评论

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

关注公众号