I need help with programing in C++. Write a program in which you create a 2D arr
ID: 3812804 • Letter: I
Question
I need help with programing in C++.
Write a program in which you create a 2D array of type double with 32 rows and 8 columns. Populate it with random real numbers between 100.0 and 200.0 and print out the array in tabular format. Next, copy the values into a 1D array and sort the array. Display the median value. Finally, modify the linear search function. Ask the user to enter a maximum search limit and a minimum search limit. The search function should return the index of the first number that falls in the range.
Explanation / Answer
C++ code:
#include <bits/stdc++.h>
using namespace std;
int linearsearch(vector<double> v, double l, double r)
{
for (int i = 0; i < v.size(); ++i)
{
if(v[i] >= l and v[i] <= r)
{
return i;
}
}
return -1;
}
double Median(vector<double> v)
{
double median;
int size = v.size();
if (size % 2 == 0)
{
median = (v[size / 2 - 1] + v[size / 2]) / 2;
}
else
{
median = v[size / 2];
}
return median;
}
int main()
{
vector< vector<double> > Array;
for (int i = 0; i < 32; ++i)
{
vector<double> tmp ;
for (int j = 0; j < 8; ++j)
{
tmp.push_back(100 + rand()%100 + 1);
}
Array.push_back(tmp);
}
vector<double> singleArray;
for (int i = 0; i < 32; ++i)
{
for (int j = 0; j < 8; ++j)
{
singleArray.push_back(Array[i][j]);
cout << Array[i][j] << " ";
}
cout << endl;
}
sort(singleArray.begin(),singleArray.end());
cout << "Median = " << Median(singleArray) << endl;
double l,r;
cout << "Enter Min of the limit ";
cin >> l;
cout << "Enter Max of the limit ";
cin >> r;
int index = linearsearch(singleArray,l,r);
if(index == -1)
{
cout << "Number not found!";
}
else
{
cout << "Number " << singleArray[index] << " found at index " << index;
}
return 0;
}
Sample Output:
142 168 135 101 170 125 179 159
163 165 106 146 182 128 162 192
196 143 128 137 192 105 103 154
193 183 122 117 119 196 148 127
172 139 170 113 168 200 136 195
104 112 123 134 174 165 142 112
154 169 148 145 163 158 138 160
124 142 130 179 117 136 191 143
189 107 141 143 165 149 147 106
191 130 171 151 107 102 194 149
130 124 185 155 157 141 167 177
132 109 145 140 127 124 138 139
119 183 130 142 134 116 140 159
105 131 178 107 174 187 122 146
125 173 171 130 178 174 198 113
187 191 162 137 156 168 156 175
132 153 151 151 142 125 167 131
108 192 108 138 158 188 154 184
146 110 110 159 122 189 123 147
107 131 114 169 101 192 163 156
111 160 125 138 149 184 196 142
103 151 192 137 175 121 197 122
149 200 169 185 182 135 154 200
119 139 101 189 128 168 129 194
149 184 108 122 111 118 114 115
110 117 136 152 101 150 120 157
199 104 125 109 145 110 190 103
196 186 194 144 124 188 115 104
149 101 159 119 181 197 199 182
190 199 110 158 173 123 139 193
139 180 191 158 159 192 116 189
157 112 103 135 173 156 129 147
Median = 146.5
Enter Min of the limit
100
Enter Max of the limit
110
Number 101 found at index 0