Array auto-filling itself in C++ - c++

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;

Related

if/else statement with arrays is failing

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.

How to write a code where user can give the elements of the array?

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.

Issue with user-defined array in C++

I am trying to create an array using cin to define the size. While that seems to be working (based on what I currently have), none of the other stuff I want to do seems to be working.
For instance, I want to use a for loop to find the smallest int in the array since I will then need to compare it with all the other ints in the array, but no matter where I have the statement to return the smallest int, it does not do it.
What am I doing wrong?
#include <iostream>
using namespace std;
int main(){
int userSize;
cout << "Please define size of array: ";
cin >> userSize;
int *duckArray = new int[userSize];
for (int i = 0; i < userSize; i++) {
cout << "Please enter a number into the array: ";
cin >> duckArray[i];
}
int smallest = duckArray[0];
for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
cout << smallest << endl;
}
}
//cout << smallest << endl;
return 0;
}
Your code is working if you change this:
for (int i = 0; i < userSize; i++){
if (duckArray[i] < smallest){
smallest = duckArray[i];
}
}
cout << smallest << endl;
This will find and print the smallest number entered.
Arrays in C++ must have their size declared to the compiler at runtime. Other people are going to explain how you can buffer memory to simulate a dynamically allocating arrays. You can also have your Array at a given size and as the user adds and removes, you can reject inputs over the current size.
I highly recommend you look into Vectors. Vectors are much like ArrayLists in Java. They are a form of higher level collections that resize themselves as you add more elements to them.

Creating an array

write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}

Infinite loop without accepting input

I am writing a simple C++ Program which allocates dynamic memory to my Program and then deletes this memory. Here is my Program:
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
In the above program when I input the value of i (Number of inputs) equal to or less than 2 Billion than this program works as expected. However when I enter anything above 2 Billion like 3 Billion or higher, this program goes in an infinite loop without taking a number input in my for loop.
I am expecting this program to fail when I enter a very high value for i by saying it could not allocate the memory.
As per my understanding, I think when I enter a very high value of int i, I am going out of bound for integer data type but still in this case, it should take number input from me in for loop as I have a cin statement there instead of going in for loop or memory allocation should fail simply.
When I changed type of i from int to long then it works but I am curious to know for i of type int, why it goes in infinite loop instead of taking values when it sees cin in for loop?
I am running this program on Mac OS X and compiling it using g++ compiler.
1) You are trying assign to int value bigger than 2147483647, which is usually maximum value for this type.
Generally, if you want to handle such a large numbers, you should use long long int (or something from <cstdint> for better portability).
2) You don't clear state of cin after it fails.
The code bollow generate infinite loop:
int i = 0;
while (i <= 0)
{
std::cout << "Enter a number greater than 10..." << std::endl;
std::cin >> i;
}
You can solve it this way:
int i = 0;
while (i <= 0)
{
std::cout << "Enter a number greater than 10..." << std::endl;
if (!(std::cin >> i))
{
std::cin.clear(); // Clear error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Remove incorrect data from buffer
}
}
3) You are trying to create a really big array. You need a few GiB of
contiguous memory to this. Even if you succeed allocate the array, it is still a design issue. You should use many of smaller arrays or use/create a suitable container.
The maximum value of a 32 bit signed integer is 2^31-1, namely 2147483647.
Now, if you assign a higher value to an Int variable the behaviour is quite unexpected, try and see what i actually contains.
BTW, what do you mean by "infinite loop"? Does the program crash or does it never end executing?