Alex Alex - 2 months ago 4
C Question

Turning my array into a function and making 2nd function to print it

Im trying to create a program that has 2 options, view and compute. Right now im trying to figure how to turn my array where i will input my values into a function, so i can go in and out several times to store the values. I also want to view to be a function where i can view the values several times.

i've managed to get the computing part to work in my main, now i need to turn it into a function. Secondly how do i create a second function to view it?

My code is a bit mess please bear with me.

#include <stdio.h>

int printArray();

int main(void)
{

char option;

printf("Press V to view and C to input"); // My main menu
scanf("%c", &option); // here it should store the input

int arrayTable[10] = {0}; // turn this into function
int iValue = 0;
int i = 0;

while(i < 10)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &iValue); // input iValue

if (!iValue) // if iValue is zero then exit loop without affecting array with this value
break;
else
{
arrayTable[i] = iValue; // if the value is non-zero store it in array and continue
i++;
}
}

printf("Your input: %d", printArray); // if i select V for view

return 0;
}

int printArray() // here i should be the print function
{
int i;
for (i = 0; i < j; i++)
{
printf("%d", );
p++;
}
}

Answer

Alex, continuing from your last comment, to display a menu that will allow you to add values to your array, delete values from your array and view the array (along with the max, min and average of the values), can do something similar to the following. Note: the command line isn't a windowed user interface, so your menu operations are more like a printed receipt of your transactions with it. (you can do nice text windows and stationary menus, but that generally requires an text library, such as ncurses which is well beyond the scope of your question.

As explained in the comment, your basic approach is simply to create a loop that repeats continually. It will display your menu and allow you to enter your selection from a list, e.g.:

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: 

After the user enters the selection, to make the comparison easier, the user's input in converted to lower-case. Also note, that the input is read as a string using fgets (a line-oriented input function) which makes taking user input much easier than having to worry about whether the '\n' remains in the input buffer (stdin) just waiting to cause problems for your next input. (you can use the scanf family of functions, but YOU are the one responsible for accounting for each character entered by the user (and emptying the input buffer).

Reading input with fgets will read up to and including the '\n', so their is no chance of the '\n' being left unread in stdin. Also note that fgets will read a string or characters, where you are only interested in the first. That is easily handled simply by referencing the first character in the buffer. (e.g. if you are reading user-input into a buffer called buf, you can simply use buf[0] to access the first character, or simply *buf for that matter)

After the user input is read, the first character is passed to a switch statement, where each case of the statement is compared against the first character. If the character matches a case, then the actions associated with that case are taken, ending with the break (you can read about fall-through processing if the break is omitted on your own)

