Reputation: 47
I have a square matrix in my program. I want to sum the numbers on the diagonal of the matrix and multiply the numbers on the other diagonal of the matrix. I want to do it with a short way. I think "for" loop is what I'm looking for but I couldn't understand that how I can do it with "for".
Code is below:
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<iostream>
#include<math.h>
#include<sstream>
#include <iomanip>
#include<time.h>
using namespace std;
int main()
{
setlocale(LC_ALL,"turkish");
cout << "Problem 3\n" << "---------\n" << "Bir kare matrisin esas köşegeni üzerindeki
elemanlarının toplamını ve diğer köşegen üzerindeki elemanların çarpımını hesaplatan C
programı\n\n\n" << "Seçilen matris:\n" << "---------------\n";
int dizi[5][5] = {{1,-25,86,-46,8},{-15,63,48,75,-21},{5,-84,-6,32,10},{41,23,6,-14,-7},
{-19,-25,40,27,61}};
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
printf("%5d\t",dizi[i][j]);
}
cout << endl;
}
cout << endl;
int kosegenToplam = dizi[0][0] + dizi[1][1] + dizi[2][2] + dizi[3][3] + dizi[4][4]; // Here is the summing area.
int tersKoseCarpim = dizi[4][0] * dizi[3][1] * dizi[2][2] * dizi[1][3] * dizi[0][4]; // Here is the multiplying area.
cout << "Seçtiğim matrisin esas köşegeni üzerindeki sayıların toplamı = " << kosegenToplam << endl;
cout << "Seçtiğim matrisin diğer köşegeni üzerindeki sayıların çarpımı = " << tersKoseCarpim << "\n" << endl;
system("pause");
return 0;
}
Thanks for helping.
Upvotes: 0
Views: 83
Reputation: 4449
For the summing your indices are both the same and are incrementing by 1 each time. So write a simple for
loop that increments from 0 to 4:
// int kosegenToplam = dizi[0][0] + dizi[1][1] + dizi[2][2] + dizi[3][3] + dizi[4][4];
int kosegenToplam = 0;
for (int i = 0; i < 5; ++i) {
kosegenToplam += dizi[i][i];
}
For the multiplying you have 2 indices, i
and j
, that are different but are related by the formula i = 4-j
. So write the same loop where i
increments from 0 to 4 and calculate j
based on the value of i
:
// int tersKoseCarpim = dizi[4][0] * dizi[3][1] * dizi[2][2] * dizi[1][3] * dizi[0][4];
int tersKoseCarpim = 1;
for (int j = 0; j < 5; ++j) {
int i = 4-j;
tersKoseCarpim *= dizi[i][j];
}
You can combine them into a single loop:
int kosegenToplam = 0;
int tersKoseCarpim = 1;
for (int i = 0; i < 5; ++i) {
kosegenToplam += dizi[i][i];
tersKoseCarpim *= dizi[4-i][i];
}
Upvotes: 2
Reputation: 2716
Within the nested for
loops you can check the indices to see if the element is on a diagonal:
int kosegenToplam = 0;
int tersKoseCarpim = 1;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if (i == j)
kosegenToplam += dizi[i][j];
if (i+j == 4)
tersKoseCarpim *= dizi[i][j];
}
}
Upvotes: 1
Reputation: 11219
If you mean only one loop you can achieve this with modulo and divide:
for(int i=0;i<25;i++) {
printf("%5d\t",dizi[i/5][i%5]);
if (i % 5 == 4)
cout << endl;
}
Upvotes: 1