Variable doesn't get updated when I run a loop

52 Views Asked by At

I want to iterate through a word and print each of its characters, together with its ASCII number.

I've tried

#include <iostream>
#include <stdio.h>

using std::cout;

int main()
{
    char cWord[30] = {"Larissa"};
    int iCounter = 0;
    char cLetter = cWord[iCounter];

    for (iCounter = 0; iCounter < 5; iCounter++) {
        printf("%c == %d \n", cLetter, cLetter);
    }
}

but that just prints L == 76 five times. I suppose that means the cLetter variable doesn't update as I run the for loop, but I don't understand why.

2

There are 2 best solutions below

0
yano On

You need to update cLetter in the loop, there's no magic connection to earlier code. Might as well move cLetters scope to inside the loop as well. Try

for (iCounter = 0; iCounter < 5; iCounter++) {
        char cLetter = cWord[iCounter];
        printf("%c == %d \n", cLetter, cLetter);
    }

Here, iCounter is updated each iteration, and therefore cLetter is too.

0
Naz On

You're only assigning cLetter once, outside of the loop, so it remains constant throughout the loop iterations.