Thursday, January 3, 2013

Handling more functions in C++ arrays


Arrays are not just used to store and retrieve values you want. It provides more properties to work with it easily.

How to use strlen() and strcpy() functions in arrays?


Target 1 :-

  1. store the String "Computer System" in an array called name
  2. print it in the reverse order 
  3. copy the name array to a new array called reveres
  4. print the reverse array


#include<iostream>
#include<cstring>                              //functions to handle strings are stored in this library                                  
using namespace std;
int main()
{
 //store the string in a char array (character by character is stored in name now) it's size will be 15
char name[]="Computer System";   
char revers[15];     //this array is to store the reverse of the string

int size=strlen(name);        //strlen() function will return the size of the name array

for(int i=size-1;i>=0;i--)    //for loop traverse the index from size-1 to 0 (back to front)
{
cout<<name[i]; //print the letter in the ith position
}
cout<<endl;

//copy the name array to the reverse array and display
cout<<"copy of reverse array:"<<strcpy(revers,name)<<endl;     

return 0;
}


learn the strcpy() and the strlen() functions from the above code that can be used to copy one array to another and to get the length of an array respectively. Also note that you must include the cstring library to use those functions.

How to use strcmp() function in arrays?

Target 2:-

  1. let the use enter two strings one after the other
  2. compare the two strings and display as,
    • string 1 and string 2 are same
    • alphabetically string 1 comes before string 2
    • alphabetically string 1 comes after string 2


Source Code :-


#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char array_1[20];
char array_2[20];

cout<<"Enter a Word for Array1:"<<endl;
cin>>array_1;

cout<<"Enter a Word for Array2:"<<endl;
cin>>array_2;

int compare=strcmp(array_1,array_2);

if(compare==0)
cout<<"word 1 is same as word 2"<<endl;

else if(compare<0)
cout<<"alphabatically "<<array_1<<" comes before "<<array_2<<endl;

else 
cout<<"alphabatically "<<array_2<<" comes before "<<array_1<<endl;

return 0;
}



According to the above code, you have to understand that when passing two strings to strcmp() function as

strcmp(array_1,array_2)

  • it returns 0 if both if them are same
  • it returns a positive value if array_2 alphabetically is greater than array_1
  • it returns a negative value if array_1 alphabetically is greater than array_2