C program to print each character of a string

In this example, we will emphasize on use of strings in c programming. We use strings to hold set of characters that can be sentence or word.

So here we will get a string through user input and then try to print that string character by character.

We are not printing string as whole rather character by character so that means we will store input in an array of characters and then based on indexed position the characters will be printed on screen.

Pre-requisites:

Input output functions, strings, array, for loop

Approach:

First we will get the user input that can be word or sentence i.e. string and then hold that one into an array.

Once we are done with first step then we have to make use of loop so that we can iterate through array index by index and then capture each character at particular index position in an array.

For example, when we store a word in an array of size 5 then array can be referenced based on index position from 0 to 4 i.e. word will be stored in an array character by character starting from index position 0 to 4.

We will make use of for loop and iterate through loop array size times so till last character of array is not reached loop will continue to iterate.

To print each character, we will use %c format specifier inside printf() function and put address consisting the index position e.g. array[0],array[1],.. so on.

Step by step approach:

First you must declare character array, say CharArr[8] and read input using scanf() function into array.

Also declare counter variable i to use in for loop to iterate loop till string’s last character i.e. how many times loop should iterate to print all characters?

Use sizeof operator to find out size of CharArr i.e. string input and set it as limit in for loop and increment counter variable i.

Inside for loop, Make use of %c format specifier to print each character through printf() function and after format specifier give address of each character in string by putting value in i inside index in rectangle bracket after character array i.e. CharArr[index]. Here i will have values from 0 to size of array so compiler will read it as CharArr[0], .. so on..

Program:

Output:

2 thoughts on “C program to print each character of a string”

Leave a Reply

%d bloggers like this: