C101: the best way to fill an array from user input?

I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached:

#include<stdio.h> #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); while(arr[idx-1] != -1 && idx < MAX){ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; } /* Approach #2 */ do{ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; }while(arr[idx-1] != -1 && idx < MAX); // Main func continues here. }

Any advice would be much appreciated!

Update:

Now it works! thanks MUCH all of you guys for such instant responses. This is definitely a great community, it's helping me a lot.

--------------Solutions-------------

arr[idx] <= MAX

should be

idx < MAX

unless you are checking the item instead of the index.

You are also always checking the "next" element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value.

so if you had

arr[idx-1] != -1

you would be fine.

arr[idx] <= MAX

should be

idx <= MAX

while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}

First of all, you should check if the index variabel idx is smaller than MAX (not smaller than or equal to). You would go out of bounds if your index equals MAX. An array with MAX = 10 has index values 0 to and including 9, but not 10.

Secondly, you add the first element to arr[0], you increment your index from 0 to 1, then you jump back to the while-condition and check if arr[1] == -1, which it is not. So check instead that arr[idx-1] != -1. Note however that the first time you get to the while-loop, you will actually check arr[-1] != -1, which is also out of bounds. ;) So you need to figure out how to solve this one.

to Roman M:

First of all, the guy asking the question has just started a programming course, and has probably not yet learned about pointers. Secondly, you now deal with both a counter and a pointer. I'm not sure I see the benefit of doing that versus using an index like this:

for(idx=0; idx < MAX; ++idx) {

scanf("%d", &arr[idx]);
if(arr[idx] == -1)
break;

}

Using a for loop you can eliminate the need for the messy idx-1 checking code:

/* Approach #3*/
int i;
int value;

for (i = 0; i < MAX; ++i)
{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &value);
if (value == -1) break;
arr[i] = value;
}

C arrays begin counting from 0.

If you allocate an array of size MAX, accessing the element at MAX would be an error. Change the loop to;

int arr[MAX];
for ( .... && idx < MAX )

In your first while loop, the

arr[idx] <= MAX

line should read

idx <= MAX

In your second loop, you're incrementing idx before the test - it should end with

} while ((arr[idx-1] != -1) && (idx-1 <= MAX));

I also tend to parenthesize all internal conditions just to be absolutely certain that the precedence is correct (hence the extra brackets above).

I'd go with somthing like this.

You don't have to worry about array bounds and other confusing conditions.

int cnt = MAX; // how many elements in the array, in this case MAX
int * p = &arr[0]; // p is a pointer to an integer and is initialize to the address of the first
// element of the array. So now *p is the same as arr[0] and p is same as &arr[0]

// iterate over all elements. stop when cnt == 0
while (cnt) {

// do somthing
scanf("%d", *p); // remember that *p is same as arr[some index]
if (*p == -1) // inspect element to see what user entered
break;

cnt --; // loop counter
p++; // incrementing p to point to next element in the array
}

Category:c# Time:2008-09-21 Views:0

Related post

  • How to Fill an array from user input C#? 2008-10-23

    What would be the best way to fill an array from user input? Would a solution be showing a prompt message and then get the values from from the user? --------------Solutions------------- string []answer = new string[10]; for(int i = 0;i<answer.len

  • Assemblyx86 filling an array with user input 2014-06-11

    i have this part of code in which i am trying to fill an array (named array_number) with users input. For that reason i use a loop. Before the loop i use MOV AH, type array_number and because array_number is type SWORD, AH=2. While i was debuging i s

  • c# Fill multiple arrays with input 2011-04-02

    I'm trying to fill 3 arrays with user input, it should look like this: Enter account number 1: 29384 Enter the account balance: 1111 Enter the account holder last name: lastname Enter account number 2: 34938 Enter the account balance: 2222 Enter the

  • Most efficient way to create a zero filled JavaScript array? 2009-08-18

    What is the most efficient way to create an arbitrary length zero filled array in JavaScript? --------------Solutions------------- Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one

  • Why is the table filled with Array[0], Array[1],Array[2],Array[3] after the following SQL statement is executed? 2009-11-20

    Why is the table filled with Array[0], Array[1], Array[2], Array[3] after the following SQL statement is executed? mysql_query("INSERT INTO choicetable (announcementid, question, option1, option2, option3, option4) VALUES ('$announcementid', '$choice

  • how to fill char **array thats in a struct 2010-02-12

    typedef struct _stats_pointer_t { char **fileNames; stats_t stats; } stats_pointer_t; I need to fill 'fileNames'. Basically, I need to mimic this functionality: char *fileNames[argc - 1]; fileNames[0] = argv[0]; ... but using the struct stats_pointer

  • How do you fill an array with strings in C? 2010-02-20

    I'm trying to fill an array with names from a file: Andrew Andy Bob Dan Derek Joe Pete Richy Steve Tyler Here is the function I wrote...but the program crashes when I run it: #include <stdio.h> main(){ int i=0, size=10; char fname[15]; char** d

  • filling an array with random number 2010-03-03

    I'm trying to fill an array of 20 ints with numbers from 1-20 in random sequence. here's my code: int lookup[20]={0}; int array[20]={0}; srand(time(NULL)); for(int i=0;i<20;++i){ bool done=false; while(!done){ int n=rand()%20; if(lookup[n]==0){ ar

  • How do I randomly fill an array in Java? 2010-03-23

    I'm writing a program that creates a 2D array from a integer n. I then have to fill the array with values from 1 to the n*n array size and check to see if it is a magic square. The way I am doing it now fills the array in order from 1 to n*n array si

  • Fill a array with List data 2010-03-29

    How can I fill a array with the data provided by one List? For example, I have a List with Strings: List l = new ArrayList<String>(); l.add("a"); l.add("b"); l.add("c"); then I want to copy this data into a String array: String[] array = ? ----

  • How to fill byte array with junk? 2010-06-06

    I am using this: byte[] buffer = new byte[10240]; As I understand this initialize the buffer array of 10kb filled with 0s. Whats the fastest way to fill this array (or initialize it) with junk data every time? I need to use that array like >5000 t

  • Fill javascript array with c# 2010-08-07

    Hi How Can i fill an array that defined in javascript with c# in behind code? EDIT: here is my code protected void Page_Load(object sender, System.EventArgs e) { string[] locations = new string[] { "Las Vegas", "Los Angeles", "Tampa", "New York", "s"

  • Filling an Array with Items from a Table 2010-09-03

    I have a small requirement in VB.NET and that is to fill an array with values retrieved from a table. That is i have a table called "user_roles" and that is having columns called "role_id" and "role_name". In the load event of the form, i want to exe

  • Iteratively filling an array with hashes from an each/do block gives me all repeat values..help! 2010-10-31

    I am trying to fill an array of hashes with hashes created through an each loop, If I print each individual hash within the iteration they are distinct, but when I try to push them to an array, the resulting array has the last hash repeated whatever

  • Filling an array with random numbers from 1 to 10^10 in C or C++ 2011-01-15

    a part of an assignment of mine is based on an array (its size is given by the user) which contains random numbers from 1 to 10^10. Then we have to find the k-th smaller number of the array. Here's what I tried: #include <cstdlib> #include <

  • Why does this code to fill an Array create a memory leak? 2011-02-16

    I have encountered a somewhat baffling problem with the simple task of filling an Array dynamically in Java. The following is a snapshot from where the problem originates: entries = new Object[ (n = _entries.length + 1) ] ; for(i = 0 ; i < n ; i++

  • Can not fill an array in thread 2011-02-24

    This gui should draw moving images on frame panel called "system". But first of all i need to make those objects. Here i'm trying to add them to an array and use that array in other classes. But array keeps being empty! I guess the problem is in decl

  • Iterating through a List that is filled with arrays in C# 2011-02-25

    public List<string[]> parseCSV(string path) { List<string[]> parsedData = new List<string[]>(); try { using (StreamReader readFile = new StreamReader(path)) { string line; string[] row; while ((line = readFile.ReadLine()) != null) {

  • Am i filling this array wrong or outputting it wrong? 2011-03-10

    I am working on a program that fills an array with data from a text file. When I output the array its contents are not in the order I thought I read them in. I'm thinking the problem is either in one of the for loops that inputs data into the array o

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.290 (s). 13 q(s)