इस समस्या में, हमें एक मैट्रिक्स दिया गया है। हमारा काम ऊपरी त्रिकोण और निचले त्रिकोण के योग को प्रिंट करने के लिए एक प्रोग्राम बनाना है।
निचला त्रिभुज
M00 0 0 … 0 M10 M11 0 … 0 M20 M21 M22 … 0 … Mrow0 Mrow1 Mrow2 … Mrow col
ऊपरी त्रिकोण
M00 M01 M02 … M0col 0 M11 M12 … M1col 0 0 M22 … M2col … 0 0 0 … Mrow col
समस्या को समझने के लिए एक उदाहरण लेते हैं,
Input: {{5, 1, 6}
{8, 2, 0}
{3, 7, 4}}
Output: upper triangle sum = 18
lower triangle sum = 29
Explanation:
Sum of upper triangle sum = 5 + 1 + 6 + 2 + 0 + 4 = 18
Sum of lower triangle sum = 5 + 8 + 2 + 3 + 7 + 4 = 29 इस समस्या का एक सरल उपाय। हम ऊपरी त्रिकोणीय तत्वों और निचले त्रिकोणीय तत्वों में सरणी को पार करने के लिए लूप का उपयोग करेंगे। योग को दो अलग-अलग चरों, lSum और uSum में परिकलित करें।
उदाहरण
हमारे समाधान की कार्यप्रणाली को दर्शाने के लिए कार्यक्रम,
#include <iostream>
using namespace std;
int row = 3;
int col = 3;
void sum(int mat[3][3]) {
int i, j;
int uSum = 0;
int lSum = 0;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++) {
if (i <= j) {
uSum += mat[i][j];
}
}
cout<<"Sum of the upper triangle is "<<uSum<<endl;
for (i = 0; i < row; i++)
for (j = 0; j < col; j++) {
if (j <= i) {
lSum += mat[i][j];
}
}
cout<<"Sum of the lower triangle is "<<lSum<<endl;
}
int main() {
int mat[3][3] = { { 5, 1, 6 },
{ 8, 2, 0 },
{ 3, 7, 4 }};
sum(mat);
return 0;
} आउटपुट
Sum of the upper triangle is 18 Sum of the lower triangle is 29