How to work with a variable number of variables in C?

I think you can do this with a fixed number of variables. Like

int p, a, ans=1;
scanf("%d", &p); //read number

for(int r=0; r<p; ++r)
{
    scanf("%d", &a);
    if(a==0)
    {
        ans=0;
        break;
    }
}   
printf("\nAnswer is: %d", ans);

ans variable holds the answer. First you read the number of ints into p and then read p number of ints using a loop.

During each iteration of the loop, you read into the same variable a. You just need to know if at least a single input is zero.

ans is initially set to 1 and is changed to 0 only if a zero is input. If zero is input, the control exits the loop immediately because of the break statement.

You may want to check the return value of scanf() and other error checking.

Various ways to use an unknown number of variables is mentioned in the comments.

If you can use C99, variable length array are allowed. Like

int p;
scanf("%d", &p);
int arr[p];

If dynamic memory allocation is used, you could use malloc() or calloc() which are in stdlib.h.

See this.


And the pointer k in

    for (n=0; n<p; n++){
        int a;
        scanf ("%d", &a);
        int *k=&a;
    }
    for (n=0; n<p; n++){
        int a=*k;
        if (a==0)
            i=0;
        else i=1;
    }

is a local variable of the first loop and is hence visible only to that loop and is invisible to the second loop. k‘s scope is limited to the first loop. See this.

If you want a variable to be visible in both the loops, declare it outside both.

Leave a Comment