How to Reverse the String in C Using Arrays Without Traversing Multiple Times
- 1). Open your C source file in an editor, such as Microsoft Visual Studio.
- 2). Include the necessary C header files for the program by adding the following code at the top of your file:
#include "stdafx.h"
#include "stdio.h" // printf, scanf
#include "string.h" // strlen - 3). Declare and initialize the variables necessary for the program by adding the following code at the top of your main function:
char str[40];
int a, b, length;
char temp;
a=b=length=temp=0; - 4). Prompt the user for a string to reverse by adding the code:
printf("Enter a string: ");
scanf("%s", str); - 5). Loop through the string and reverse it by adding the code:
length=strlen(str);
for (a=0, b=length-1; a<=b; a++, b--)
{
temp = str[a];
str[a] = str[b];
str[b] = temp;
}
The loop accesses the first and last characters and swaps their values, using a temporary variable. It then advances one character in each direction, continuing to swap characters until it reaches the center of the string. - 6). Display the reversed string by adding the code:
printf("%s",str); - 7). Save the C file. Compile and run the program to reverse a string.