-
Notifications
You must be signed in to change notification settings - Fork 0
/
18.cpp
74 lines (52 loc) · 1.23 KB
/
18.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
@Author: Amritanshu Sikdar
Session: 2018-'19
Repository: https://github.com/amritanshusikdar/CS30PracticalQuestion
*/
// Find sum of all alternate elements of a 2D Array
#include <constream.h>
int alterSum(int a[][5], int, int);
void main()
{
clrscr();
int i, j;
int arr[5][5], sum;
// Input
for (i=0; i < 5; i++)
{
for (j=0; j < 5; j++)
{
cout << "A[" << i << "][" << j << "]: ";
cin >> arr[i][j];
}
}
// Getting the sum of alternate elements
sum = alterSum(arr,5,5);
// Output
cout << "Entered array is: \n";
for (i=0; i < 5; i++)
{
for (j=0; j < 5; j++)
{
cout << arr[i][j] << "\t";
}
cout << endl;
}
cout << "Sum of all alternate elements: " << sum << endl;
getch();
}
int alterSum(int a[][5], int m, int n)
{
int i, j, sum=0;
for (i=0; i < m; i++)
{
for (j=0; j < n; j++)
{
if(i%2 == 0 && j%2 == 0) // Checking if both indices are even
sum += a[i][j];
if(i%2 == 1 && j%2 == 1) // Checking if both indices are odd
sum += a[i][j];
}
}
return sum;
}