Array will not fill backwards in C++ - c++

I am attempting to fill an array backwards from 20 to 0 but whenever I print it out it still prints out forwards. For instance I want to put in 1,2,3,4,5 and have it come out as 5,4,3,2,1.
I have attempted to do a for loop that counts backwards from 20 to 0 but when i print it it is still coming out incorrect. Any help?
int temp;
for (int i = 20; i > 0; i--)
{
cout << "Please enter the next number. Use a -1 to indicate you are done: ";
cin >> temp;
while(temp > 9 || temp < -2)
{
cout << "You may only put numbers in 0 - 9 or -1 to exit. Please enter another number: ";
cin >> temp;
}
arr1[i] = temp;
cout << arr1[i];
}
for (int i = 21; i > 0; i--)
{
cout << arr1[i];

What's the size of your array?
Assume that the size is 21 (indexes from 0 to 20).
First of all please note that your first loop will never populate the array at index 0 (something like this arr1[0] = temp will never be executed inside your first loop).
If you want to avoid this behavior you should write your first for loop like this:
for (int i = 20; i >= 0; i--){...}.
The second for loop has some issues:
You are traversing the array backwards while you want to do the opposite.
The loop starts from an index out of bound (21).
The loop may print some undefined values (You should remember the index of the last added value).
I suggest you to use other data structures like a Stack but if you want to use an array you can edit your code as follows:
int i;
for (i = 20; i >= 0; i--){...}
for (i; i <= 20; ++i) { cout << arr1[i]; }
If you don't want to declare int i; outside of the loop you can do something like that:
int lastAdded;
for (int i = 20; i >= 0; i--){
...
lastAdded = i;
}
for (int i = lastAdded; i <= 20; i++) { cout << arr1[i]; }
Edit: Note that neither your code nor mine stops asking for a new value after the insertion of a -1.
If you want to achieve this behavior you should use a while loop instead of the first for loop and check for the exit condition.

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;

What can I use to stop a loop instead of 'return 0'?

so I made a simple loop that finds out if an array has the elements with the values of 0 and 1.
if the loop indeed finds 0 or 1 inside of the array, it will say "YES", otherwise "NO".
yes, the program works just fine, but at the end of the program it prints out "YES" or "NO" as many times as i put cin>>dim to.
for example if dim which means (dimension[of the array]) is 5 it's going to print either "YESYESYESYESYES" or "NONONONONO"
I have to use return 0 in order to make it print it out like once, but I feel like this is not the right way to do it. Please help me with this. thanks!
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, dim, v[100];
cin>>dim;
for(i=0;i<dim;i++)
cin>>v[i];
for(i=0;i<dim;i++)
if(v[i]==0 || v[i]==1){
cout<<"YES"; return 0;}
else{
cout<<"NO"; return 0;}
return 0;
}
The break statement can be used to break out of loops. The example from cppreference:
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 5; k++) { //only this loop is affected by break
if (k == 2) break;
std::cout << j << k << " ";
}
}
As the comment suggests, break only breaks the innermost loop.
In your code you always exit from the loop on the very first iteration, hence you do not need the loop in the first place. This will have the same output as your code:
int main() {
int i, dim, v[100];
cin >> dim;
for(i=0; i < dim; i++)
cin >> v[i];
if(v[0] == 0 || v[0] == 1) {
cout << "YES";
} else {
cout << "NO";
}
}
After reading the question again...
I made a simple loop that finds out if an array has the elements with the values of 0 and 1
If you exit the loop after checking the first element then you only check the first element. If you want to see if an array contains only 1 or 0 or it contains at least one element which is 0 or 1 (not 100% clear which one you want), then you rather need this:
bool only_zero_or_one = true;
bool one_zero_or_one = false;
for (int i = 0; i < dim; ++i) {
zero_or_one = ( v[i] == 0 | v[i] == 1);
only_zero_or_one = zero_or_one && only_zero_or_one;
one_zero_or_one = zero_or_one || one_zero_or_one;
}
Only for one_zero_or_one you can break the loop once zero_or_one == true.
Moreover, you should rather use a std::vector. In your code, if the user enters a dim which is greater than 100 you write beyond the bounds of v. This can be avoided easily:
size_t dim;
std::cin >> dim;
// construct vector with dim elements
std::vector v(dim);
// read elements
for (size_t i=0; i < v.size(); ++i) std::cin >> v[i];
// .. or use range based for loop
for (auto& e : v) std::cin >> e;
but I feel like this is not the right way to do it
Returning is an entirely right way to break out from a loop.
Another right way is the break statement, which jumps to after the loop.
Even better, you can actually check if v[i]==0 or 1 inside the input for loop immediately after taking input and set a flag to true. Depending on requirement, you can either break or wait until the entire input is read and then come out and check for flag==true and then print "YES" and print "NO" if flag==false.
This will save you running the loop again to check for 0 or 1.

Arrays Outputting the Wrong Numbers in C++

My goal is to have a player input a bunch of numbers for an array then that array is written into a text file. Another part of it is to be able to receive a bunch of numbers from a text file and put them into a sorted array of highest to lowest then output that array. But for some reason, I'm getting a lot of errors, ones that i feel like with some research I can fix. Unfortunately, there is one very confusing situation where I test to make sure the unsorted array is correct by outputting each element of the array. This is not a part of the final program but a test for now. I have a for loop that does so and it works perfectly, outputting each number as expected. Then in the next for loop, the exact same thing is supposed to happen but the numbers being outputted are all messed up. I do not understand how. Code below
void readFile(string fName) {
string fileName = fName + ".txt";
ifstream myFile(fileName);
char c;
string num;
int count = 0;
// Bring the array from file to int array
while (!myFile.eof()) {
myFile.get(c);
if (isspace(c) && num != "") {
int n = stoi(num);
intArray[count] = n;
count++;
num = "";
continue;
}
if (!myFile.eof()) {
num += c;
}
}
for (int i = 0; i < 10; i++) {
cout << intArray[i] << endl;
}
// Sort the array higest to lowest
for (int i = 0; i < 10; i++) {
cout << intArray[i] << " ";
for (int j = 9; j >= i; j--) {
if (j == 0) {
continue;
}
if (intArray[j] > intArray[j - 1]) {
int temp = arr[j];
intArray[j] = intArray[j - 1];
intArray[j - 1] = temp;
}
}
cout << endl;
}
}
sorry about the formatting above, its being weird so imagine the code is within the function.
This is what this outputs:
1
2
3
4
5
6
7
8
99
234
1
1
1
1
1
1
1
1
1
1
The numbers before the series of 1's is the actual array, the 1's is what is apparently the array according the cout in the last section of code where it says cout << intArray[i]
Your array does appear to be sorted. The reason for all the ones being printed is due to the location of the cout << within the outer loop.
Consider what your array looks like after your first iteration through the inner loop:
234,1,2,3,4,5,6,7,8,99
Now consider that you've incremented i to 1 in the outer loop. When you index your array intArray[i], the ith element is now 1 because you correctly moved it there. Each time, you're moving your smaller elements up one position in the array, then indexing to the position where the 1 is.
Don't try to print the sorted array while you're sorting it. Instead loop over it and print it after the sort.

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