C++ program to print the characters of a string using pointer

C++ program to print the characters of a string using pointer:

In this post, we will learn how to print the characters of a string using pointer. We will use a character array to hold the string and using a character pointer, we will print the contents of the array.

How to access the characters using pointer:

Let’s take a look at the below example.

#include <iostream>
using namespace std;

int main()
{
  char word[] = "Hello World";

  char *wordPointer = word;

  cout<<wordPointer<<endl;
  cout<<wordPointer[1]<<endl;
 
}

In this example, we have created a character array word that holds the string Hello World. wordPointer is a character pointer and we are assigning word to it.

So, wordPointer is pointing to word.

The last two lines are printing the value of wordPointer and also we are trying to access the second character of word using wordPointer.

If you run this program, it will give the below output:

Hello World
e

Now, if you want to read the characters of the string using the pointer variable, you can do it as like below:

#include <iostream>
using namespace std;

int main()
{
  char word[] = "Hello World";

  char *wordPointer = word;

  cout<<*wordPointer<<endl;
  
  wordPointer += 1;
  
  cout<<*wordPointer<<endl;
 
}

It will print:

H
e

*wordPointer prints the first character. We added 1 to the pointer and then it printed the second character.

Use a loop to iterate through the characters and print them:

We can use a loop to iterate through the characters one by one and print them using pointer as like below:

#include <iostream>
using namespace std;

int main()
{
  char word[] = "Hello World";

  for(char *wordPointer = word;*wordPointer != NULL; *wordPointer++){
    cout<<*wordPointer<<endl;   
  }
 
}

The for loop runs till the value of wordPointer is not NULL. It increments its value by 1 on each step. If you run this program, it will print all characters in a new line:

H
e
l
l
o
 
W
o
r
l
d

We can also write this program using a while loop:

#include <iostream>
using namespace std;

int main()
{
  char word[] = "Hello World";
  char *wordPointer = word;

  while(*wordPointer != NULL){
    cout<<*wordPointer<<endl;
    *wordPointer++;
  }
 
}

It will print the same output.

You might also like: