Output C String Characters: Techniques & Examples

In C language, strings can be seen as arrays of characters and can be outputted character by character. Here are some common methods:

  1. Iterate through each character of the string using a for loop and output them one by one by using an index.
#include <stdio.h>

int main() {
    char str[] = "Hello";
    int i;

    for (i = 0; str[i] != '\0'; i++) {
        printf("%c\n", str[i]);
    }

    return 0;
}
  1. Using pointers: Traverse each character of the string with a pointer and output them one by one using the pointer.
#include <stdio.h>

int main() {
    char str[] = "Hello";
    char *ptr = str;

    while (*ptr != '\0') {
        printf("%c\n", *ptr);
        ptr++;
    }

    return 0;
}

Characters in a string can be output one by one, whether using loops and indexes or using pointers.

bannerAds