Home > Enterprise >  How to loop for a specific amount
How to loop for a specific amount

Time:01-19

I am writing a program that would iterate through a sequence of characters, where every 4 counts would add the iterated 4 characters into a char array which means that it must be able to constantly be updating every 4 counts.

For example,

The sequence: char sequence[32] = "qRiM1uOtGgXl5yuNPJwKo4 bAdQuPUbr";

I want a loop that would be able to get every four characters, which in this case the first 4 characters is "qRiM".

Then I would want it to be stored in a char array: char test[4]; (This must be able to print qRiM)

Then when 4 counts has been done then the cycle would repeat where the next 4 characters would be "1uOt"

I've tried to attempt this but it would only print out qRiM and that the test[4] array is not updating.

int count_steps = 0;
for (int i = 0; i < 32; i  ) {
    // Adds a character from a sequence into the test array until 4
    while(count_steps < 4) {
        test[i] = sequence[i];
        count_steps  ;
    }
    // Checks if four counts has been done
    if (count_steps == 4) {
        //decoder(test, decoded_test);

        // Prints out the four characters
        for(int j = 0; j < 4; j  ) {
            printf("%c\n", test[j]);
        }
        // Resets back to 0
        count_steps = 0;
    }
    else {
        continue;
    }
}

CodePudding user response:

With details explaination from torstenvl, you can rewrite code:

for (int i = 0; i < 32; i  ) {
    test[i%4] = sequence[i];

    if ((i 1) % 4 == 0) {
        printf("\n");
        for(int j = 0; j < 4; j  ) {
            printf("%c\n", test[j]);
        }
    }
}

CodePudding user response:

    test[i] = sequence[i];

This line assigns the ith entry in test to the ith entry in sequence. But test only has 4 entries, so on the second iteration, you are writing to test[4] throught test[7]. You need to use count_steps as the index in test.

You also need to add count_steps to i when accessing sequence so that the correct index in sequence is set in test.

And since you're adding processing 4 characters in each iteration of the for loop, you need to increment i by 4, not by 1

demo

for (int i = 0; i < 32; i  = 4/* increment by 4 */) {
    // Adds a character from a sequence into the test array until 4
    while(count_steps < 4) {
        test[count_steps] = sequence[i   count_steps]; // use count_steps as index in test and offset in sequence
        count_steps  ;
    }
    ...
}
  • Related