Create an array of user-defined size. Fill this array with random numbers (Auto Generated). Create a menu from 1 to 6 to perform an operation on the array. As the option is selected, it calls a function with appropriate parameters and return type.
1. Average of all values.
2. Print the array
3. Find the minimum
4. Find maximum
5. Search a number
6. Print the array in reverse order
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int fillingArrayRandomly (int arr[], int len) {
srand(time(NULL));
int min, max;
cout << "Filling the array randomly between [min, max].\n";
cout << "min: "; cin >> min;
cout << "max: "; cin >> max;
for (int i = 0; i < len; i++) {
arr[i] = min + rand() % (max - min + 1);
}
}
int main () {
int n;
int array[n];
cout << "Enter length of the array: "; cin >> n;
// filling the array with random numbers
fillingArrayRandomly(array, n);
cout << "\n1. Average of all values.\n";
cout << "2. Print the array.\n";
cout << "3. Find the minimum.\n";
cout << "4. Find the maximum.\n";
cout << "5. Search a number.\n";
cout << "6. Print the array in reverse order.\n";
int option;
while (true) {
cout << "\nChoose one option from the menu and to finish the program enter nonMenuNumber. ";
cin >> option;
if (option == 1) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
cout << "Average of all values of the array: " << (float) sum / n;
}
else if (option == 2) {
cout << "Our array: ";
for (int i = 0; i < n; i++) {
cout << array[i] << " ";
}
}
else if (option == 3) {
int minElement = array[0];
for (int i = 0; i < n; i++) {
if (minElement > array[i]) {
minElement == array[i];
}
}
cout << "minimum element of the array: " << minElement;
}
else if (option == 4) {
int maxElement = array[0];
for (int i = 0; i < n; i++) {
if (maxElement < array[i]) {
maxElement == array[i];
}
}
cout << "maximum element of the array: " << maxElement;
}
else if (option == 5) {
int search, index = -1;
cout << "Enter a number for search: ";
cin >> search;
for (int i = 0; i < n; i++) {
if (array[i] == search) {
index = i;
break;
}
}
if (index != -1) {
cout << search << " found in the array at a index of " << index;
}
else {
cout << "Number not found.";
}
}
else if (option == 6) {
cout << "Reverse array: ";
for (int i = n - 1; i >= 0; i--) {
cout << array[i] << " ";
}
}
else {
cout << "program finished.";
break;
}
}
}
Comments
Leave a comment