Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

2 variable for loop allowed in C?

In C is it allowed to use 2 variables in one line of a for loop?
This code does not compile.

#include<stdio.h>
int main(){
    int arr[3][4]={
    {0,3,5,2}, 
    {2,13,4,6},
    {7,33,12,5} 
    };

    int i,j;
    for (i=0,j=0;i++,j++;i<3, j<4){
        printf("%d ", arr[i][j]);
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It is OK to have as many variables as you wish in the for loop. The only problem with for (i=0,j=0;i++,j++;i<3, j<4) that the conditions are in the wrong place and you should use a logical operator as comma will simply take into account the last comparison.

for (i=0,j=0; i<3 && j<4;i++,j++)

Bear in mind that both variables will increment at the same time and it will not create two loops. So your loop will stop execute when i is equal to 3

int main(void)
{
    for (int i=0, j=0; i<3 && j<4;i++,j++)
    {
        printf("i = %d, j = %d\n", i, j);
    }
}

Result:

i = 0, j = 0
i = 1, j = 1
i = 2, j = 2

https://godbolt.org/z/P5oxsr9Wf

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading