2

I am a beginner in c++. I have spent hours trying to figure out loops and the structure of arrays.

GOAL: take a user input and set it to the size allocation of an array. Take another user input and add values to the array. Display an output of the array, backwards. [last index.....first ind`ex]

I have read everywhere and in my textbook that spaces are not counted by cin >> but my code shows me spaces. I have tried testing whether my loop is correctly adding the input values to the loop. Maybe my output loop is wrong? I can't figure out what the issue is.

These are the example outputs I am getting. If I have an array of 5 elements, why did only 3 items output? In the backwards output loop, I am not seeing all of my array items, and it repeats 3.

I have a lot of comments to keep track of my thought process. Thanks for taking a look and helping me out!!

Example Test Case of Mine:

5

1 2 3 4 5

print array 

123

backwards array 
3 3 2 1 

...Program finished with exit code 0
Press ENTER to exit console.

Expected Example: (user enters)5

(user enters)1 2 3 4 5 (hit enter)

Expected Output:

5 4 3 2 1

#include <iostream>
#include <string>
using namespace std;

int main() {
    
  //write your solution here
  //define variables
  //int sizeofArray;
  
  //need to account for spaces
  //no you don't they are accounte for
  //int array[sizeofArray];
  int num;
  
  int sizeofArray;
  int array[sizeofArray];
  
  cin >> sizeofArray;

  //think about 2 for loops
  
  //store values to the array
  for (int i=0; i < sizeofArray; ++i) {
      
      //for each index, populate the array
      cin >> array[i];
  }//end of populate array
  
  cout << "\nprint array \n";
  
  //print the array
  for (int k=0; k < (sizeofArray); k++) {
      cout << array[k];
  }//end of print array
  
    
  //output values of the arrray backwards
  cout << "\nbackwards array \n";
  
  for (int j=sizeofArray; j >=0; --j) {
      cout << array[j] << " ";
  }
  
  
                   
  return 0;
}//end of main
  • tried to print out the array to see what the system sees. I get an incorrect output
  • tried to learn and use the right increment/decrement syntax, ++i or i++
  • tried to account for spaces by adding a multiplier of 2 to "sizeofArray"
user17732522
  • 53,019
  • 2
  • 56
  • 105
Labbayk
  • 37
  • 4
  • 3
    You have at least one serious error. You declare `int sizeof array;`, but never initialize it to any value, and then use it on the following line in `int array[sizeofArray]; Using an uninitialized variable produces undefined behavior, which means basically anything can happen. **Never** use a variable without initializing it first. And that means **NEVER**. Turn on all compiler warnings, and don't ignore the messages that are generated. The compiler will tell you about mistakes like this one. – Ken White Jun 04 '23 at 02:28
  • 2
    Even if you exchange the lines `int array[sizeofArray];` and `cin >> sizeofArray;`, then your code still is not valid in standard C++. This is because standard C++ does not support [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array). However, some compilers may support them as an extension to the language. In C++, it is generally recommended to use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead, as that is supported by all compilers. – Andreas Wenzel Jun 04 '23 at 02:37
  • Please don't mark your question as resolved by adding "Fixed" or similar to its title. Also, please don't edit answers into your question. You can instead answer your own question by using the "Your Answer" field and "Post Your Answer" button at the end of this page. Also, if an answer solved your problem, you can "accept" it to indicate that your problem is resolved. See https://stackoverflow.com/help/someone-answers. – user17732522 Jun 04 '23 at 23:50

3 Answers3

5
int sizeofArray;

This declares an int named sizeofArray. This int is not initialized, so it contains random garbage.

int array[sizeofArray];

There are two reasons why this is wrong. This is not valid C++. In C++ the size of all arrays is a fixed constant specified at compile time. That's how C++ arrays work. int a[4] is a valid array declaration. The size of this array is 4. It is specified at compile-time. You cannot specify the size of an array by a non-constant expression. Your C++ compiler accepts this construct only as a non-standard extension to the C++ language, but even assuming that you're willing to use this nonstandard C++, this will fail for another reason:

cin >> sizeofArray;

This now reads sizeofArray from cin. You obviously expect that this will result in the previously-declared array to have this size. This is not going to happen (that's the second thing that was wrong with the array declaration). The array was declared using an uninitialized variable, as its size, which is undefined behavior.

C++ does not work this way, C++ does not work like a spreadsheet. If you declare an array whose size is specified by a variable (using a non-standard C++ extension), and then change the value of the variable, this would not retroactively change the size of the previously-declared array. C++ code is executed a statement at a time: you declare something, and it's declared; you declare something else, that something else is declared; you change the value of some variable, and it's changed; and so on. If, previously, a different variable was set based on the contents of this variable, then the previously-set variable's value does not automatically change just because this variable now has a different value. This is how spreadsheets work, not C++.

You must correct all these issues in order to fix your program. If you wish to continue to use non-standard C++ you can cin >> sizeofArray before declaring the array.

Or, if you actually wish to learn how to do this, correctly, using standard C++, you can keep reading your C++ textbook until you get to a description and an explanation of what std::vector is, and how it works, and then take that approach.

for (int j=sizeofArray; j >=0; --j) {
      cout << array[j] << " ";
}

One more logical flaw. Let's pretend that sizeofArray is 3. There are three values in the array. They are array[0], array[1], and array[2].

If you work out, on paper and pencil, what the above does, it attempts to print array[3] followed by array[2], then array[1], and the finally array[0]. It should be rather obvious that there is no array[3], so this loop's logic also needs to be adjusted. Note that the first value that must be printed, the first iteration of the loop, should be one less than the array's size. You can do that simply by decrementing the index variable, j--, before printing the value of each array element, rather than after (as part of the loop's iteration).

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Thank you for telling me the why and walking me through my wrong assumptions. I am learning with Murachs training and reference for c++. He does give snippets of code instead of entire concepts at once so I definitely will continue reading on. Thanks for helping me see the difference between the index position and the size of the array and why I cant interchange them in the logic. Tonight I will look for a good desktop ide for c++. I am using the onlinegdb c++ compiler. – Labbayk Jun 04 '23 at 04:01
  • I do not see Murach's C++ textbook listed in [Stackoverflow's canonical list of C++ textbooks](https://stackoverflow.com/questions/388242/). This is likely to be one of the low-quality textbooks mentioned in that answer's introduction. – Sam Varshavchik Jun 04 '23 at 11:02
  • What free c++ compiler do you recommend? I want to get away from the online compiler. I use Netbeans for php, java, javascript, and html. I have the latest JDK (version 17) and the c++ plug in doesn't work past version 8 or 11. Next, I tried to install Homebrew to get a compiler for Visual Studio Code. I got error 404 and a connection issue to the git. – Labbayk Jun 04 '23 at 22:13
  • Every Linux distribution comes packaged with the latest version of gcc. – Sam Varshavchik Jun 04 '23 at 22:57
  • Eh. I found a tool called Eclipse where I can compile c++. Setting up a whole operating system to access its tools to develop introductory code is over kill for me. Murach texts might be assumed as low quality but I'm starting somewhere to learn. Undergrad cs programs include interpersonal communication as a requirement. Threads like this that sound like someone is talking to a wall or giving a dull speech in response to a question, plague the IT engineering field. In the mean time, I have been saying thank you and engaging your responses. – Labbayk Jun 05 '23 at 11:44
  • Unfortunately, C++ is a 2nd class citizen on MS Windows. Microsoft prefers everyone to use C#, a technology they fully control. Although historically MS has provided adequate support and resources for their C++ it always plays 2nd fiddle on Windows. Anyone who's serious about learning C++ will learn on Linux, where it is a 1st class citizen, with gcc often adding support for the latest C++ standard and features before MS gets around to it. – Sam Varshavchik Jun 05 '23 at 11:56
  • P.S. Eclipse is ***not*** a C++ compiler, it's just an editor. – Sam Varshavchik Jun 05 '23 at 12:02
0

When you want to create an array of a size specified during the runtime, you have to use dynamic allocation (on the heap). You can search for dynamic allocation on the internet.

You can also consider using std::vector for this task since it is doing practically the same thing.

I remade your code using dynamically allocated array of ints. It is worth noting that every time you use dynamic allocation, you have to free the memory to prevent memory leaks using delete or delete[] with arrays.

I have also used std::reverse to simplify the code. It reverses the array, so you do not have to print it in reversed order. However, if you do not want to change the array, you can use the loop from your program.

#include <iostream>
#include <algorithm>



int main(int argc, char *argv[]) {
    //take user input
    int array_size;
    std::cin >> array_size;
    
    //dynamically allocate the array with non constant size
    int* array = new int[array_size];
    
    //read input
    for (int i = 0; i < array_size; i++) {
        std::cin >> array[i];
    }
    
    for (int i = 0; i < array_size; i++) {
        std::cout << array[i] << ' ';
    }
    std::cout << std::endl;
    //use std::reverse from algorithm library
    std::reverse(array, array + array_size);
    
    for (int i = 0; i < array_size; i++) {
        std::cout << array[i] << ' ';
    }
    std::cout << std::endl;
    
    //free the dynamically allocated memory
    delete[] array;
    
    return 0; 
}

Please be aware that when you change the array_size after the array was created, it will not resize the array.

I recommend you to read more about memory management in C++. When you fully understand how the memory works, your code will have less bugs.

Aturtl3
  • 37
  • 8
  • Thank you for the explanation and showing me a better way to output items. The next chapter I am reading is about vectors. – Labbayk Jun 04 '23 at 21:51
0

You have made a few small logical errors.

You're still a student, so this will come with time, but always have a focus of understanding how C++ works. Semantic errors are harder to catch than syntactic ones.

the first issue with your code its that you initialized an array BEFORE asking the user what size to make it. if you ask later, that changes the sizeofArray variable but doesn't resize the array you already created. In fact, to resize an array you have to allocate a new array and copy the old elements to the new array, then delete the old array.

I suppose you have not yet studied vectors, therefore, lets figure out how to fix this code while implementing an array.

Your code:

  int sizeofArray;    //int whose size is garbage
  int array[sizeofArray];  // Array is made of garbage size
  
  cin >> sizeofArray;   

// The variable you used to get input is now the desired size, // However, the original array is still garbage size.

you can fix this issues by simply changing the order so that the computer knows what size to make the array.

  int sizeofArray;
  cin >> sizeofArray;

  int array[sizeofArray];
  

Now, The array will be created with the size that you read in from the user.

Second error: When printing out the array backwards, if you start at the sizeofArray, you will try to print out an index that doesn't exist.

suppose sizeofArray = 4 you have indexes 0,1,2,3 because we start counting at 0. If the highest index is 3 and you try to print starting at sizeofArray, youll try to print Array[4] which does not exist.

How to fix this: simple, we subtract 1 from sizeofArray. now it will print indices 3,2,1,0

for (int j = sizeofArray - 1 ; j >=0; --j) {
  cout << array[j] << " ";

}

mpAppProg
  • 1
  • 4