0

I have been thinking about looping through arrays whose sizes are not fixed in advance... for example, allowing a user to input as many elements into an array as they want.

Question 1: How would I set up user prompts to enter as many elements of the array as they want? I am thinking a do-while loop, maybe with some sort of question as the while, such as:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int numbers[];

    do
    {
        numbers[i] = get_int("Type an integer\n");

        char more = get_char("Do you have another element to add? y/n \n");
    }
    while (more == y);

(I am pretty sure this code is not yet correct, but just some early thoughts...)

Question 2: If I wanted to get a variable (that I could then use as the limit of the number of times a for loop runs through that array) for the eventual size of that array, how would I do it, since the size of the array isn't determined until the user stops entering elements?

Thanks!

2 Answers 2

0

The main problem here is that arrays are of a fixed size when created. Additional array elements can't be arbitrarily added in this way (unlike other languages that allow it.)

You could start by asking how many elements will be added and then declare the array with that number of elements. Finally run a for loop with the size that the user submitted.

Having said that, it is possible to do exactly what you want, but it's more complicated. Basically, you're creating a new array each loop pass, copying the old to the new and adding the new element. Or you can create a linked list (taught in detail in pset5 speller).

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
0

Thanks for your help, @Cliff B. I was able to take your suggestion and setup my own version of Prof. Malan's phonebook1.c which enables the user to determine the size of the phonebook, as well as the contents. So far, it works exactly as I hoped. (if you see any errors or design flaws, let me know!)

#include <stdio.h>
#include <cs50.h>
#include <string.h>

typedef struct
{
    string name;
    string number;
}
person;


int main(void)
{
    int size =  get_int("How many contacts are in this phonebook?\n");

    person people[size];

    for (int i = 0; i < size; i++)
    {
        string who = get_string("Name of contact:\n");
        string phone = get_string("Phone number:\n");

        people[i].name = who;
        people[i].number = phone;
    }


    for (int j = 0; j < size; j++)
    {
        printf("%s: %s\n", people[j].name, people[j].number);
    }



    for (int k = 0; k < size; k++)
    {
        if (strcmp(people[k].name, "David") == 0)
        {
            printf("Number found: %s\n", people[k].number);
            return 0;
        }
    }
    printf("Not found/n");
    return 1;

}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .