Home > other >  C programming constantly updating variable in for loop
C programming constantly updating variable in for loop

Time:08-10

I am learning to code and I face an issue regarding undeclared variables in the for loop. Any feedback or suggestions will be greatly appreciated.

I have provided a T and an R value as shown in the code below. However, by trying to add a for loop, the variable becomes undeclared. I would like to compare the value of T0 T1 T2 to T7 using a for loop with the Ti variable. How do I include the Ti variable so that the i constantly change according to the for loop?

int T0=0, T1=1, T2=1, T3=0, T4=0, T5=1, T6=1, T7=0;

int R0=0, R1=0, R2=1, R3=0, R4=1, R5=1, R6=0, R7=0;

int j=0;
int r;

for (int i=0; i<8; i  )
{
    if (Ti==1)
    {
        r = Ri;
        j  ;
    }
    else
        i  ;

   printf("The output for r is %d", r);
}

CodePudding user response:

First of all, you need to use an array instead of these variables like T1, T2, ..., etc. As T0, T1 are considered as variables and as per rule for the identifiers declaration this is wrong way. The compiler is using Ti as a variable and showing error, that it is undeclared.

Additionally, there will be a path through your loop that does not write into r, if all elements of T[] are not equal to 1, given that you change it somewhen. Better initialize r.

I have attached a working code below:

#include <stdio.h>

int main(void) {
    int T[8] = { 0, 1, 1, 0, 0, 1, 1, 0 };
    int R[8] = { 0, 0, 1, 0, 1, 1, 0, 0 };
    int j = 0;
    int r = 0;

    for (int i = 0; i < 8; i  ) {
        if (T[i] == 1) {
            r = R[i];
            j  ;
        }
        else {
            i  ;
        }

        printf("The output for r is %d\n", r);
    }
    return 0;
}

Your idea for solving the problem as a beginner is truly appreciable. Keep it up.

  •  Tags:  
  • c
  • Related