Program C ++ za dodavanje dvije matrice pomoću višedimenzionalnih nizova

Ovaj program uzima dvije matrice reda r * c i pohranjuje ih u dvodimenzionalni niz. Zatim program dodaje ove dvije matrice i prikazuje ih na zaslonu.

Da biste razumjeli ovaj primjer, trebali biste imati znanje o sljedećim temama programiranja na C ++:

  • C ++ višedimenzionalni nizovi
  • C ++ nizovi

U ovom programu od korisnika se traži da unese broj redaka r i stupaca c. Vrijednost r i c u ovom programu trebala bi biti manja od 100.

Od korisnika se traži da unese elemente dviju matrica (reda r * c).

Zatim program dodaje ove dvije matrice, sprema ih u drugu matricu (dvodimenzionalni niz) i prikazuje na zaslonu.

Primjer: Dodajte dvije matrice pomoću višedimenzionalnih nizova

 #include using namespace std; int main() ( int r, c, a(100)(100), b(100)(100), sum(100)(100), i, j; cout <> r; cout <> c; cout << endl << "Enter elements of 1st matrix: " << endl; // Storing elements of first matrix entered by user. for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) ( cout << "Enter element a" << i + 1 << j + 1 <> a(i)(j); ) // Storing elements of second matrix entered by user. cout << endl << "Enter elements of 2nd matrix: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) ( cout << "Enter element b" << i + 1 << j + 1 <> b(i)(j); ) // Adding Two matrices for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) sum(i)(j) = a(i)(j) + b(i)(j); // Displaying the resultant sum matrix. cout << endl << "Sum of two matrix is: " << endl; for(i = 0; i < r; ++i) for(j = 0; j < c; ++j) ( cout << sum(i)(j) << " "; if(j == c - 1) cout << endl; ) return 0; ) 

Izlaz

 Unesite broj redaka (između 1 i 100): 2 Unesite broj stupaca (između 1 i 100): 2 Unesite elemente 1. matrice: Unesite element a11: -4 Unesite element a12: 5 Unesite element a21: 6 Unesite element a22: 8 Unesite elemente 2. matrice: Unesite element b11: 3 Unesite element b12: -9 Unesite element b21: 7 Unesite element b22: 2 Zbir dvije matrice je: -1 -4 13 10 

Zanimljivi članci...