Thread: populating arrays

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    9

    Arrow populating arrays

    I am having a hard time find example in C (not c ++) in populating arrays.
    I need example to refrence to because i have never done it before. I want to error check the inputs before i put it in the array.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Perhaps in a for loop, you could have the input tested, either in a block of code, or in a function, before assigning the value into your array, something like:

    Code:
    for(i = 0; i < MaxArrayInputItems; i++)  {
       variable = getInput();
       if(okInput(variable))
          array[i] = variable;
    }
    Where getInput() receives input from the user or file, and okInput() tests the variable to see if it's OK to go into the array at index i, returning zero if the input is bad. An actual zero could be a good variable, and okInput() should return the value 1 for that input, if in fact, a zero would be in the range of a good input value.

    Don't confuse the return value from okInput, with the value that okInput is testing.

    You may need to hit the books or some on-line C tutorials, in order to make this program.

    In any case, it will be a good exercise to learn from.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Try this

    Its a good tutorial on arrays in c

    C Programming - Arrays

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Here's an example:
    Code:
    #include <stdio.h>
    #include <errno.h>
    #include <stdlib.h>
    
    /* compile -std=c99 */
    
    float getInput() {
    	char input[32], *tptr;
    	float val;
    	printf("Enter any kind of number: ");
    	fgets(input,32,stdin);
    	errno = 0;
    	val = strtof(input,&tptr);
    	if ((errno) || ((val == 0) && (tptr == input))) {
    		puts("That input is not valid!  Try again...");
    		val = getInput();
    	} 
    	return val;
    }
    
    int main() {
    	float array[6];
    	int i;
    	for (i=0; i<6; i++) array[i] = getInput();
    	for (i=0; i<6; i++) printf("%f\n",array[i]);
    	return 0;
    }
    This may seem a bit complex, but the form should be easy to follow. The verification is slightly lame since strtof will go to some length to take a number, eg, "1324mdsf" will be 1324 and "3,5" will be 3, but this at least means you will end up with a valid number submitted to the array. And you get an example of how to error check the strtof/l/d() functions, which are useful in verifying input this way.

    NB. strtof is a c99 function and needs to be compiled with that in mind!
    Last edited by MK27; 08-04-2009 at 09:54 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    9

    Thumbs down

    thanks Adak i think i got what you said there

    roaan thanks for the link i will read it

    MK27 thanks for the example but theres some stuff in there i haven't learn yet floats and strtof yet so i didnt understand it fully


    i want to have so that if the user enters a number but if the number doesnt meet the requirements it doesnt store it in the array

    i wrote some code quickly just now
    i am not sure if i am doing it right

    is is possible to do to this in one function
    Code:
    int getInput(int x);  
    int okInput(int y);
      main()   
    
    {
    int variable, maxarr, usri;
    maxarr = 10
    for (i=0; i < maxarr; i++);
    variable = getInput(usri);
    if (okInput (variable))
            array[i] = variable
    
    }           
    int getInput(int x);
    {
     printf("Enter a number");
    scanf("%d, &usri");
    return x;
    }
    int okInput(int y);
    {
    if (y <0)
        break;
    else
    return y;
    }
    Last edited by jafa401; 08-04-2009 at 10:45 AM.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by jafa401 View Post

    i want to have so that if the user enters a number but if the number doesnt meet the requirements it doesnt store it in the array

    i wrote some code quickly just now
    i am not sure if i am doing it right
    If you can write code, you should be able to read code. So, read the code you have posted. Follow its logic, either mentally or on paper. Think up some inputs (both good and bad) and see what will happen when this code runs. If it does what you want, then it's right(*). If it doesn't, it's wrong.

    (*)Technically, it could still be wrong, if it fails on some input case you didn't consider. That's why you want to be sure, when you're thinking of test cases, that you be thorough about it.

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by jafa401 View Post
    is is possible to do to this in one function
    Yeah, and using scanf() is fine too. But you need to use the return value of scanf to determine whether or not it retrieved a number. Then you can check that, and do what I did to repeat if scanf() failed -- here's a pseudo code version:
    Code:
    int getInput () {
         int value;
         ask for input
         r=scanf("%d%*c",&value);
         if (r != 1) {
              puts error message;
              value = getInput();
         }
         return value;
    }
    About the bit in red: %*c will trap the "trailing newline" which will get left in the input buffer and cause a problem (do it first without %*c and you will understand what the problem is).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    9
    i want it so if the user enters umm a negative number it will not store it in the array it just continues on with out error msg.

    thanks MK27 i will play around this that code

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Some suggestions:

    Code:
    #include <stdio.h>   //add
    
    #define maxarr 10   //change maxarr to a define
    
    int getInput(void);  //88
    int okInput(int y);
    
    int  main() // always int main() and a return at the end  
    {
      int i, variable;  //add i, delete usri
      int array[maxarr];        //add array[]
    
      for (i=0; i < maxarr; i++) { //remove ; add curly brace
        variable = getInput();
        if (okInput (variable))
          array[i] = variable; //add ;
      }
      printf("\n The array is full.\n");
      printf("\n Why not make a function to show it? \n");
      printf("\n\t\t\t     Press Enter When Ready\n");
      i = getchar(); 
      return 0;
    }  //add closing brace         
    /*we could send x to getInput, but we don't need to 
    we're using just the one return value that a function 
    can give us, instead.
    */
    int getInput(void)  //remove ;  
    {
      int x;
      printf("Enter a number");
      scanf("%d, &x");
      return x;
    }
    int okInput(int y)  //remove ;
    {
      int valid = 1;
      int invalid = 0;
    
      if (y <0)
        return invalid;
      else
        return valid;
    
    //there is no need to return y. main() already has it as "variable"
    }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I think that okInput would be more readable as:
    Code:
    int okInput(int y)
    {
        return y >= 0;
    }
    after all, the extra variables are not necessary, and now it is easy to see that "ok input" means that "the input is greater than or equal to 0".
    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

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by jafa401 View Post
    i want it so if the user enters umm a negative number it will not store it in the array it just continues on with out error msg.
    Do you want to use an error msg at all? Anyway, if not, you could just take that part out, and simplify by setting "value" to -1 initially. Then, if scanf() doesn't get a proper number, value will still be -1 and you can use that as the if condition -- so no more need to check scanf's return value"
    Code:
    int value = -1;
    scanf("%d%*c",&value);
    if (value < 0) value = getInput();
    return value;
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Wow, lots of people doing people's homework today!

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by nonoob
    Wow, lots of people doing people's homework today!
    It is reasonable to suggest improvements in code after the person has actually posted a reasonable attempt.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  2. Need Help With 3 Parallel Arrays Selction Sort
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2005, 10:47 PM
  3. populating arrays
    By john_murphy69 in forum C Programming
    Replies: 7
    Last Post: 04-04-2003, 12:03 PM
  4. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM
  5. populating two dimensional arrays
    By garycastillo in forum C Programming
    Replies: 2
    Last Post: 04-05-2002, 08:22 PM

Tags for this Thread