Thread: Terminator in integer Array.

  1. #1
    Registered User
    Join Date
    May 2020
    Posts
    8

    Question Terminator in integer Array.

    Hello

    I have to create program in which user has to choose how many numbers he would like to enter for example 3. then program ask about these numbers.(Array needs to have space=100) After that program has to add the terminator with value (-1) on the next free space in the array. (that is my main problem).

    For example, if the user enters that they have 5 values, the system will then ask them5 times to enter a number to be placed in the arrayOnce the user has finished entering their values, the system should add a -1 in to thenext free element of the array. This will act as a 'terminator'.

    in the same program system should ask the user what element of the arraythey want to replace. It should then ask what number they want to put in theirchosen array element.The program should then replace the users chosen array element with the value theyentered.

    Main problem which i have i do not know how to use terminator, when i cant declare variables like int /code a[5]={1,2,3,4\-1};, like a[100]; and user has to enter the values. /code

    Code:
    #include <stdio.h>
    #include <ctype.h>
    void As5GradeB()
    {
    
      int a[100];
      char opt;
      int i;
      float mean;
      int sum = 0;
      int num;
    
      opt = tolower(opt);
      printf("Enter number of elements \n");
      scanf("%d", &num);
      for (i = 0; i < num; i = i + 1) {
        printf("Enter value of the elements%d\n", i + 1);
        scanf("%d", &a);
      }
    
    
      while ((opt = getchar()) != '\n' && opt != EOF);
    
      while (opt != 'x') {
    
    
        printf("\n Please enter your choice from the following menu:\n");
        printf("A – Repopulate array \n");
        printf("B - Display all values \n");
        printf("C – Replace one number \n");
        printf("D – Calculate the mean \n");
        printf("E - Find largest number\n");
        printf("X - Exit the program \n");
        scanf("%c", &opt);
    
        opt = tolower(opt);
        if (opt == 'a') {
          for (i = 0; i < num; i = i + 1) { // reading 5 values from user and storing it in array
            printf(" Enter the value number %d\n\n", i + 1);
            scanf("%d", &a);
          }
          printf("The new array is : \n");
          for (i = 0; i < num; i++) {
            printf("%d\n", a);
          }
        } else if (opt == 'b') {
          printf("You choose to display all values \n\n");
          for (i = 0; i < num; i++) {
            printf("%d\n", a);
          }
        } else if (opt == 'c') {
          int ele;
          int val;
          printf("You choose to replace one number\n");
          printf("Which element of the array You want to replace ? \n");
          scanf("%d", &ele);
          printf("What is the replaced value ?");
          scanf("\n%d", &val);
          for (i = 0; i < 100; i++) {
            if (a == ele) {
              a = val;
            }
          }
          printf("%d", a);
        } else if (opt == 'd') {
          sum = 0;
          for (i = 0; i < num; ++i) {
            sum += a;
          }
          mean = sum / num;
          printf
              ("Mean = sum of  the elements devided on the number of elements\n = %.2f\n",
               mean);
        }
    
        else if (opt == 'x') {
          printf("Thank you for using the program");
          break;
        } else if (opt == 'e') {
          printf("You choosed to find the largest element  \n\n");
          // storing the largest number to arr[0]
          for (i = 0; i < num; ++i) {
            if (a[0] < a)
              a[0] = a;
          }
          printf("Largest element = %d\n", a[0]);
        } else {
          printf("Wrong menu option- try again\n");
        }
        while ((opt = getchar()) != '\n' && opt != EOF);
    
    
      }
    }
    Last edited by Salem; 05-24-2020 at 07:14 AM. Reason: Fixed crayola formatting

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    728
    You need to attempt to write the code yourself, then if you have problems, post the code so we can comment. We can't and don't write homework assignments for you.

    Please read the forum FAQ.

  3. #3
    Registered User
    Join Date
    Apr 2020
    Posts
    58
    What's a terminator you are talking about?

  4. #4
    Registered User
    Join Date
    May 2020
    Posts
    8
    i need to do all options with terminator in the loop i have no idea how to do this + option c is not working

  5. #5
    Registered User
    Join Date
    May 2020
    Posts
    8
    the same like character array has terminator i has to use terminator for inteteger.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,064
    > scanf("%d", &a);
    All your references to your array should have a subscript.
    As in
    scanf("%d", &a[i]);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    May 2020
    Posts
    8
    what do you mean sorry im beginner

  8. #8
    Registered User
    Join Date
    May 2020
    Posts
    8
    in option c ?

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,064
    No, there are 10 different places where you make the same mistake.
    Code:
    $ gcc -Wall -Wextra -c main.c
    main.c: In function ‘As5GradeB’:
    main.c:18:11: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int (*)[100]’ [-Wformat=]
         scanf("%d", &a);
               ^
    main.c:40:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int (*)[100]’ [-Wformat=]
             scanf("%d", &a);
                   ^
    main.c:44:16: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
             printf("%d\n", a);
                    ^
    main.c:49:16: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
             printf("%d\n", a);
                    ^
    main.c:60:15: warning: comparison between pointer and integer
             if (a == ele) {
                   ^
    main.c:61:13: error: assignment to expression with array type
               a = val;
                 ^
    main.c:64:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
           printf("%d", a);
                  ^
    main.c:68:13: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
             sum += a;
                 ^
    main.c:83:18: warning: comparison between pointer and integer
             if (a[0] < a)
                      ^
    main.c:84:16: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
               a[0] = a;
                    ^
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    May 2020
    Posts
    8
    Thank You i will change that , but what about this terminator how i can do this when user choosing the numbers ?

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,064
    I guess it would be something like this
    Code:
        if (opt == 'a') {
          for (i = 0; i < num; i = i + 1) { // reading 5 values from user and storing it in array
            printf(" Enter the value number %d\n\n", i + 1);
            scanf("%d", &a[i]);
          }
          a[i] = -1;  // I'll be back
        } else if (opt == 'b') {
          printf("You choose to display all values \n\n");
          // pretend we don't know what num is any more, but there is a terminator
          for (i = 0; a[i] != -1 ; i++) {
            printf("%d\n", a[i]);
          }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Apr 2019
    Posts
    47
    Does it have to be a terminator? I am experiencing the same problem with sending an array of structs. I ignore the first struct and start filling the array from array[1]. Then when done I put the total items of the array in array[0]. Then I don't have to check for a terminator, I have the number of items for a loop limit, and I can do this:
    Code:
    new_array = &array[1];
    Which allows me to use the array as normal. Just an idea.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,777
    Quote Originally Posted by Yonut View Post
    Does it have to be a terminator? I am experiencing the same problem with sending an array of structs. I ignore the first struct and start filling the array from array[1]. Then when done I put the total items of the array in array[0]. Then I don't have to check for a terminator, I have the number of items for a loop limit, and I can do this:
    Code:
    new_array = &array[1];
    Which allows me to use the array as normal. Just an idea.
    That's not a good idea: it means that you need a member in the struct object just for storing the number of items, and this member is uselessly repeated for all the struct objects even though most of them don't need it. Either that, or you reuse a suitable member, but that's code obfuscation.

    There are at least 4 better approaches:
    • The use of a sentinel value (terminator), which of course only makes sense if you can designate such a sentinel value (typically a pointer or some zero-initialised value; in the original poster's case it is a negative value because only the non-negative values are used as per normal)
    • Pass/keep track of the number of items in a separate variable
    • Pass/keep track of a pointer to one past the end of the array of items in a separate variable
    • Declare a struct to wrap the array of items and the number of items
    Last edited by laserlight; 05-24-2020 at 02:07 PM.
    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

  14. #14
    Registered User
    Join Date
    Apr 2019
    Posts
    47
    Quote Originally Posted by laserlight View Post
    That's not a good idea: it means that you need a member in the struct object just for storing the number of items, and this member is uselessly repeated for all the struct objects even though most of them don't need it.
    Are you thinking that there is a special field for this data? In the struct, there is an 'int' used for 'mode'. The first struct is informational an does not have a mode, so I use it to store to total of the items in the array. It is a field normally used for the remaining data.

    I did have it setup that way before (using separate variables) I started using a function pointer in my struct. There are 4 functions that can be executed using the function pointers, and for the most part, sending one struct as an argument instead of a struct and a title and an amount, helps the other functions that don't care about the title and amount.

    For instance, I have the main function that accepts the struct array. In the first struct is the title for what it is displaying and the amount of items that follow in the array. Then I can just send a struct as an argument. Now there is a function that requires the struct but not the information in the first element. It doesn't care about it. But if they were separate variables, I would need to include the following (to stop compiler from complaining):
    Code:
    if(title || amount)
             {;}
    I guess I thought that if the biggest use of the struct array has 3672 elements, sending 1 extra element wouldn't be that big of an overhead.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,777
    Quote Originally Posted by Yonut
    Are you thinking that there is a special field for this data? In the struct, there is an 'int' used for 'mode'. The first struct is informational an does not have a mode, so I use it to store to total of the items in the array. It is a field normally used for the remaining data.
    That's what I mean by "Either that, or you reuse a suitable member, but that's code obfuscation."

    Basically, instead of properly designing a way to convey the number of items, you're obfuscating your code by relying on implicit knowledge that a particular member that normally serves an entirely different purpose is now the number of items for that particular array element. Furthermore, this only works if there is such a member to begin with, otherwise the obfuscation is even worse because you'll have to reinterpret certain bytes of the first array element as an integer.

    EDIT:
    Quote Originally Posted by Yonut
    I did have it setup that way before (using separate variables) I started using a function pointer in my struct. There are 4 functions that can be executed using the function pointers, and for the most part, sending one struct as an argument instead of a struct and a title and an amount, helps the other functions that don't care about the title and amount.

    For instance, I have the main function that accepts the struct array. In the first struct is the title for what it is displaying and the amount of items that follow in the array. Then I can just send a struct as an argument. Now there is a function that requires the struct but not the information in the first element. It doesn't care about it. But if they were separate variables, I would need to include the following (to stop compiler from complaining):
    So what you should have done is something like this:
    Code:
    struct X
    {
        // ...
    };
    
    struct Container
    {
        char title[TITLE_SIZE];
        struct X xs[XS_SIZE];
        size_t xs_count;
    };
    
    // ...
    struct Container container;
    Now, you can pass a pointer to struct Container where you need it, or directly pass container.xs to functions that only need the array (but then you will probably also pass container.xs_count as if you need the array, you probably also need the count of the number of elements in use for the array).

    Having said that, I don't want to discourage you from using your idea in other contexts where it is not necessarily obfuscation. For example, if you were trying to write your own version of malloc, storing the number of bytes allocated just before the bytes that are actually allocated could be a reasonable strategy to allow for deallocation.

    Anyway, we have gone off topic from danlopek14q's discussion, so if you want to discuss this further, let's start a new topic.
    Last edited by laserlight; 05-25-2020 at 03:58 PM.
    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. integer null terminator
    By vead in forum C Programming
    Replies: 6
    Last Post: 02-11-2018, 08:42 PM
  2. function terminator
    By programmerc in forum C Programming
    Replies: 3
    Last Post: 02-17-2013, 08:08 AM
  3. array and string terminator
    By bobknows in forum C++ Programming
    Replies: 2
    Last Post: 03-08-2011, 07:45 PM
  4. Terminator 4
    By abachler in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 05-23-2009, 11:15 PM
  5. Terminator 3..nope
    By Nutshell in forum A Brief History of Cprogramming.com
    Replies: 30
    Last Post: 07-18-2003, 07:42 AM

Tags for this Thread