Change the alternate character of a string in upper case

Input:

this is a string 

Output:

ThIs Is A sTrInG 

The logic I've used to make this program is pretty simple. But it is working only to a certain extent.

int main()
{
    int i,j;
    char s[100];
    printf("Enter a sentence\n");
    gets(s);

    printf("The sentence now is\n\n");
    i=0;
    j=i;
    while(s[i] != '\0')
    {
        if(j%2==0)
        {
            s[i] = s[i]-32;
        }
        if(s[i] == ' ')
        {
            if(j%2==0)
            {
                s[i] = s[i]-32;
            }
        }
        i++;
        j++;
    }
    puts(s);

}  

For the above program,

Input:

this is a string  

Output:

ThIs  

Where did I go wrong?

1 answer

  • answered 2018-05-16 04:44 MFisherKDX

    A space has ASCII code 32. So these lines

    if(j%2==0)
    {
        s[i] = s[i]-32;
    }
    

    turn your even indexed spaces into the null character (a zero) effectively terminating your string.