牛骨文教育服务平台(让学习变的简单)
博文笔记

用一个for循环打印出一个二维数组

创建时间:2017-03-24 投稿人: 浏览次数:273



#include<iostream>
#include<iomanip>
using std::cout;
using std::endl;
using std::setw;


int main()
{
void print2(int a[][3]);
void print1(int a[][3]);
int a[][3]={{1,2,3},{4,5,6},{7,8,9},{1,2,3}};
        print2(a);                                  
print1(a);
   

        system("pause");
return 0;
    
}


void print2(int a[][3])                             //两个for循环打印一个二维数组
{
const int rows=4;
const int cols=3;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
cout<<setw(2)<<a[i][j];
cout<<endl;
}
}




void print1(int a[][3])                          //一个for循环打印一个二维数组;
{
const int rows=4;
const int cols=3;


for(int i=0;i<rows*cols;i++)
cout<<setw(2)<<a[i/cols][i%cols];

}



分析:二维数组在内存中是默认是按照行存储的,则可以将二维数组array[rows][cols]看成一个一维数组,

            i标识在一维数组中的位置,则array在二维数组中的行号和列号分别为[i/cols]、[i%cols]









声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。