Reversing a null terminated string – CSKC
Sign In

Search

Code Learning #CPP#2621    siteicon   siteicon  

Reversing a null terminated string

Reversing the original string given by the user and then printing it.

Learning Objectives

  • Reversal of string which is based on a char array.
  • Reversal concept using mid-point based flipping.
  • Char variable swapping using intermediate variable.

Source Code

TC++ #2621

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

Code Understanding

char str[80]; cout<<“Input String to Be Reversed : ” ; cin.getline(str,80);
String is collected in char array str.

int len = strlen(str); //The string length is calculated using the function for loop traversing
char temp; //A temp variable is declared which will help to keep data while reversal swapping
for(int i=0; i<len/2; i++)
The reversal loop will be traversed till mid point only as for reversal swapping of variables till mid point is sufficient.
{
temp=str[i]; str[i]=str[len-i-1]; str[len-i-1]=temp;
This is standard array reversal procedure as explained in #2506
}
cout <<str<<endl; //The reversed entry is printed.

Notes

  • The reversal logic here uses the reversal of individual characters. This reversal situation applies to any data type, char, int, long, float, double etc. as long as they are in an array.

Common Errors


Suggested Filename(s): str-rev.cpp



Share

Created: 13-Jan-2018 22:25 | Updated: 20-Jan-2018 15:21|