Wim Van de Velde
Wim Van de Velde

Reputation: 3

For loop ignores test expression

i am a novice c programmer and i have a problem with my for loop in my program , the loop creates letter 'A' to 'Z' in a char "letter" but my loop does not stop at the letter 'Z' it just keeps going indefinitely,can someone help me?

Thanks in advance

#include <stdio.h>
#include <stdlib.h>

FILE * fptr;

int main()
{
    char letter;
    int i;

    fptr = fopen("C:\\Users\\Wim\\Documents\\C\\random read write to                      
       file\\letters.txt", "w+");

    if (fptr == 0)
    {
        printf("There was a error while opening the file! ");
        exit(1);
    }

    for (letter = 'A'; letter <= 'Z'; letter++)//This is the offending part of the code!
    {
        fputc(letter, fptr);
    }

    puts ("You just wrote the letters A through Z");

    fseek(fptr, -1, SEEK_END);
    printf("Here is the file backwards :\n");

    for (i= 26; i > 0;i++)
    {
        letter = fgetc(fptr);
        fseek(fptr, -2, SEEK_CUR);
        printf("The next letter is %c .\n", letter);
    }

    fclose(fptr);

    return 0;

}

Upvotes: 0

Views: 57

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

This loop

for (i= 26; i > 0;i++)

is wrong. There has to be

for ( i= 26; i > 0; i-- )

Also I would write this loop the following way

for ( i = 'Z' - 'A' + 1; i > 0; i-- )

Upvotes: 3

Related Questions