Thread: Size of Array, user inputted..

  1. #1
    Student otchster's Avatar
    Join Date
    Oct 2005
    Posts
    30

    Size of Array, user inputted..

    I am familiar with basic arrays...
    Code:
    int list[50]
    Creates an array named list, that is 50 long.

    How do I go about coding an array that is the length that the user inputs?

    I thought about declaring a variable length, and then doing this:
    Code:
    int list[length];
    So when the program would ask, "How long do you wish to make the array?", if the user inputted 27, the array would be 27 long..


    ...but that of course didn't work. Whats the best way to achieve this?

    thanks all =)

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Dynamically allocate the array
    Code:
    int * list = new int[length];
    and dont forget to
    Code:
    delete [] list;
    when youre done with the array
    Kurt

  3. #3
    Registered User
    Join Date
    Dec 2005
    Location
    Canada
    Posts
    267
    I think vectors would be best fit for the job
    http://www.cplusplus.com/reference/stl/vector/

    OS: Windows 7, XUbuntu 11.10, Arch Linux
    IDE: CodeBlocks
    Compiler: GCC

  4. #4
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    You should read a few tutorials about pointers/memory allocation, before using them
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  5. #5
    Student otchster's Avatar
    Join Date
    Oct 2005
    Posts
    30
    Quote Originally Posted by ZuK View Post
    Dynamically allocate the array
    Code:
    int * list = new int[length];
    and dont forget to
    Code:
    delete [] list;
    when youre done with the array
    Kurt
    Im having trouble figuring out how to take an int input from a user and create the array with that amount..

    Code:
    #include <iostream>
    #include <string>
    #include <algorithm>
    
    
    int length;
    int * list = new int[length];
    
    int main()
    {
    
    
    std::cout << "How many numbers do you wish to input?: ";
    std::cin >> length;
    
    
    
    
    
    
    return (0);
    }

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Im having trouble figuring out how to take an int input from a user and create the array with that amount..
    You're having trouble because C++ doesn't support arrays with a non-const size. Read the other posts again for alternative solutions.
    My best code is written with the delete key.

  7. #7
    Student otchster's Avatar
    Join Date
    Oct 2005
    Posts
    30
    Quote Originally Posted by Prelude View Post
    >Im having trouble figuring out how to take an int input from a user and create the array with that amount..
    You're having trouble because C++ doesn't support arrays with a non-const size. Read the other posts again for alternative solutions.
    I am new to C++ and I know nothing about vectors, etc.. Also, I haven't been taught anything about them in my class, so I'm guessing that they shouldn't be required to code the program I am trying to code..

    I have to create a function named count, with the 3 inputs, number, array and length.. The program must count the number of times number appears in the array. The array has length elements, so I was thinking of some how defining the array from an integer user input..

    I'm not asking for the exact program, I want to learn. But I've been staring at this exercise for 2 days and I have no idea where to begin..

    Thanks for all who help push me in the right direction =)

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    There are three options. The best option is to use vector. IMO vector should be taught before any other option for user defined sized arrays. However, if you haven't learned it in your class, then you might not want to use it for an assignment.

    The second option is to use a dynamic array with new [] and delete [] as in ZuK's example. I don't like this option, and you will rarely (if ever) find a situation where it is a better choice than vector. However, C++ classes still teach it, so if this is what your class is teaching this is what you should use.

    If your class is not teaching dynamic arrays with new[]/delete[] and also not teaching vectors, then perhaps you aren't supposed to use either. A third option would be to have a maximum size. For example, you get the length from the user but they cannot input more than 1000 (or some other number). What you would do is create your array with the MAXIMUM number of values, but only use the number of values that the user tells you they want to use.

    In this case, you aren't creating a dynamic array, but you can still accomplish your task of only using how many numbers the user specifies.

  9. #9
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Quote Originally Posted by otchster View Post
    I am new to C++ and I know nothing about vectors, etc.. Also, I haven't been taught anything about them in my class, so I'm guessing that they shouldn't be required to code the program I am trying to code..
    It helps to know something despite it not being covered in class. In a good C++ class they are taught as part of the curriculum later. Arrays ususally are to get you started with the concept of sequential data. Arrays are just an improvement and encapsulation of arrays.

    It's also part of the Standard Template Library, which is a large part of the C++ standard.
    Last edited by indigo0086; 06-25-2007 at 11:44 AM.

  10. #10
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    I have to create a function named count, with the 3 inputs, number, array and length..
    So just forget about CREATING the array.
    Just suppose it is ALREADY CREATED outside the function.
    And concentrate on your task at hand: write the FUNCTION THAT ACCEPTS the array and legth
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    In a good C++ class they are taught as part of the curriculum later.
    Like Daved, I would say that in a good C++ class vectors should be taught before dynamic arrays created with new[], and possibly even before statically sized arrays.

    otchster, what were you taught concerning arrays? Based on that you can choose the best option as suggested by Daved.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Student otchster's Avatar
    Join Date
    Oct 2005
    Posts
    30
    I wish to go the route of a maxinum array..

    Code:
    #include <iostream>
    #include <string>
    #include <algorithm>
    
    
    int length;
    int list[100];
    int counter;
    
    
    int main()
    {
    
    
    std::cout << "How many numbers do you wish to input?: ";
    std::cin >> length;
    
    for (counter = 0; counter < length; ++counter)
            {
            std::cout << "Number? ";
            std::cin >> //***ARRAY ELEMENT X
    
            }
    
    
    //***   ONCE THE ARRAY IS FILLED WITH THE USER DEFINED AMOUNT, I NEED
            TO SEARCH THE ARRAY FOR A USER INPUTTED NUMBER, AND OUTPUT HOW
            MANY TIMES IT IS IN THE ARRAY
    ***//
    
    
    
    
    return (0);
    }
    Here, I'm hoping to have a user input length, and then use a FOR statement to prompt the user length times to input numbers into the array... How do I code a FOR statement to fill an array element with the next slot each time?

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    How do I code a FOR statement to fill an array element with the next slot each time?
    You could replace your "//***ARRAY ELEMENT X" with list[counter], thus accessing the current element in the array.

    I suggest that you move these lines into the main() function:
    Code:
    int length;
    int list[100];
    int counter;
    There is no need to have them as global variables.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    If you really want to go the dynamic memory allocation route then you've got some switching around of code to do to get it working properly:
    Code:
    #include <iostream>
    #include <string>
    #include <algorithm>
    
    int main()
    {
        int length;
    
        std::cout << "How many numbers do you wish to input?: ";
        std::cin >> length;    // Get length from user "before" you attempt to allocate space
    
        // Now allocate space based on user input length...
        int * list = new int[length];
    
       
        // Do whatever you need to with the list array you've allocated.
    
    
        // Clean up the memory you've allocated.
        delete [] list;
    
        return 0;
    }
    Using a vector is far better like others have mentioned... you don't need to new/delete any memory, it's automatically done for you by the vector itself.

    The algorithm header you are including contains a templated function that can easily do the counting for you (not gonna tell you what it's called) although I suspect you need to learn/experience loops more.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  15. #15
    Student otchster's Avatar
    Join Date
    Oct 2005
    Posts
    30
    Quote Originally Posted by laserlight View Post
    You could replace your "//***ARRAY ELEMENT X" with list[counter], thus accessing the current element in the array.

    I suggest that you move these lines into the main() function:
    Code:
    int length;
    int list[100];
    int counter;
    There is no need to have them as global variables.
    Thanks everyone, my program now fills an array to the amount of the users preference, to a maximum.

    The next step is to have the user input a number, search the array, and then respond with an output of how many times the number was inputted in the array...

    Heres where I'm at, it compiles without error:

    Code:
    #include <iostream>
    #include <string>
    #include <algorithm>
    
    int main()
    {
    
    int length;             //The length of the array
    int list[100];          //The array Max 100
    int counterfill;        //Counter for filling array
    int counterfind;        //Counter for finding array
    int number;             //The number to search for
    int amount;             //The amount the number was found
    
    
    std::cout << "How many numbers do you wish to input?: ";
    std::cin >> length;
    
    
    for (counterfill  = 0; counterfill < length; ++counterfill)             //For statement to fill array
            {
            std::cout << "Number? ";
            std::cin >> list[counterfill];
            }
    
    std::cout << "What number do you wish to search for?: ";
    std::cin >> number;
    
    for (counterfind = 0; counterfind < length; ++counterfind)
            {
            if(list[counterfind] == number)
                    {
                    ++amount;
                    }
            }
    
    std::cout << "The number " << number << " appeared " << amount << " times. \n";
    
    return (0);
    The program compiles and runs correctly, EXCEPT this is what happens when I run it...

    An example:

    Code:
    How many numbers do you wish to input?: 5
    Number? 3
    Number? 9
    Number? 4
    Number? 26
    Number? 8
    What number do you wish to search for?: 26
    The number 26 appeared 671472553 times.
    Code:
    The number 26 appeared 671472553 times.
    ^^ Should say The number 26 appeared 1 times, obviously
    Last edited by otchster; 06-25-2007 at 12:30 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c++ a very simple program
    By amjad in forum C++ Programming
    Replies: 1
    Last Post: 05-27-2009, 12:59 PM
  2. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 03:55 AM
  3. templates, unresolved external error
    By silk.odyssey in forum C++ Programming
    Replies: 9
    Last Post: 06-09-2004, 04:39 PM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM
  5. Assign array size by user
    By Brown Drake in forum C++ Programming
    Replies: 2
    Last Post: 09-11-2001, 06:45 AM