In C++, you can model two-dimensional arrays, but you are not restricted to just two dimensions. Depending on your need and the nature of the application, you can model multidimensional arrays in memory
Declaring and Initializing Multidimensional Arrays
Syntax:
int Arr [2][3];
int Arr [2][3] = {{0, 1, 2}, {3, 4, 5}};
int Arr[3][3] = {{154, 219, 362}, {101, 248, 417}, {921,675, 811}};
Accessing Elements in a Multidimensional Array
#include <iostream>
using namespace std;
int main(){
int Arr[3][3] = {{154, 219, 362}, {101, 248, 417}, {921,675, 811}};
cout << “row 0: “ << Arr[0][0] << “ “<< Arr[0][1] << “ “<< Arr[0][2] << endl;
cout << “row 1: “ << Arr[1][0] << “ “<< Arr[1][1] << “ “<< Arr[1][2] << endl;
cout << “row 2: “ << Arr[2][0] << “ “<< Arr[2][1] << “ “<< Arr[2][2] << endl;
getch();
return 0;
}
Example
#include<iostream>
#include<math.h>
int arr[5][5],n;
// input matrix
void Input(){
cout<<"\n
Input the number element of matrix:\n";
do{
cout<<"\n
n= "; cin>>n;
if(n<2||n>5) cout<<"\n Input n again ";
} while (n<2||n>5);
// Input matrix
cout<<"\n
Input matrix:\n";
for(int
i=0;i<n;i++)
for(int
j=0;j<n;j++){
cout<<"\n
arr["<<i<<"]["<<j<<"]=";
cin>>arr[i][j];
}
}
// Print matrix
void Print(){
cout<<"\n
Matrix:\n";
for(int
i=0;i<n;i++){
for(int
j=0;j<n;j++)
cout<<arr[i][j]<<"\t";
cout<<"\n";
}
}
//main function
int main(){
Input();
Print();
getch();
return 0;
}
No comments:
Post a Comment