different variables in each for loop in C language
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?
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.