As mentioned in the comment, if you simply need to break out of one loop, then break is all you need. However here, your switch statement is inside the loop. A single break will only get you out of the switch but not the outside for loop. To break out of nested loops, use the goto statement. (you could also add more variables and set some type of exit flag, but why? This is what the goto was meant to do. (there are some cases where a flag is equally good as well)

In each case within the switch, you are free to call whatever code is needed to handle that menu selection. You will note we simply call short helper functions from within the switch to print the array, insert values, remove values, etc. You can put all the code in the switch if you like, it just rapidly become unreadable.

Putting that altogether, you can do something like the following:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>

enum { MAXN = 64 };  /* constant - max numbers of vals & chars */

void showmenu ();
void prnarray (int *a, int n);
int addvalue (int *a, int n, int newval);
int delvalue (int *a, int n, int index);
int minvalue (int *a, int n);
int maxvalue (int *a, int n);
int sumvalues (int *a, int n);

int main (void) {

    int vals[MAXN] = { 21, 18, 32, 3, 9, 6, 16 }, /* the array */
        n = 7;

    for (;;) {  /* loop until user quits or cancels, e.g. ctrl+d */

        showmenu();                         /* show the menu */

        char buf[MAXN] = "";
        fgets (buf, MAXN, stdin);           /* read user input */
        /* convert to lower-case for comparison of all entries */
        switch (tolower (buf[0])) {         /* 1st char is entry */
            case 'p' :  prnarray(vals, n);
                        break;
            case 'i' :  printf ("\n enter the new value: ");
                        if (fgets (buf, MAXN, stdin) &&
                            isdigit (buf[0])) {
                            n = addvalue (vals, n, atoi (buf));
                        }
                        break;
            case 'd' :  printf ("\n enter the index to delete: ");
                        if (fgets (buf, MAXN, stdin) &&
                            isdigit (buf[0])) {
                            n = delvalue (vals, n, atoi (buf));
                        }
                        break;
            case 'n' :  printf ("\n Mininum of '%d' values is : %d\n",
                                n, minvalue (vals, n));
                        break;
            case 'x' :  printf ("\n Maxinum of '%d' values is : %d\n",
                                n, maxvalue (vals, n));
                        break;
            case 'a' :  printf ("\n Average of '%d' values is : %.2lf\n",
                                n, (double)sumvalues (vals, n)/n);
                        break;
            case 's' :  printf ("\n Sum of '%d' values is : %d\n",
                                n, sumvalues (vals, n));
                        break;
            case 'q' :  printf (" that's all folks...\n");
                        goto done; 
            default  :  if (!buf[0]) {  /* check for manual EOF */
                            putchar ('\n');  /* tidy up */
                            goto done;
                        }
                        fprintf (stderr, "error: invalid selection.\n");
        }
    }
    done:;  /* goto label - breaking 'for' and 'switch' */

    return 0;
}

void showmenu ()
{
    fprintf(stderr, "\n ======== Program Menu =========\n\n"
                    "  V)  View the Array.\n"
                    "  I)  Insert New Value.\n"
                    "  D)  Delete Existing Value.\n"
                    "  N)  Display Minimum Value.\n"
                    "  X)  Display Maximum Value.\n"
                    "  A)  Display Average of Values.\n"
                    "  S)  Display Sum of Values.\n"
                    "\n"
                    "  Q) Quit.\n"
                    "\n"
                    " Selection: ");
}

void prnarray (int *a, int n)
{
    int i;

    printf ("\n there are '%d' values in the array:\n\n", n);

    for (i = 0; i < n; i++)
        printf (" array[%2d] : %d\n", i, a[i]);
}

int addvalue (int *a, int n, int newval)
{
    if (n == MAXN) {
        fprintf (stderr, "error: all '%d' values filled.\n", n);
        return n;
    }
    a[n++] = newval;

    return n;
}

int delvalue (int *a, int n, int index)
{
    if (index < 0 || index > n - 1) {
        fprintf (stderr, "error: index out of range.\n");
        return n;
    }

    int i;

    for (i = index + 1; i < n; i++)
        a[i-1] = a[i];
    a[i] = 0;

    return --n;
}

int minvalue (int *a, int n)
{
    int i, min = INT_MAX;
    for (i = 0; i < n; i++)
        if (a[i] < min)
            min = a[i];

    return min;
}

int maxvalue (int *a, int n)
{
    int i, max = INT_MIN;
    for (i = 0; i < n; i++)
        if (a[i] > max)
            max = a[i];

    return max;
}

int sumvalues (int *a, int n)
{
    int i, sum = 0;
    for (i = 0; i < n; i++)
        sum += a[i];

    return sum;
}

(note: there are always additional validation checks you can add to test whether you have read all the input the user provided, etc.. But given the crux of your question I'll leave that learning to you)

Example Use/Output

$ ./bin/menusimple

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: v

 there are '7' values in the array:

 array[ 0] : 21
 array[ 1] : 18
 array[ 2] : 32
 array[ 3] : 3
 array[ 4] : 9
 array[ 5] : 6
 array[ 6] : 16

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: i

 enter the new value: 77

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: v

 there are '8' values in the array:

 array[ 0] : 21
 array[ 1] : 18
 array[ 2] : 32
 array[ 3] : 3
 array[ 4] : 9
 array[ 5] : 6
 array[ 6] : 16
 array[ 7] : 77

Look things over and let me know if you have any questions. Also, as you are just learning, make sure you are compiling your code with compiler warnings enabled and that you don't consider your code reliable until it compiles without warning. That means you should be compiling with at least the -Wall -Wextra flags set. If you are using gcc and the command line, then it would be:

gcc -Wall -Wextra -O2 -o simplemenu simplemenu.c

To compile the code in simplemenu.c into an executable named simplemenu with the -O2 optimizations applied. If you are really wanting to eliminate all warnings, add -pedantic as well. For codeblock or other IDE, look through the compiler menu options, they all provide a place to input all of the options you would like. Good luck with your code.

Comments