loop for entering numbers into array
Apr 12, 2016 at 6:26pm UTC
for the part where I'm entering 20 integers into the array that are greater than 0 and less than 100 i had to put i-- to make it so when i entered a number out of range it did not become part of the 20 integers. i was wondering if there is a better way to do this?
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
#include <iostream>
#include <cctype>
using namespace std;
/********************PROTOTYPES**************************/
void getValues(int userVals[], const int number);
/***********************************************************/
int main(){
int userVals[20];
const int number = 20;
getValues(userVals, number);
return 0;
}
/**********************Functions************************/
void getValues(int userVals[], const int number){
int i = 0;
for (i = 0; i < number; ++i) {
cout << "Enter 20 integer values greater then zero and less than 100 " << endl;
cin >> userVals[i];
if (userVals[i] < 0 || userVals[i] > 100 ){
cout << "you have entered an invalid number" << endl;
i--;
}
else
continue ;
}
cout << "You entered: " ;
for (i = 0; i <number; ++i) {
cout << userVals[i] << " " ;}
}
Apr 12, 2016 at 11:39pm UTC
You can use the while loop to validate the user's input.
For instance:
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
#include <iostream>
void inputArray(int num[], int sz);
void displayArray(int num[], int sz);
int main()
{
const int MAXELEMENTS{ 20 };
int num[MAXELEMENTS] = { 0 };
inputArray(num, MAXELEMENTS);
displayArray(num, MAXELEMENTS);
return 0;
}
void inputArray(int num[], int sz)
{
int inputCounter{ sz };
for (int count = 0; count < sz; count++)
{
std::cout << "Enter a number from 0 to 100.\n" ;
std::cin >> num[count];
while (num[count] < 0 || num[count] > 100)
{
std::cout << "The number " << num[count] << " is not between 0 and 100.\n" ;
std::cout << "Enter a number from 0 to 100.\n" ;
std::cin >> num[count];
}
inputCounter--;
std::cout << "You have " << inputCounter << " left\n" ;
}
}
void displayArray(int num[], int sz)
{
std::cout << "Displaying the numbers you inputted...\n" ;
for (int count = 0; count < sz; count++)
std::cout << num[count] << std::endl;
}
Topic archived. No new replies allowed.