Comparing elements in an array? - c++

as the title says I'm attempting to compare elements in an array. My intent is to have the user enter 3 integers into the program, thereafter it should increment through this array comparing the the 1st number to the 2nd, and so forth and swapping the element's from order of lowest to highest.
My issue currently is that it will swap the first and second elements but the third causes an integer overflow due to me comparing and assigning an integer in an index higher than the initialized array can hold.
I'm currently drawing a blank as to how I could still compare these numbers in this manner without causing it to overflow.
A hint or perhaps a whole different perspective would be appreciated.
#include "E:/My Documents/Visual Studio 2017/std_lib_facilities.h"
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
//This should swap the elements from smallest to greatest
for (int i = 0; i = 3; i++)
{
if (numbersArray[i] > numbersArray[i+1])
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
//swap(numbersArray[i], numbersArray[++i]);
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
keep_window_open();
return 0;
}

You will need to modify this to suit your needs, but this should get you on the right track. One important thing to investigate is how you decided to sort the elements. Your sorting needs to be looped, otherwise, you won't necessarily sort the entire array (depending on your inputs).
#include <iostream>
using namespace std;
int main()
{
cout << "Enter three integers: \n";
int numbersArray[3];
int temp = 0; //This lets us hold our integers temporarily so we can swap them around in the array
//This enters integers as elements in the array
for (int i = 0; i < 3; i++)
{
cin >> numbersArray[i];
}
for(int loop = 0; loop <3; loop++){
//This should swap the elements from smallest to greatest
for (int i = 0; i < 2; i++)
{
if (numbersArray[i] > numbersArray[i+1]){
temp = numbersArray[i];
numbersArray[i] = numbersArray[i+1];
numbersArray[i+1] = temp;
}
//swap(numbersArray[i], numbersArray[++i]);
}
}
//This prints the index's containing the elements in the array
for (int i = 0; i < 3; i++)
{
cout << numbersArray[i] << ' ';
}
cout << endl;
return 0;
}

Related

execution order for cout in C++

c++
When printing to console, if function execution is sequential it would seem logical the ordered array would be printed after calling insertionSort, however order list does not print until next loop. Any help would be appreciated.
#include <stdio.h>
#include <iostream>
#include <array>
using namespace std;
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = i - 1;
while (i > 0 && array[key] > array[i] ) {
int tmp = array[i];
array[i] = array[key];
array[key] = tmp;
i -= 1;
key -= 1;
}
}
}
const int ARRAY_MAXSIZE = 5;
int main(void) {
int *array = (int*)calloc(ARRAY_MAXSIZE, sizeof(int));
int input;
cout << "Enter 5 digits\n";
for (int size=0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
insertionSort(array, size);
for (int j=0; j <= size; j++) {
cout << array[j];
}
cout << '\n';
}
}
Console Entry
This is a classic off-by-one error. Your insertionSort expects you to pass the number of elements to sort via the parameter size. But your main loop is always holding a value that is one less than the size immediately after adding an element.
I want to say that bugs like this are easily discovered by stepping through your program's execution with a debugger. If you don't know how to use a debugger, start learning now. It is one of the most important tools used by developers.
Anyway, the quick fix is to change your function call to:
insertionSort(array, size + 1);
However, as Paul McKenzie pointed out in comments, it's a bit crazy to do this every time you add a new element because your function sorts an entire unsorted array. Your array is always nearly sorted except for the last element. You only need to call that function once after your input loop is done:
// Read unsorted data
for (int size = 0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
}
// Sort everything
insertionSort(array, ARRAY_MAXSIZE);
// Output
for (int j = 0; j < ARRAY_MAXSIZE; j++) {
cout << array[j];
}
cout << '\n';
But if you want every insertion to result in a sorted array, you can "slide" each new value into place after inserting it. It's similar to a single iteration of your insertion-sort:
// Sort the last element into the correct position
for (int i = size; i >= 1 && array[i] > array[i - 1]; i--)
{
std::swap(array[i], array[i - 1]);
}
Even better, you don't need to swap all those values. You simply read the value, then shuffle the array contents over to make room, then stick it in the right spot:
// Read next value
cin >> input;
// Shuffle elements to make room for new value
int newPos = size;
while (newPos > 0 && array[newPos - 1] > input) {
array[newPos] - array[newPos - 1];
newPos--;
}
// Add the new value
array[newPos] = input;

