OneBite.Dev - Coding blog in a bite size

loop through each character in a string in C

Code snippet on how to loop through each character in a string in C

  int main() 
  { 
    char str[] = "GeeksForGeeks"; 
    int i; 
  
    // Loop through each character of the string  
    // and print it on the screen  
    for (i = 0; str[i] != '\0'; ++i)  
    { 
        printf("%c", str[i]); 
    } 
  
    return 0; 
  } 

This code begins with the int main() function called. The following line declares a character array with string “GeeksForGeeks” in it. The third line declares an integer value i. The fourth line starts a for loop, which will loop from 0 to the length of the string and executes the code within its block. Inside the for loop we are printing out the characters of the string one by one using the printf statement. The for loop terminates when the value of index i is between the length of the string. At the end program returns zero, which indicates successful completion of the program.

c