-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecur_5.cpp
107 lines (101 loc) · 2.26 KB
/
recur_5.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//Addition of two 1D Arrays recursively
#include <iostream>
int input(int[], int, char);
void display(int[], int);
int add(int[], int[], int[], int);
using namespace std;
int main()
{
int m;
cout << "Enter the size of the array: ";
cin >> m;
int a[m], b[m], result[m];
char arr1 = 'a';
char arr2 = 'b';
int size = sizeof(a) / sizeof(a[0]);
cout << "Enter the elements of 1st Matrix: " << endl;
input(a, size, arr1);
cout << "Displaying the Matrix: " << endl;
display(a, size);
cout << "Enter the elements of 2nd Matrix: " << endl;
input(b, size, arr2);
cout << "Displaying the Matrix: " << endl;
display(b, size);
add(a, b, result, size);
cout << "Displaying the Addition of 2 Square Matrix: " << endl;
display(result, size);
return 0;
}
int input(int a[], int size, char arr)
{
if (arr == 'a')
{
for (int i = 0; i < size; i++)
{
cout << arr << "[" << i << "] = ";
cin >> a[i];
}
}
else
{
for (int i = 0; i < size; i++)
{
cout << arr << "[" << i << "] = ";
cin >> a[i];
}
}
cout << endl;
return a[size];
}
void display(int a[], int size)
{
cout << "[";
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
}
cout << "]";
cout << endl;
}
int add(int a[], int b[], int result[], int size)
{
if (size == 0){
return 0;
}
else{
result[size-1] = a[size-1] + b[size-1];
add(a, b, result, size - 1);
}
return result[size];
}
/******************************
* Workings
* Let size =3
* a[0] = 1
* a[1] = 2
* a[2] = 3
*
* b[0] = 4
* b[1] = 5
* b[2] = 6
*
* Now in Recursion:
*
* result[size-1 => 3-1 = 2] = a[size-1 => 3-1 = 2] + b[size-1 => 3-1 = 2] = 3 + 6 = 9
*
*
* result[size-1 => 2-1 = 1] = a[size-1 => 2-1 = 1] + b[size-1 => 2-1 = 1] = 2 + 5 = 7
*
* result[size-1 => 1-1 = 0] = a[size-1 => 1-1 = 0] + b[size-1 => 1-1 = 0] = 1 + 4 = 5
*
* Now the recursion will end and the result will be:
* result[0] = 5
* result[1] = 7
* result[2] = 9
*
*
*
*
*
*
* *******************************/