Reputation:
I realized after I was done that I needed to loop it until they type q, Im not sure how to do it though. What I'm looking for is until the last option (‘q’ or ‘Q’) is selected, the main program comes back at the beginning, asking the user to insert a letter.
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
#include <iostream>
using namespace std;
int main()
{
int array[5];
int i, num, x;
char c;
float average = 0;
srand(time(0)); //This makes the set of numbers differnet every time
for (i = 1; i <= 5; i++)
{
array[i] = (rand() % 5) + 15;
}
cout << "Array elements are: \n";
for (i = 1; i <= 5; i++)
{
cout << array[i] << endl;
}
cout << "\nEnter your choice:\n MENU\n[P]osition\n[R]everse\n[A]verage\n[S]earch\n[Q]uit\n";
cin >> c;
cout << "\nYou chose option " << c << endl;
switch (c)
{
case 'P':
cout << "This is the array with each element's position" << endl;
for (i = 1; i <= 5; i++)
{
cout << "Value at position " << i << " is " << array[i] << endl;
}
break;
case 'R':
cout << "The array in reverse order is:" << endl;
for (i = 5; i >= 1; i--)
{
cout << array[i] << endl;
}
break;
case 'A':
cout << "The average of the array is:" << endl;
for (i = 1; i <= 5; i++)
{
average = average + array[i];
}
cout << average / 5;
break;
case 'S':
cout << "Enter a number to search the array:" << endl;
cin >> num;
x = 0;
for (i = 1; i <= 5; i++)
{
if (array[i] == num)
{
x = 1;
break;
}
}
if (x == 1)
{
cout << num << " is found at position " << i;
}
else
{
cout << "This number is not in the array";
}
break;
case 'Q':
exit(1);
return 0;
}
}
Upvotes: 0
Views: 65
Reputation: 482
You can put your code in a while loop like this:
int array[5];
int i, num, x;
char c = '\0';
float average = 0;
srand(time(0)); //This makes the set of numbers differnet every time
for (i = 1; i <= 5; i++)
{
array[i] = (rand() % 5) + 15;
}
while (c != 'q')
{
cout << "Array elements are: \n";
for (i = 1; i <= 5; i++)
{
cout << array[i] << endl;
}
cout << "\nEnter your choice:\n MENU\n[P]osition\n[R]everse\n[A]verage\n[S]earch\n[Q]uit\n";
cin >> c;
cout << "\nYou chose option " << c << endl;
switch (c)
{
case 'P':
cout << "This is the array with each element's position" << endl;
for (i = 1; i < 5; i++)
{
cout << "Value at position " << i << " is " << array[i] << endl;
}
break;
case 'R':
cout << "The array in reverse order is:" << endl;
for (i = 5; i >= 1; i--)
{
cout << array[i] << endl;
}
break;
case 'A':
cout << "The average of the array is:" << endl;
for (i = 1; i <= 5; i++)
{
average = average + array[i];
}
cout << average / 5;
break;
case 'S':
cout << "Enter a number to search the array:" << endl;
cin >> num;
x = 0;
for (i = 1; i <= 5; i++)
{
if (array[i] == num)
{
x = 1;
break;
}
}
if (x == 1)
{
cout << num << " is found at position " << i;
}
else
{
cout << "This number is not in the array";
}
break;
case 'Q':
exit(1);
return 0;
}
}
So the code will only run if c
does not equal q
. Hope this helps :)
Upvotes: 1