0

Is it possible to automate this program more in order to change the variable number?

    for (i = 1; i < 4; i++)
    {
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &CodeNumber1);
    printf("Enter the Price for Item #%d: ",i);
    scanf("%f", &Price1);
    printf("Enter the Quantity for Item #%d: ", i);
    scanf("%d", &Quantity1);
    }

So where the variable has 1 written, would it be possible to replace it with i?

Without using an array

VallyMan
  • 135
  • 5
  • 1
    Take a look at this: https://stackoverflow.com/questions/10468128/how-do-you-make-an-array-of-structs-in-c – Fabio_MO May 02 '18 at 13:02
  • I'd say no. What are you trying to achieve. This might be an [XY Problem](http://xyproblem.info). What's wrong with using an array? You definitely need one here. – Jabberwocky May 02 '18 at 13:02
  • 1
    Normally the 1 should be replaced by `[i]` or similar, but for some secret reason you don't want to use arrays. – Gerhardh May 02 '18 at 13:04
  • I wanted to see if it'd be possible doing it without an array, thanks though guys, il use an array – VallyMan May 02 '18 at 13:06
  • when calling any of the `scanf()` family of functions: 1) always check the returned value (not the parameter values) to assure the operation was successful. – user3629249 May 04 '18 at 09:46

3 Answers3

3

You could use arrays instead of a fix name. For example you could use something like

int CodeNumber[4] = {0};
for (i = 0; i < 4; i++)
{
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &CodeNumber[i]);
}

In my opinion an even better approach would be to use structs that hold your 3 integers inside:

struct item {
  int CodeNumber;
  int ...
}

And then use it like this:

struct item myItem[4];
for (i = 0; i < 4; i++)
{
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &(myItem[i].CodeNumber));
    ...
}
izlin
  • 2,129
  • 24
  • 30
3

Without an array? Challenge accepted. Good thing Boost.Preprocessor also works with C!

#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/cat.hpp>

#define LOOP_BODY(z, n, data) \
    printf("Enter the Code for Item #%d: ", n); \
    scanf("%d", &BOOST_PP_CAT(CodeNumber, n)); \
    printf("Enter the Price for Item #%d: ", n); \
    scanf("%f", &BOOST_PP_CAT(Price, n)); \
    printf("Enter the Quantity for Item #%d: ", n); \
    scanf("%d", &BOOST_PP_CAT(Quantity, n));

BOOST_PP_REPEAT_FROM_TO(1, 4, LOOP_BODY, ~)

I am not to be held responsible for any loss of personal or professional reputation, pride, life, limb; or the happenstance of any kind of apocalypse resulting from the use of the code above.

Quentin
  • 62,093
  • 7
  • 131
  • 191
0

You should use an array to hold your variables, like so :

int data[4] = {0};
for(unsigned int i = 0; i < 4; i++) {
    printf("Enter the data for item #%d: ",i);
    scanf("%d", &data[i]);
}
Magix
  • 4,989
  • 7
  • 26
  • 50