C++ Shuffle Deck Issue [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 4 years ago.
I am having trouble with shuffling a deck of cards in C++.
I have a deck of cards class. Within the class I have a vector of objects, which are the cards within the deck, and I am trying to shuffle the elements within the vector to shuffle the cards. However, the function I wrote to do it appears to be just shifting everything over every iteration instead of swapping it with another random element within the vector. I'm sure its something really simple and stupid that I am missing, but I just haven't been able to figure it out yet. Any help would be greatly appreciated.
Thanks.
void shuffle(int seed = 0)
{
for (int i = 0; i < 100; i += 1)
{
for (unsigned int i = 0; i < deck.size(); i++)
{
card *swap = deck[i];
srand(time(NULL) + seed);
int temp = rand() % 52;
deck[i] = deck[temp];
deck[temp] = swap;
}
cout << "shuffled deck: ";
for (unsigned int i = 0; i < deck.size(); i++)
cout << deck[i]->compare() << " ";
cout << endl;
}
}
This is being called within a probability function I made, inside a loop. The seed for the shuffle function is the iteration of the loop.
This is a sample of part of the output in one iteration
Initialize your RNG just once, for example in your main() function
srand(time(NULL));
Then one of simplest methods of shuffling is just swap each item from the end to the beginning with a random element from those preceding it. Note the item to swap can be the same to be swapped – this way the item can also stay where it already is.
void shuffle()
{
for (int i = 0; i < 100; i ++)
{
for (unsigned int n = deck.size(); n > 1; --n)
{
unsigned swapPosition = rand() % n;
card *swap = deck[n-1];
deck[n-1] = deck[swapPosition];
deck[swapPosition] = swap;
}
cout << "shuffled deck: ";
for (unsigned int n = 0; n < deck.size(); n++)
cout << deck[n]->compare() << " ";
cout << endl;
}
}

Zeros when printing out an array which is declared on the heap. C++

I want to make a program that lets the user insert some numbers to the array and the print it out afterwards. Problem is when I try to do that (lets say the size of my array is 100) then:
What it should do: Inserted- 1,2,3,4,5 -> should print 1,2,3,4,5
But instead it prints -> 1,2,3,4,5,0,0,0,0,0,0, .... up to the size of my array.
Is there any way I can get rid of those zeros?
Code:
int SIZE = 100;
int main()
{
int *numbers;
numbers = new int[SIZE];
int numOfElements = 0;
int i = 0;
cout << "Insert some numbers (! to end): ";
while((numbers[i] != '!') && (i < SIZE)){
cin >> numbers[i];
numOfElements++;
i++;
}
for(int i = 0; i < numOfElements; i++){
cout << numbers[i] << " ";
}
delete [] numbers;
return 0;
}
You increase numOfElements no matter what the user types. Simply do this instead:
if(isdigit(numbers[i]))
{
numOfElements++;
}
This will count digits, not characters. It may of course still be too crude if you want the user to input numbers with multiple digits.
Get numOfElements entered from user beforehand. For example
int main() {
int n;
cin >> n;
int * a = new int[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
for (int i = 0; i < n; ++i)
cout << a[i] << endl;
delete[] a;
}
Input
4
10 20 30 40
Output
10 20 30 40
Since you declared array size, all indices will be zeros.
User input changes only the first x indices from zero to the value entered (left to right).
All other indices remains 0.
If you want to output only integers different from 0 (user input) you can do something like that:
for(auto x : numbers){
if(x!=0)cout<<x<<" ";
}
You can use vector and push_back the values from user input to get exactly the
size you need without zeros, then you can use this simple code:
for(auto x : vectorName)cout<<x<<" ";
Previous solutions using a counter is fine.
otherwise you can (in a while... or similar)
read values in a "temp" var
add if temp non zero
exit loop if counter >= SIZE-1 (you reach max slots)
increment counter
when You will print, form 0 to counter, you will get only non zero values.

c++ bubble sort returning weird values

I'm trying to use a bubble sort to sort an array of 10 numbers. The program asks for 10 numbers from the user then outputs the unsorted array. This part works fine. It then runs a bubble sort and outputs the sorted array. In my tests I only entered positive integers, however the first value in the sorted array is always a really small number expressed like "2.6812368e-317" or something similar. The rest of the values in the array then appear after that number sorted as they should be. After the sorted array displays Windows then comes up with an error saying the program has stopped working.
My code is as follows:
int main(int argc, char** argv) {
double arrSort[10];// declare array to store numbers to be sorted
cout << "Please enter 10 numbers to be sorted" << endl;
// ask for values from user and input them in array
for (int i = 0; i < 10; i++)
{
cin >> arrSort[i];
}
// display unsorted array
cout << "Unsorted Array: " << endl;
for (int i = 0; i < 10; i++)
{
if (i < 9)
cout << arrSort[i] << ", ";
else
cout << arrSort[i] << endl;
}
bool changed = true; // variable to store whether a change has been made
double temp; // variable to temporarily store a value while swapping
//start looping the array
do
{
changed = false; // change to false so that if no changes are made to array the loop exits
for (int i = 0; i < 10; i++) // start loop within array to check values
{
if (arrSort[i] > arrSort[i + 1]) // check if current index is greater than next index
{
// swap values
temp = arrSort[i]; // store current index in temp variable
arrSort[i] = arrSort[i + 1]; // assign next index to current index
arrSort[i + 1] = temp; // assign temp value to next index
changed = true; // set changed to true to run another loop
}
}
}while (changed); // if array was changed loop through again, if not changed exit loop
// output results of sorted array
cout << "Sorted Array: " << endl;
for (int i = 0; i < 10; i++)
{
if (i < 9)
cout << arrSort[i] << ", ";
else
cout << arrSort[i] << endl;
}
return 0;
}
Here is a screenshot of a test run of the program:
Sorted Array output
for (int i = 0; i < 10; i++) // <-- here's problem.
{
if (arrSort[i] > arrSort[i + 1])
{
// swap values
}
}
i variable should be less than 9 not 10. As you can see in if statement you are checking arrSort[i + 1], so in last element you are checking number which is out of your table range (arrSort[10] doesn't exist). I'm not able to check it right now, but I guess it's the problem.
I think the problem is here:
if (arrSort[i] > arrSort[i + 1])
When
i=9
Your array have 10 elements and you try to compare
arrSort[9] > arrSort[9+1]
And
arrSort[10]
Does not exist

C++ Reverse Polish Notation Stack

I am working on a project which requires me to accept a string written in reverse polish notation and evaluate it using a stack. I am supposed to go through the string and if the element is a number, I keep going through the string until I reach a space, and I convert that section of the string to an integer using atoi. I then push that integer onto the stack. My code for this works, however, I am not sure how to continue to the next number after the space. This is the for loop I have so far:
for (unsigned int i = 0; i < a.size(); i++)
{
int b;
char c[a.size()];
while (isdigit(a[i]))
{
cout << a[i] << endl;
c[i] = a[i];
b = atoi(c);
i++;
}
cout << b << endl;
stack.push(b);
}
This always pushes the first integer onto the stack, even if there are more after a space. What would I need to add to continue pushing integers onto the stack after a space? Thanks for your help.
Your problem is here:
c[i] = a[i];
When reading the second integer you will use the current i and not write the digits at the start of your array c. The call to atoi(c) will see the first integer which was not overwriten and return that value.
You should use a second index to put digits in the c array and reset this second index after you pushed an integer on the stack.
Here is an example (not tested):
unsigned j = 0;
char c[a.size()+1];
for (unsigned int i = 0; i < a.size(); i++)
{
int b;
while (isdigit(a[i]))
{
cout << a[i] << endl;
c[j] = a[i];
j++;
i++;
}
c[i] = '\0';
b = atoi(c);
cout << b << endl;
stack.push(b);
j = 0;
}
I assume this is some homework and you must work the way you do. In idiomatic C++ one would use a stringstream for this work.
#include <sstream>
int b;
std::stringstream buffer(a);
while(buffer >> b) {
stack.push(b);
}