#include <iostream>
using namespace std;
int main()
{
int n;
bool error;
do
{
cout << "How many numbers would you like to put in this sequence? "<< endl;
cin >> n;
error = cin.fail() || cin.peek() != '\n' || (n < 0);
if (error)
{
cout << "Please input again" << endl;
}
cin.clear();
cin.ignore(999,'\n');
}while(error);
int a[n];
cout << "Please input the numbers in your sequence." << endl;
for(int i = 0; i < n; i++)
{
do
{
cin >> a[i];
error = cin.fail() || cin.peek() != '\n';
if (error)
{
cout << "Please input again" << endl;
}
cin.clear();
cin.ignore(999,'\n');
}while(error);
}
for(int i=0; i<n; i++)
{
if (a[i]<a[i+1])
{
cout << "The sequence is monotonically increasing." << endl;
}
else
{
cout << "The sequence is not monotonically increasing." << endl;
}
}
}
Hello guys, I want to check if this sequence (integer numbers) is monotonically increasing or not.
And I do not know which way I should use, so I just choose to use the 'For' loop, which it just compare two numbers each time, which its not comparing all numbers together.
Could you please help me?
Thanks ::>
Your initial attempt using the for loop is on the right track. The key here to fix the message being printed multiple times is to move the print statement (cout << ...) outside the loop. Now, you may ask, "How do I do that?" The proper way to approach it is to negate the condition: how do you know that a sequence is not monotonically increasing? (Based on your code, I will assume you are looking for a strictly increasing sequence.)
You know a sequence is not monotonically increasing if the current term in the sequence is greater than or equal to the next term in the sequence. Once you find one such pair of terms, you immediately know the sequence does not satisfy that property and can exit the loop early. Thus, our tactic to solving the problem is to first assume the condition is true, check if the condition is ever not true for any two elements, and then to check the condition again and print the result.
Thus, your final for loop should look like this:
bool is_increasing = true; // Begin by assuming the condition is true.
for (int i = 0; i < n - 1; ++i) { // Note the condition. More info below.
if (a[i] >= a[i + 1]) { // Here we check if the condition is NOT met.
is_increasing = false;
break; // This exits the loop. We don't have to keep going because
// of the way monotonically increasing is defined.
}
}
// Now we check the condition and present the result.
if (is_increasing) {
cout << "The sequence is monotonically increasing." << endl;
}
else {
cout << "The sequence is not monotonically increasing." << endl;
}
There is another issue with your code. You want to be very careful about not attempting to read past the end of an array. If we trace over the for loop you wrote, what happens when i = n - 1? Clearly, n - 1 < n, so the body of the for loop runs. Then we run into the if statement: if a[i] < a[i + 1]. Okay, the first part a[i] is good because that is really asking for a[n - 1] which is legal, but what about a[i + 1]? Whoops, if n is supposed to be size of the array, then a[n] does not exist! (Remember, arrays are zero-based!) Off-by-one errors are ubiquitous in programming, but if you take the time to trace through the code, you can catch most of them. (Notice how I in the above fixed the issue by changing the loop condition.)
Edit:
As pointed out by paddy in the comments, you do not want to use an array here because that is nonstandard c++. Instead, you want to use the std::vector (or just vector if you are using namespace std) class. Vectors are very similar to arrays, but they can grow and shrink as needed at runtime. The syntax for using them is also a little different. An example of how to use vector follows:
std::vector<int> a {}; // This constructs an empty vector of ints.
a.push_back(1); // This puts 1 at the end of the vector. In this case,
// you can access this number at location 0.
a.push_back(2); // This puts 2 at the end.
cout << print(a.at(0)) << endl; // This will print 1.
cout << print(a.at(1)) << endl; // This will print 2.
You can also use [] like with arrays to access existing elements of the vector, but using .at may be preferable because you get bounds checking.
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.
I wanted to write a code where user will give input the element of the array and then the elements will be print as an array. Here is my code but the code do not give the array as output.
#include<iostream>
using namespace std;
int main(){
int arr[100] , size , i , num ; //Here we are defining the maximum size of array is 100. So user can choose the size of array by him/her but cannot choose more than 100
cout << "Enter the size of array (Maximum array size you can take is 100) : ";
cin >> size;
if (size > 100)
{
cout << "You cannot take the size more than 100" << endl;
}else{
cout << "Inter the elements using space : ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
cout << "Enter data you want to insert : ";
cin >> num;
for (int i = size - 1 ; i >= 0 ; i--)
{
arr[i+1] = arr[i];
}
arr[0] = num;
size++;
}
cout << arr[i] << endl;
return 0;
}
Your question isn't entirely clear, but I see two basic problems.
First, you define variable i at the top of your code. That's fine, although there are arguments for variable names being longer than a single character. Think about searching for uses of that variable -- you're going to get it in all sorts of places that have nothing to do with the variable. while has an i. if has an i. Be that as it may.
But here's a real problem. You have some for loops like this:
for (int i = 0; ....)
There's nothing wrong with that, not exactly. It works. HOWEVER, it's considered bad form to reuse a variable inside an inner block that matches a variable from an outer block. It's legal, but it's a common source of bugs. I recommend you don't do it.
Then, at the bottom, you do this:
cout << arr[i] << endl;
At this point, we're back to the original variable i that you declare at the top. But you never actually initialize it, so it's some random value. And you're not doing any sort of loop.
I suspect if you wrap this inside another of your for-loops, you'd get the results you want.
And get rid of declaring i at the top.
void getPlayerRolls(int RollValues[], int& AttemptCount) {
int i = 0;
int FrameNumber = 0;
int RollNumber = 0;
while(RollValues[i] != -1) {
FrameNumber++;
cout << "Frame # " << FrameNumber << endl;
cout << "Roll #1 "
<< " ";
cin >> RollValues[i];
i++;
cout << "Roll #2 "
<< " ";
cin >> RollValues[i];
i++;
cout << endl;
}
}
My expectation is that when a -1 is entered for one of the roll values that the program terminates. I tried to create a while loop that works with an array but I am having trouble determining how to do this.
I removed lines from your function that are not part of the problem, but maybe this will clarify:
while(RollValues[i] != -1) {
cin >> RollValues[i];
i++;
cin >> RollValues[i];
i++;
i++;
}
What is the value of i by the time the loop condition variable is tested?
The first rollvalue entered is read into some place in the array, but then i is incremented, so if you read back from RollValues[i] you read from a different place in memory! Not only that, you never look at the first roll before accepting the second. And then you increment i yet again. By the time you're back at the top of the loop, i has been advanced 3 times, and neither of the entered rolls is ever tested.
You have other issues too, such as
receiving an array has no "size" information associated, so you do not now how big of an array the caller provided. Your code therefore cannot protect against overruning the memory.
in your while loop, you advance 3 times per iteration, so even if your loop condition checks for boundary cases, you still could have walked off the end of the array before getting back to the top of the loop.
Therefore, I suggest the following:
1) pass in the size of your array into your function, or use a safer data structure, such as std::array or std::vector
2) only process a single roll per loop, and check that you're within bounds before advancing.
3) don't advance your index variable until you're done looking at the value in that place that it refers.
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.
I'm learning C++, doing some easy examples, and found this odd behavior.
When filling the elements of an array of integers, if any of the elements is set to something greater than 2147483647 (which I believe is the maximum integer value?), the rest of the elements in the array are set to that exact number, every one of them.
I understand that if one element goes beyond its type limit, the compiler caps it to that limit, but I can't get why it does the same thing with the other items, without even asking the user to fill them.
Here's a simple test I've run:
#include <iostream>
using namespace std;
int main()
{
int test[5];
int num = 0;
for (int i=0; i<5; i++)
{
cout << "Enter the number in position " << i << endl;
cin >> num;
test[i] = num;
}
cout << "Values in the array: " <<endl;
for (int i=0; i<5; i++)
cout << test[i] << endl;
}
Thanks for reading, commenting, and helping!
Documentation of std::istream::operator>>:
If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.
Once the failbit flag is set, subsequent input operations will have no effect, meaning that aux is left unchanged.
If you want to continue extracting items after conversion failure, you need to clear failbit:
cin.clear();
cin >> aux;