-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday4_Array1.cpp
More file actions
126 lines (102 loc) · 2.6 KB
/
day4_Array1.cpp
File metadata and controls
126 lines (102 loc) · 2.6 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <array>
#include <iostream>
using namespace std;
// Array lecture 1
int main()
{
// finding smallest & largest in an array
int smallest = INT_MAX;
int greatest = INT_MIN;
int arr[] = {342, 54, 35656, 56356, 4645442, 2, 32212, 54, 2322};
int len = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < len; i++)
{
if (arr[i] < smallest)
smallest = arr[i];
if (arr[i] > greatest)
greatest = arr[i];
}
cout << "the smallest is :: " << smallest << endl;
cout << "the greatest is :: " << greatest << endl;
// pass by reference, we pass the address i.e. real value
// linear search
int target = 2;
bool found = false; // to check
for (int i = 0; i < len; i++)
{
if (arr[i] == target)
{
cout << "The value is found in array at : " << i << endl;
found = true;
break;
}
}
if (!found)
{
cout << "The value not found" << endl;
}
// arrray reversal (using two pointer approach)
int s = 0;
int e = len - 1;
while (s < e)
{
// swap(arr[s], arr[e]);
// s++;
// e--;
swap(arr[s++], arr[e--]);
}
cout << "Reversed array : ";
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
// sum & product of all numbers
int sum = 0;
long long prod = 1; // do not initialise like prod = 0, on large value code will break
for (int i = 0; i < len; i++)
{
sum += arr[i];
prod *= arr[i];
}
cout << "sum is :: " << sum << endl;
cout << "product is :: " << prod << endl;
// swap min max of arr
cout << "swapped array : ";
for (int i = 0; i < len; i++)
{
if (arr[i] == smallest)
{
arr[i] = greatest;
}
else if (arr[i] == greatest)
{
arr[i] = smallest;
}
// swap(arr[i],greatest)
cout << arr[i] << " ";
}
cout << endl;
// print unique value (repeated num)
// int count = 1;
// for (int i = 1; i < len; i++)
// {
// if (arr[i] == arr[i - 1])
// {
// count++;
// }
// else
// {
// if (count > 1)
// {
// cout << " unique value is : " << arr[i - 1] << "repeated " << count << " times" << endl;
// }
// count = 1;
// }
// }
// if (count > 1)
// {
// cout << "Value " << arr[len - 1] << " repeated " << count << " times" << endl;
// }
return 0;
}