character array

Sequence of characters is called string and the character array is like a collection of character or a sequence of character, which means the character array is used for the string related task. The character array is declared like int and float data type.

SYNTEX:-

storage_class char array_name[size];

The character array and the other array only differ only. The character array always terminates with the NULL character while the array is not such a condition.

Example:-

char name[6]="Rahul"; 

or

char name= {'R','a','h','u','l'};

such as,

character-array

Here we have declared size of array (name) 6, but it will only store the value upto 5 characters. last space NULL character reserves.

 

initialization of character array

SYNTEX:-

storage_class char array_name[size]= {list, '\0'};
char name[]= { 'R', 'a', 'h', 'u', 'l', '\0'};

or

storage_class char array_name[size]= {list};
char name[] = "Rahul";

Here in below program, firstly we print the first string while in second string, we calculate string length, both operation are possible using array of character,

#include<iostream.h>
#include<conio.h>
void main()
{
  int i,len=0;
  // character array declaration
  char first[6]="Rahul";

  char sec[]={'S','h','e','r','m','a','\0'};
  clrscr();
  
   cout<<"First String : ";
  for(i= 0; first[i]!='\0'; i++)            // displaying character using loop
  {
     cout<<first[i]; // displaying first string
  }
 
   cout<<"\nSecond String: "<<sec;
  for(i= 0; sec[i]!='\0'; i++)
  {
     len++; // calculate second string length
  }
  
   cout<<"\nSecond string length: "<<len++;
  
  getch();
}
OUTPUT:-
First String : Rahul

Second String: Sherma

Second string length: 6

 

Similarly in two-dimensional array –

char name[3][4];
char name[2][3]={ "one", "two", "three", "four", "five"};

as we can see in above program, It is a bit difficult to do a relative task with string, so there is already a defined library function to perform string related task in C++.

Here is an example of character array where we get the ASCII code of name which is given by the user, 

 

To find ASCII code of a name given by user using character array

#include<iostream.h>
#include<conio.h>

void main()
{
  clrscr();
  char n[30];

   cout<<"Enter your name: ";
  cin>>n;

   for(int i=0;n[i]!='\0';i++)
    {
      cout<<n[i]<<"\t";   // print name
    }
 
  cout<<endl;

   for(int j=0;n[j]!='\0';j++)
    {
      cout<<int(n[j])<<"\t";  // print ascii value
    }

 getch();
}
OUTPUT:-
1st RUN:
Enter your name: rohit
r	o	h	i	t	
114	111	104	105	116

2nd RUN:
Enter your name: ROHIT
R	O	H	I	T	
82	79	72	73	84

explanation:

Here program executed twice, so you can understand ASCII code will different, doesn’t matter that entered string is same.

For more about ASCII code check found ascii code in C++


previous-array and their types

next-Structure in C++