C++ FOR LOOP ONLY task

C++ FOR LOOP ONLY task

本文关键字:task ONLY LOOP FOR C++      更新时间:2023-10-16

好的,所以我有这个C++任务,通过使用ONLY for循环,我必须创建这个表

1 5 9 13

2 6 10 14

3 7 11 15

4 8 12 16

到目前为止,有了这行代码:

int n;
int count = 1;
cout << "Please enter N: "; cin >> n;
for (int i = 1;i<=n;i++)
{
    cout << i << ", ";
    for (int j = count;j<n;j++)
    {
        count+=n;
        cout << count << ", ";
    }
    cout << endl;
}

我设法只得到

1  5  9  13
2
3
4

我下一步该怎么办?

你走在了正确的轨道上。您应该注意,行中任意两个连续条目之间的差为n,第一个条目是行号。

for (int i = 1;i<=n;i++)
{
    // loops from 0 to n-1
    for (int j = 0;j<n;j++)
    {
        cout << i + j*n << " ";
    }
    cout << endl;
}

如果您想反转偶数行,那么对于这些行,您将向后运行for循环。

for (int i = 1;i<=n;i++)
{
    if ( i % 2 == 1 ) {
      for (int j = 0;j<n;j++)
        cout << i + j*n << " ";
    } else {
      for (int j = n-1; j>=0 ; j-- )
        cout << i + j*n << " ";
    }
    cout << endl;
}

如果您想反转偶数列,那么您可以看到模式。

for (int i = 1;i<=n;i++)
{
    for (int j = 1; j <= 4 ; j-- )
    {
        if ( j % 2 == 0 ) {
          cout << (5-i) + (j-1)*n << " ";
        }
        else
          cout << i + (j-1)*n << " ";
    }
    cout << endl;
}

问题是count需要在内部for循环之后或之前重置:

for (int i = 1;i<=n;i++)
{
    cout << i << ", ";
// ***
    count = i;
// ***
    for (int j = count;j<n;j++)
    {
        count+=n;
        cout << count << ", ";
    }
    cout << endl;
}

你可以把它简化为Abishek的答案。

This problem can be solved by doing this coding.
#include<iostream>
#include <conio.h>
using namespace std;
main()
{
    int i,j,n;
    for (i=1;i<=4;i++)
    {
        n=i;
        for (j=1;j<=4;j++)
        {
            cout<<n<<"t";
            n=n+4;
        }
        cout<<endl;
    }
    getch ();
    return 0;
}
#include <iostream> 
using namespace std; 
int main()
{
    for (int i = 1 ; i <= 13 ; i +=4) 
    {
        cout << i << " " ; 
    }
    cout << endl; 
    for (int x = 2 ; x <= 14 ; x+=4)
    {
        cout << x << " " ;
    }
    cout << endl;
    for (int y = 3 ; y <= 15 ; y+=4) 
    {
        cout << y << " ";
    }
    cout << endl;
    for (int z = 4 ; z <= 16 ; z+=4) 
    {
        cout << z << " " ; 
    }
    cout << endl;
}

这是我的答案。我在Microsoft Visual C++2010学习版上写了它,它给了我书面答案。

相关文章: