confused about arrays

This is a discussion on confused about arrays within the C Programming forums, part of the General Programming Boards category; ok, i know that store data in arrays. for example int grades[5], but let's say i don't want to input ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    17

    confused about arrays

    ok, i know that store data in arrays. for example int grades[5], but let's say i don't want to input all five yet, first input (90), then go back to menu, choose a subject(Science), and input (91), and return to menu again. How do i use a for loop to do this.

  2. #2
    moi
    moi is offline
    Registered User moi's Avatar
    Join Date
    Jul 2002
    Posts
    946
    what code do you have so far?
    hello, internet!

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    Maybe something like this:
    Code:
    void enter_grade(int subject, float grade);
    int x=0;
    for(;;)
    {
         int subject;
         float grade;
         printf("Enter subject:\n\t0.Science\n\t1.Social Studies\n:");
         scanf("%d", &subject);
         printf("Enter grade for subject: ");
         scanf("%f", &grade);
         enter_grade(subject, grade);
    }
    
    void enter_grade(int subject, float grade)
    {
         grades[subject][x] = grade;
          x++;
    }
    there's probably a much better way of doing that, but im bored and stupid so... did that answer your question?
    Last edited by principii; 09-18-2004 at 02:11 PM.

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    277
    You want a variable size matrix thats it? Well you will have to go memory allocating (dunno if I wrote it right please correct me if I'm wrong I'm lazy about look at a dictionary) it dinamical...
    For reference:

    ALLOC(3) Linux Programmer's Manual MALLOC(3)

    NAME
    calloc, malloc, free, realloc - Allocate and free dynamic
    memory

    SYNOPSIS
    #include <stdlib.h>

    void *calloc(size_t nmemb, size_t size);
    void *malloc(size_t size);
    void free(void *ptr);
    void *realloc(void *ptr, size_t size);

    DESCRIPTION
    calloc() allocates memory for an array of nmemb elements
    of size bytes each and returns a pointer to the allocated
    memory. The memory is set to zero.

    malloc() allocates size bytes and returns a pointer to the
    allocated memory. The memory is not cleared.

    free() frees the memory space pointed to by ptr, which
    must have been returned by a previous call to malloc(),
    calloc() or realloc(). Otherwise, or if free(ptr) has
    already been called before, undefined behaviour occurs.
    If ptr is NULL, no operation is performed.

    realloc() changes the size of the memory block pointed to
    by ptr to size bytes. The contents will be unchanged to
    the minimum of the old and new sizes; newly allocated memI am silly
    ory will be uninitialized. If ptr is NULL, the call is
    equivalent to malloc(size); if size is equal to zero, the
    call is equivalent to free(ptr). Unless ptr is NULL, it
    must have been returned by an earlier call to malloc(),
    calloc() or realloc().

    RETURN VALUE
    For calloc() and malloc(), the value returned is a pointer
    to the allocated memory, which is suitably aligned for any
    kind of variable, or NULL if the request fails.

    free() returns no value.

    realloc() returns a pointer to the newly allocated memory,
    which is suitably aligned for any kind of variable and may
    be different from ptr, or NULL if the request fails. If
    size was equal to 0, either NULL or a pointer suitable to
    be passed to free() is returned. If realloc() fails the
    original block is left untouched - it is not freed or
    moved.

    CONFORMING TO
    ANSI-C

    SEE ALSO
    brk(2), posix_memalign(3)

    NOTES
    The Unix98 standard requires malloc(), calloc(), and realI am silly
    loc() to set errno to ENOMEM upon failure. Glibc assumes
    that this is done (and the glibc versions of these rouI am silly
    tines do this); if you use a private malloc implementation
    that does not set errno, then certain library routines may
    fail without having a reason in errno.

    Crashes in malloc(), free() or realloc() are almost always
    related to heap corruption, such as overflowing an alloI am silly
    cated chunk or freeing the same pointer twice.
    Recent versions of Linux libc (later than 5.4.23) and GNU
    libc (2.x) include a malloc implementation which is tunI am silly
    able via environment variables. When MALLOC_CHECK_ is
    set, a special (less efficient) implementation is used
    which is designed to be tolerant against simple errors,
    such as double calls of free() with the same argument, or
    overruns of a single byte (off-by-one bugs). Not all such
    errors can be protected against, however, and memory leaks
    can result. If MALLOC_CHECK_ is set to 0, any detected
    heap corruption is silently ignored; if set to 1, a diagI am silly
    nostic is printed on stderr; if set to 2, abort() is
    called immediately. This can be useful because otherwise
    a crash may happen much later, and the true cause for the
    problem is then very hard to track down.

    BUGS
    By default, Linux follows an optimistic memory allocation
    strategy. This means that when malloc() returns non-NULL
    there is no guarantee that the memory really is available.
    This is a really bad bug. In case it turns out that the
    system is out of memory, one or more processes will be
    killed by the infamous OOM killer. In case Linux is
    employed under circumstances where it would be less desirI am silly
    able to suddenly lose some randomly picked processes, and
    moreover the kernel version is sufficiently recent, one
    can switch off this overcommitting behavior using a comI am silly
    mand like
    # echo 2 > /proc/sys/vm/overcommit_memory
    See also the kernel Documentation directory, files
    vm/overcommit-accounting and sysctl/vm.txt.


    So IMHO you should make a matrix of list heads for each subject and just go putting the grades there.

  5. #5
    Registered User
    Join Date
    Sep 2004
    Posts
    17

    Code:

    here is what i came up with, i can select menu, go to that option,back to menu, do something different, but can't get it to print out my array after all input has been stored. Any suggestions?



    #include <stdio.h>
    #define MAX 10
    int num_books(int[],int );

    void print_num_books(int [],int);
    int main(void)
    {

    int stock_amt[MAX];

    int n;
    while(n!=11)
    {

    printf("\nPlease choose an option below by typing a number between 1 and 11.\n\n");

    printf("1\tAutomobiles\n\n");
    printf("2\tCookbooks\n\n");
    printf("3\tGardening\n\n");
    printf("4\tHistory\n\n");
    printf("5\tMystery\n\n");
    printf("6\tPlanets\n\n");
    printf("7\tScience fiction\n\n");
    printf("8\tSelf Help\n\n");
    printf("9\tSports\n\n");
    printf("10\tTravel\n\n");
    printf("11\tExit program\n\n");


    n=num_books(stock_amt,MAX);
    print_num_books(stock_amt,n);
    }

    }
    int num_books(int stock_amt[],int lim)
    {
    int index=0,n;

    scanf("%d", &n);


    if(n==1)
    {
    printf("How many automobiles will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else if(n==2)
    {
    printf("How many cookbooks will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    if(n==3)
    {
    printf("How many gardening will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else if(n==4)
    {
    printf("How many History will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    if(n==5)
    {
    printf("How many Mystery will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else if(n==6)
    {
    printf("How many Planets will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    if(n==7)
    {
    printf("How many Science fiction will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else if(n==8)
    {
    printf("How many Self Help will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }

    if(n==9)
    {
    printf("How many Sports will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else if(n==10)
    {
    printf("How many Travel will Perfect book carry?");
    scanf("%d",&stock_amt[index]);
    }
    else return(index);
    }
    void print_num_books(int stock_amt[],int n)
    {
    int index;
    printf("\n***STOCK INVENTORY**\n\n");
    for(index=0;index<n;index++){

    printf("Amount is %d\n",stock_amt[index]);
    }
    }

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Use this as a base to work from:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      int a[10];
      int index = 0;
      int i;
    
      while ( index < 10 ) {
        printf ( "1) Add a number\n2) Display numbers\n" );
        printf ( "Selection: " );
        fflush ( stdout );
    
        switch ( getchar() ) {
        case '1':
          printf ( "Enter a number: " );
          fflush ( stdout );
    
          if ( scanf ( "%d", &a[index++] ) != 1 ) {
            fprintf ( stderr, "Invalid input\n" );
            return EXIT_FAILURE;
          }
    
          break;
        case '2':
          for ( i = 0; i < index; i++ )
            printf ( "%d ", a[i] );
          printf ( "\n" );
    
          break;
        default:
          fprintf ( stderr, "Invalid selection\n" );
          return EXIT_FAILURE;
        }
    
        getchar(); /* Eat the newline */
      }
    
      return EXIT_SUCCESS;
    }
    My best code is written with the delete key.

  7. #7
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    I haven't learned the switch case yet, so not allowed to use in program

  8. #8
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    then use if/else statements?

  9. #9
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    Quote Originally Posted by sal817
    I haven't learned the switch case yet, so not allowed to use in program
    Oh? Phooey, I spent the last twenty minutes toying around with your program. Perhaps something like below will help anyway... just not today. At least you can test it for errors as I did not.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAXB 10
    
    const char *BOOKS[] = { "automobile", "cook", "gardening", "history",
                            "mystery", "planet", "science fiction", "self help",
                            "sports", "travel" };
    
    int selectBook(void);
    void printSck(int *);
    
    int main(void)
    {
       char buf[BUFSIZ], *p;
                        
       int stockAmt[MAXB] = { 0 }; /* init stock */
       int cIndex, sAmount;  
       
       while((cIndex = selectBook()) != 11)
       {
          cIndex -= 1;
          
          printf("How many %s%s will Perfect Book carry: ", 
                  BOOKS[cIndex], (cIndex == 1 ? "books" : " books"));
          fgets(buf, sizeof buf, stdin);
          
          if((p = strchr(buf, '\n')) != NULL)
             *p = '\0';
          
          if((sscanf(buf, "%d", &sAmount)) != 1)
             fprintf(stderr, "Invalid amount detected - %s.  Ignoring entry.\n\n", buf);
          else
             stockAmt[cIndex] = sAmount;    
       
       }
       
       printSck(stockAmt);
          
       puts("\nDone.\n");
       while(getchar() != '\n'){}
       
       return (0);
    }
    
    int selectBook(void)
    {
       char tmp[5];
       int choice;
       static char *message = "Please select a book below (1-11)\n\n"
                              " 1) Automobiles\n"
                              " 2) Cookbooks\n"
                              " 3) Gardening\n"
                              " 4) History\n"
                              " 5) Mystery\n"
                              " 6) Planets\n"
                              " 7) Science Fiction\n"
                              " 8) Self Help\n"
                              " 9) Sports\n"
                              "10) Travel\n"
                              "11) Exit Program\n\n-> "; 
                              
       do
       {
          printf("%s", message);
          fgets(tmp, sizeof tmp, stdin);            
          
       }while((sscanf(tmp, "%d", &choice)) != 1 || (choice < 1 || choice > 11));  
       
       puts("\n");
       
       return (choice);
    } 
    
    void printSck(int *tmp)
    {
       int i;
       
       puts("     ---- Inventory ----\n");
       
       for(i=0; i < MAXB; i++)
          printf("%16s = %d\n", BOOKS[i], tmp[i]);
    }
    I haven't used a compiler in ages, so please be gentle as I try to reacclimate myself. :P

  10. #10
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    can't use pointer either,only array if else+while+for

  11. #11
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    i think i'm going the wrong way about doing this. Ok i want to ask the user to select option, store data in array, and ouput like this

    Autombiles Amount is 200
    Cookbooks Amount is 500
    History Amount is 300
    ..... ............
    etc.............

    a array of 10;
    somwhere in here i probably need a for loop
    UGH!! I don't get this stuff!!!
    please help!

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    1) Read the Announcements.
    2) Use [code] tags. You'd know this if you'd done #1.
    3) Write it out on paper, in big steps.
    Code:
    buy food:
        go to the store
        pick out things I need
        pay for them
        come home
    Once you have that done, you can breat it into smaller steps:
    Code:
    go to store:
        leave house
        walk or use some form of transportation
    
    pick out things I need:
        ...
    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    Quote Originally Posted by sal817
    i think i'm going the wrong way about doing this. Ok i want to ask the user to select option, store data in array, and ouput like this

    Autombiles Amount is 200
    Cookbooks Amount is 500
    History Amount is 300
    ..... ............
    etc.............

    a array of 10;
    somwhere in here i probably need a for loop
    UGH!! I don't get this stuff!!!
    please help!
    Your algorithm will depend on how you want the user to input information - sequentially or random. If you simply want the user to input values for each book one at a time, then use a for loop starting at pos 0, and ending at pos MAX - 1. However, if you want to bounce around with the input order, then I'd go with a while loop... something like:

    Code:
    while((index = getBookRequest()) != quit_program)
    {
       bookArray[index] = getInventoryAmount(BOOKS[index]);
       /* other stuff */
    }
    
    int getInventoryAmount(const char theBook[])
    {
        int value;
    
        printf("How many %s books to add: ", theBook);
        scanf(" %d", &value);
    
        return (value);
    }
    If you initialize your array to some value that your cannot enter, then you can use that known value to display only the books that have a good value in them.

    Code:
    int showInventory(int myArray[])
    {
       int i;
    
       for(i =0; i < MAX; i++)
       {
           if(myArray[i] != known value)
              printf("%s amount %d\n", BOOKS[i], myArray[i]);
       }
    }
    For this to work, BOOKS can be made a const global

    const char BOOKS[][MAXLEN] = { "...", "...", ... };

    As mentioned before by Prelude, check the status of all calls to scanf. If you're going to read numbers directly, then you'll want to make certain that you don't wind up with stream errors.

    HTH
    I haven't used a compiler in ages, so please be gentle as I try to reacclimate myself. :P

  14. #14
    Registered User
    Join Date
    Sep 2004
    Posts
    17
    ok i work on list last night, and still having problems, How do i get from menu to the function(error--category does not return a function) I want to be able to store the option, and go through menu, till hits 10. I've been on this too long!!
    Please help!!

    #include <stdio.h>

    int category(int[10],int[10],float[10],int[10]);

    int main(void)
    {
    int n;
    while(n!=11)
    {
    printf("\nPlease choose an option below by typing a number between 1 and 11.\n\n");

    printf("1\tAutomobiles\n\n");
    printf("2\tCookbooks\n\n");
    printf("3\tGardening\n\n");
    printf("4\tHistory\n\n");
    printf("5\tMystery\n\n");
    printf("6\tPlanets\n\n");
    printf("7\tScience fiction\n\n");
    printf("8\tSelf Help\n\n");
    printf("9\tSports\n\n");
    printf("10\tTravel\n\n");
    printf("11\tExit program\n\n");
    scanf("%d",&n);
    n=category();

    }
    return(n);


    }
    int category(int list[],int stock_amt[],float avg_price[],int sell_percentage[])
    {
    int i=0;
    printf("Enter category number(0 to end): ");
    scanf("%d",&list[i]);

    while(list[i]!=0)
    {
    printf("How many books will Perfect book carry?");
    scanf("%d",&stock_amt[i]);

    printf("What is the avg price for book?");
    scanf("%f",&avg_price[i]);

    printf("What is the selling percentage for book?");
    scanf("%d",&sell_percentage[i]);

    i++;
    }
    return(i);
    }

  15. #15
    Casual Visitor
    Join Date
    Oct 2001
    Posts
    350
    Quote Originally Posted by sal817
    ok i work on list last night, and still having problems, How do i get from menu to the function(error--category does not return a function) I want to be able to store the option, and go through menu, till hits 10. I've been on this too long!!
    Please help!!
    It sounds like you're after a 2D array, where your book categories have three properties each. For example, the user loops through each of the 10 book categories inserting values into each of the three properties.

    I still don't quite understand what you're after as your code doesn't equate to your description.

    However, you can try something like:

    Code:
    #define MAXS 10
    
    void category(int, char [], int[], float[], int[]);
    
    ...
    /* declare these in main */
    
    char books[MAXS][18] = { "automobile", ... "travel" };
    int i, count, stock_amt[MAXS], sell_p[MAXS];
    float ave_price[MAXS];
    
    count=0;
    
    while(count < MAXS)
    {
         prompt for category number
         read in category number (var i)
         validate range of number
    
         if i holds the exit value then
             set count to MAXS
         else
         {
            check number arrays for [i] having data already
    
            if(any number_array[i] == init_value)
            {
               category(i, books[i], stock_amt, ave_price, sell_p);
               count++;
            }
         } 
    }
    
    ...
    
    void category(int index, char thebook[], int s[], float a[], int p[])
    {
       printf("How many %s books will ....", thebook);
       scanf(" %d", &s[index]);
    
       printf("What is the average price for %s books: ", thebook);
       scanf(" %f", &a[index]);
    
       ....
    }
    I haven't used a compiler in ages, so please be gentle as I try to reacclimate myself. :P

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Vertex Arrays
    By Shamino in forum Game Programming
    Replies: 2
    Last Post: 01-08-2006, 01:24 AM
  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. Building B-Tree from Arrays
    By 0rion in forum C Programming
    Replies: 1
    Last Post: 04-09-2005, 03:34 AM
  4. Help with arrays and pointers please...
    By crazyeyesz28 in forum C++ Programming
    Replies: 8
    Last Post: 03-17-2005, 01:48 PM
  5. Merging two arrays.
    By Roaring_Tiger in forum C Programming
    Replies: 2
    Last Post: 08-21-2004, 08:00 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21