I'm trying to check if the users input data falls within the range i want. so far i have it like this:
void getPlayersNumbers(int playerArray[], int size) {
cout << "Please enter 5 numbers between 1-5\n";
for (int i = 0; i < size; i++) {
cin >> playerArray[i];
if (playerArray[i] < 1 || playerArray[i] > 5) {
cout << "Please enter numbers between 1 and 5\n";
}
}
}
now if they enter a number less than 1 or greater than 5 the message shows up. The only problem is i can still only input 5 numbers total even if one of them is out of the range and the message shows up. what should i do so that the function will only end if they enter 5 numbers that are within my set range?
Consider what you are doing:
You get input.
You put that input into your array.
You check whether input was smaller than 1 or bigger than 5
Go back to 1.
Related
So the code is really simple, its just a main(), but there is something wrong in the if/else statement in the while cycle and I dont't know what it is, I thought this is how it supposed to work, but clearly its not.
The code is creating a 11-element array, but the 0th element of the array is typed in by the user. So for example I type in 5, the array have the numbers from 5 to 15. Then the program shows you the numbers in the array. Then you can type in any numbers, and if your number is equal to any of the numbers in the array, then the program should say: "YEES!!!".
The problem is, the program always says, what it should only if the input number is not equal to any number in the array...
So can please someone explain me why the if/else statement is failing?
I also wrote this in Code::Blocks if that changes something...
The code:
#include <iostream>
using namespace std;
int main(){
int numbers[11];
int input;
cout << "Type in a number: ";
cin >> input;
for (int i=0; i<11; i++){
numbers[i] = input +i;
}
for (int i=0; i<11; i++){
cout << numbers[i] <<endl;
}
while (true){
cout<<endl;
cout << "Type in a number:" <<endl;
cin.sync();
cin >> input;
if (input <= numbers[11] && input >= numbers[0])
cout << "YEES!!!" << endl;
else{
cout << "Number is out of range!" <<endl;
cout << "Please try again!" <<endl;
}
}
return 0;
}
Indexing starts with zero, so if you create an array with a size of N last index always will be N-1. In your case, the index of the last element is 10.
if (input <= numbers[10] && input >= numbers[0]) // accurate
The last element in your array should be 10, not 11 because you start at zero. Try doing
if (input <= numbers[10] && input >= numbers[0])
While the other answers clearly handle the indexing issue (array indexes start at 0 and the last index of an 11 element array is 10) there is a little bit of an XY problem happening here.
If you need to determine if an input number is within the range from 1 to 11, there is absolutely no need to use an array at all. You simply need to check that it's less than or equal to 11 and greater than or equal to 1.
if (input <= 11 && input >= 1) {
// ...
}
Your code is essentially trying to do this but storing the bottom of the range in numbers[0] and the top of the range in numbers[10] with the rest of the array being unused. If you want you could use two variables to store these limits.
The function is meant to read in two values, minimum and maximum. If either value is less than two an error message prints and both values are read in again.
I've tried making a separate while loops for min < 2 and max < 2. I've tried parenthesizing each condition on each side of the or operator. I've tried declaring two variables withing the function and setting one as equal to max and one as equal to min, and using those new variables in the loops.
void read_range(int & min, int & max)
{
cout << "Enter minimum and maximum: ";
cin >> min >> max;
while (max < 2 || min < 2); {
cout << "Error. Minimum and maximum must be at least 2." << endl;
cout << "Enter minimum and maximum: ";
cin >> min >> max;
}
while (max < min) {
cout << "Error. Minimum must be less than maximum." << endl;
cout << "Enter minimum and maximum: ";
cin >> min >> max;
}
}
the second while loop works fine.
There are 2 strange cases:
1. If either entered value is less than two, the program continues reading in values and must be manually stopped:
Enter minimum and maximum: 0 5
5 6
1 2
50 90
90 50
^Z
[23]+ Stopped
Even if both entered values are greater than two, the while loop still executes. The while loop does not execute again even if the re-entered value(s) is less than 2:
Enter minimum and maximum: 5 10
Error. Minimum and maximum must be at least 2.
Enter minimum and maximum: 1 2
(program continues running after this).
also, if the exact same values are re-entered then the while loop does not execute again:
Enter minimum and maximum: 5 10
Error. Minimum and maximum must be at least 2.
Enter minimum and maximum: 5 10
(program continues running after this)
Any help is appreciated.
Your 1st loop has an erroneous ; on it:
while (max < 2 || min < 2); {
It should be this instead:
while (max < 2 || min < 2) {
while (max < 2 || min < 2); {
should be like this
while (max < 2 || min < 2) {
OUTPUT:
Enter minimum and maximum: 1
1
Error. Minimum and maximum must be at least 2.
Enter minimum and maximum: 10
5
Error. Minimum must be less than maximum.
Enter minimum and maximum: 5
12
NO ERR
I am sure this will seem very novice to many on here but I am currently trying to learn C++ and have an in depth full understanding to apply my knowledge in the real world.
The Problem Description:
Write a program that graphically depicts an integer’s magnitude by using asterisk, creating a
histogram. Hint: The inner loop handles the printing of the asterisk and the outer loop handles
exciting until zero is entered. Make sure you don’t accept negative numbers.
Sample run:
Enter a positive integer (0 to quit): 5
*****
Enter a positive integer (0 to quit): 8
********
Enter a positive integer (0 to quit): -5
Enter a positive integer (0 to quit): -10
Enter a positive integer (0 to quit): 15
***************
Enter a positive integer (0 to quit): 0
Good Bye!
My Current Code (I know this isn't right by any means, but helps demonstrate my thinking, I know you need to use a nested loop to answer this properly.):
#include <iostream>
using namespace std;
int main()
{
int ast; //Number of asterisk wanted to be displayed
char asts='*'; //Actual display coressponding to asterisk
cout<<"Enter a positive integar, (0 to quit)"<<endl;
cin>>ast;
while(ast!=0)
{
if(ast>0) // Ensuring no negative integars are entered
{
asts=ast;
cout<<asts<<endl;
cout<<endl;
}
else //Display if negative or other invalid data is entered
cout<<"Invalid Data, negative values are not accepted, try a positive integar or 0 to quit"<<endl;
cout<<"Do you want to continue? If so, enter another integar (0 to quit)"<<endl;
cin>>ast;
}
cout<<"Thank you for using the program."<<endl;
return(0);
}
Thank you for the help ahead of time!
-Colin
The basic idea is (with pseudo-code):
get number of asterisks
while number is not zero:
if number is negative:
output error message
else:
do number times:
output *
output newline
get number of asterisks
Your nested loops there are while number is not zero and do number times.
However, one of the earliest skills you should learn as a developer is to properly assign tasks to specific pieces of code (methods, functions, libraries and so on). In particular, it's a good idea to modularise your code so that each piece has a well defined purpose, then build the "upper" layers out of those pieces.
To that end, this is how I would approach the problem. First, define the functions that would be useful in this case.
Start with getAsterCount() which is responsible for asking the user how many asterisks they want and verifying that it's valid (asking again and again, until it is). For example:
#include <iostream>
int getAsterCount() {
// Until we get valid response.
for(;;) {
int count;
// Get value, checking for error, forcing exit if so.
std::cout << "Enter the number of asterisks, zero to exit: ";
if (! (std::cin >> count)) {
std::cout << "*** ERROR: could not read number\n";
return 0;
}
// Any non-negative value is allaowed.
if (count >= 0) {
return count;
}
std::cout << "That was less than zero, try again.\n";
}
}
Once that's in place, you never have to worry again about the user providing invalid information for this program, since this function will capture it (and you can call it from anywhere, as shown in the main() function below.
Next, provide a function that will actually output the asterisks, based on the count you now have:
void outputAster(int count) {
// Simple loop for asterisks then new line.
for (int i = 0; i < count; ++i) {
std::cout << '*';
}
std::cout << '\n';
}
With that in hand, your main code becomes the conceptually much simpler:
int main() {
int count = getAsterCount();
while (count > 0) {
outputAster(count);
count = getAsterCount();
}
std::cout << "Thank you for using the program. Now get off my lawn.\n";
}
Right now you are trying to do:
asts=ast;
Which doesn't make much sense, as this will only assign the entered integer to asts.
To print the magnitude in * you need to loop from 0 to the inputted integer and print out an asterix every time:
for(int i = 0; i < ast; i++) {
std::cout << "*";
}
std::cout << "\n";
Output:
Enter a positive integar, (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
3
***
Do you want to continue? If so, enter another integar (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
0
I like a somewhat different approach, without a loop.
char asts[] = “*********\n”;
After checking that the input value is in range, just write out the tail of the string:
std::cout << (asts + 9 - ast);
My program executes just fine, but I have questions about how my while loop is set up.
I know the Boolean values for true and false are 1 and 0, respectively, but I'm not understanding why my output displays the even and odd numbers backwards (to my understanding, it's backwards). Simply put, I don't understand why if ( number % 2 == 0 ) would display that a number is even and when I change it to 1, it displays odd. I'm reading this line as, if (even number equals to false). I don't know if that's where I'm going wrong. What's the correct way to read this line?
The way I have my code set up now displays the numbers correctly, I'm just not understanding why. Can anyone help?
// Program indefinitely displays an even
// or odd number until a negative number
// is entered.
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Please enter a number: ";
cin >> number;
while ( number >= 0 )
{
if ( number % 2 == 0 )
{
cout << number << " is even \n";
cout << "Please enter a number: ";
cin >> number;
}
else
{
cout << number << " is odd \n";
cout << "Please enter a number: ";
cin >> number;
}
}
cout << "Thank you. \n";
return 0;
}
number % 2 is 0 if number divides 2 (i.e. is even), 1 if number is positive and does not divide 2 (i.e. is odd), and -1 if number is negative and does not divide 2 (i.e. is odd). (The last point must be the case from C++11 onwards).
So, since 0 == 0 is true, number % 2 == 0 is true if, and only if, number is even.
So you've written if ( number % 2 == 0 ) to trap all even cases, and the else traps the odd cases.
Testing if ( number % 2 == 1 ) is only a test for positive oddness, but older C++ standards allow this to be true for negative number.
The assignment requires three functions. The user enters digits 0-9 until they enter a 10, which stops input, and counts each number, then outputs how many of each number has been counted. It should only output if the user entered a number for it.
My only problem is that for every element in the array that the user doesn't use, Xcode counts it as a 0, so the final output has an abnormally large amount of zeros. Everything else works fine.
here is my code
#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
// define variables and initialize arrays
const int SIZE=100;
int numbers[SIZE], counter[10], input;
// for loop to set all counter elements to 0
for (int assign = 0; assign < 10; assign++)
{
counter[assign]=0;
}
// for loop to collect data
for (int index=0 ; input != 10 ; index++)
{
cout << "Enter a number 0-9, or 10 to terminate: ";
cin >> input;
// while loop to ensure input is 0-10
while (input < 0 || input > 10)
{
cout << "Invalid, please enter 0-9 or 10 to terminate: ";
cin >> input;
}
// if statements to sort input
if (input >= 0 && input <=9)
{
numbers[index] = input;
}
}
// call count function
count(numbers, SIZE, counter);
// call print function
print(counter);
return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
// for loop of counter
for (int index = 0 ; index < 10 ; index++)
{
// for loop of numbers
for (int tracker=0 ; tracker < SIZE ; tracker++)
{
// if statement to count each number
if (index == numbers[tracker])
{
counter[index]++;
}
}
}
return;
}
// print function
void print(int counter[])
{
// for loop to print each element
for (int index=0 ; index < 10 ; index++)
{
// if statement to only print numbers that were entered
if (counter[index] > 0)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
}
return;
}
What you're referring to as "XCode count[ing] as a 0" is actually just the uninitialized value. Given that you've decided to restrict the user's input to 0-9, an easy way of solving this dilemma would be, immediately after you size the array, to iterate through the array and set each value to -1.
Thereafter, when the user finishes their input, instead of just couting every single value, only print it with a conditional like the following:
if (counter[index] != -1)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
Note that this is the kind of use case that's much better suited to something like a linked list or a vector. As it stands, you're not doing anything to resize the array, or guard against overflow, so if the user attempts to enter more than 100 numbers, you'll run into serious problems.
First off, this isn't an answer to your exact question, but rather a suggestion on how to write your code in a much simpler form.
I'm not going to write this for you, as it's an assignment, and a rather simple one. Looks like you have a good handle on things as far as coding goes.
Consider this:
You need to allow the user to enter 0-10, and count all 0-9's. An array has indices, and a integer of array 10, would hold those 10 numbers you're counting by the indices. Now you just have some empty ints sitting around, so why not use them to count?
A code hint:
++numbers[input];
Second hint: Don't forget to initialize everything to zero.