user2966840
user2966840

Reputation: 3

Questions about filling arrays with user inputs in C

I'm just beginning to learn C in a town where even the teenagers are borderline technophobes, so please go easy on me! ^^'

I'm trying to build a program that reads in a number of rooms, then loops a series of user inputs for each room. I want to be able to store these user inputs in an array, so I can add them up at a later stage in the program. I haven't moved onto pointers or whatever malloc/realloc is; as I said, I haven't been learning for long. Any help or constructive input [i.e Not pointing out my complete and utter newb-ishness] would be much appreciated!

int main(){
    int marks[20];
    int i;
    int rooms = 0;
    int j = rooms;
    char option = 0;
    int lights[20]; 
    int hrsUsed[20]; 
    int Telly_Computer[20];

    printf("Enter number of rooms");
        scanf_s("%d", rooms);

        while (option != 'Q'){
         for(i=0;i<j;i++) {
            printf("input wattage of lights");
            scanf_s("%d", (lights+i));
            printf("input number of hours use/day (average)");
            scanf_s("%d", (hrsUsed+i));
            printf("input number of TV/Computers");
            scanf_s("%d", (Telly_Computer+i));
                }
          return 0;
     }
}

Upvotes: 0

Views: 670

Answers (2)

Maciej Stachowski
Maciej Stachowski

Reputation: 1728

Well, for one, you never ask for the option, so your program will never end. It will also crash when somebody wishes to add more than 20 rooms.

I don't see you setting j after you read the number of rooms, too, so your main loop will not run.

Upvotes: 0

Charlie Burns
Charlie Burns

Reputation: 7044

Change

scanf_s("%d", rooms);

to

scanf_s("%d", &rooms);

Your other scanf's work because they point to the location in the array where to store the data.

Also

for(i=0;i<j;i++)

needs to be

for(i=0;i<rooms;i++)

And you should make sure rooms < 20.

And you need to set option at some point to end your loop.

Upvotes: 1

Related Questions