0

I want my loop to inlcude different variables every time it starts from beggining. It should be like this:

int a1, a2, a3;
...
...
for (i = 1; i<=10; i++)
{
a**i**
}

I just want to change variables in loop basing on i which increases by 1 every time. How to do thing like this?

3

1 Answer 1

3

You can put the 3 int variables into an array, and go through all elements of the array in a loop, accessing one element of the array per loop iteration. In every loop iteration, you can do something with the array element, for example print it using printf.

Here is an example program:

#include <stdio.h>

int main( void )
{
    //declare and initialize 3 "int" variables in an array
    int a[3] = { 10, 11, 12 };

    //go through the entire array in a loop, printing one
    //element per loop iteration
    for ( int i = 0; i < 3; i++ )
    {
        printf( "%d\n", a[i] );
    }

    return 0;
}

This program has the following output:

10
11
12

If you instead want to keep the 3 int variables as separate entities, then you could instead create an array of pointers, where each pointer points to one of these int variables, and use that array of pointers in the loop:

#include <stdio.h>

int main( void )
{
    //declare and initialize 3 separate "int" variables
    int a1 = 10, a2 = 11, a3 = 12;

    //create and initialize array of pointers to 
    //these "int" variables
    int *pointers[3] = { &a1, &a2, &a3 };

    for ( int i = 0; i < 3; i++ )
    {
        printf( "%d\n", *pointers[i] );
    }

    return 0;
}

This program has exactly the same output as the other program.

Sign up to request clarification or add additional context in comments.

3 Comments

is that possible to put variables into array (or their pointers)? for example #include <stdio.h> int main( void ) {     int *ptr, *ptr2, b1, b2; ptr = &b1 ptr2 = &b2     int a[3] = { ptr, ptr2};     //go through the entire array in a loop, printing one     //element per loop iteration     for ( int i = 0; i < 3; i++ )     {         printf( "%d\n", a[i] );     }     return 0; }
@xantico: I have added a second code example to my answer, which keeps the 3 separate int variables, and uses an array of pointers instead. Is that what you are looking for?
That's exactly what I was looking for. Thank you a lot <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.