Write a C Program to Print Characters in a String using For loop, and while with a practical example.
C Program to Print Characters in a String Example 1
This program allows the user to enter a string (or character array). Next, we used While Loop to iterate each character inside a string. Inside this, we used the printf statement to print characters in this string.
/* C Program to Print Characters in a String */
#include <stdio.h>
int main()
{
char str[100];
int i = 0;
printf("\n Please Enter any String : ");
scanf("%s", str);
while (str[i] != '\0')
{
printf("The Character at %d Index Position = %c \n", i, str[i]);
i++;
}
return 0;
}

str[] = hello
While Loop First Iteration: while(str[i] != ‘\0’)
The condition is True because str[0] = h. So, the C Programming compiler will execute the printf statement.
Second Iteration: while(str[1] != ‘\0’)
The condition while(e != ‘\0’) is True. So, e will print
Do the same for the remaining While Loop iterations.
C Program to display Characters in a String Example 2
This string Characters program is same as above. Here, we just replaced the while loop with For Loop.
/* C Program to Print Characters in a String */
#include <stdio.h>
int main()
{
char str[100];
printf("\n Please Enter any String : ");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++)
{
printf("The Character at %d Index Position = %c \n", i, str[i]);
}
return 0;
}
Please Enter any String : python
The Character at 0 Index Position = p
The Character at 1 Index Position = y
The Character at 2 Index Position = t
The Character at 3 Index Position = h
The Character at 4 Index Position = o
The Character at 5 Index Position = n