Home > Back-end >  i am trying to convert characters in a string from capital letter to small letter using for loop.it&
i am trying to convert characters in a string from capital letter to small letter using for loop.it&

Time:07-07

i cannot find any error in the code

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

int main(void) {

    char a[50];
    int i;

    setbuf(stdout,NULL);

    printf("enter a string");

    gets(a);

    for(i=0;a[i]<='\0';i  ){
        if(a[i]>='A'&&a[i]<='Z'){
            a[i]=a[i] 32;
        }
    }

    printf("%s",a);

    return EXIT_SUCCESS;
}

output

enter a string SDJnjj SDJnjj

CodePudding user response:

Your whole for loop is skipped, character '\0' is zero, any printable string you enter won't have characters less than zero. Instead, change the condition to !=:

for(i=0; a[i]!='\0'; i  ){ ... }

or simply a[i] since 0 evaluates to false in C

for(i=0; a[i]; i  ){ ... }

Also, never use gets, it creates a security vulnerability for buffer overflows, use fgets instead.

Furthermore, there's already a function that does this for you called tolower. It is the preferred method if you're allowed to use it:

#include <ctype.h>
...

for(i=0;a[i];i  ){
    a[i]=tolower(a[i]);
}
  • Related