C++入门经典-例6.2-将二维数组进行行列对换
1:一维数组的初始化有两种,一种是单个逐一赋值,一种是使用聚合方式赋值。聚合方式的例子如下:
int a[3]={1,2,3};
int a[]={1,2,3};//编译器能够获得数组元素的个数
int a[5]={1,2,3};//前3个元素被赋值,后2个元素的值为0
2:二维数组的初始化也分为单个元素逐一赋值和使用聚合方式赋值两种。聚合方式的例子如下:
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int a[3][4]={1,2,3,4};//相当于给第一行赋值,其余的元素全为0
3:代码如下:
// 6.2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int fun(int array[3][3])
{
int i,j,t;
for(i=0;i<3;i++)
for(j=0;j<i;j++)
{
t=array[i][j];
array[i][j]=array[j][i];
array[j][i]=t;
}
return 0;
}
void main()
{
int i,j;
int array[3][3]={{1,2,3},{4,5,6},{7,8,9}};//一种二维数组的赋值方法
cout << "Converted Front" <<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout << setw(7) << array[i][j] ;//设置输出的宽度
cout<< endl;
}
fun(array);//带入的是数组名
cout << "Converted result" <<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout << setw(7) << array[i][j] ;
cout<< endl;
}
}
View Code
运行结果: