C Online Compiler
Example: Reverse String Manually in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Reverse String Manually #include <stdio.h> #include <string.h> // Required for strlen #include <stdlib.h> // Required for malloc and free (if dynamic allocation used) // Function to reverse a string manually void reverseString(char* str) { int length = strlen(str); int start = 0; int end = length - 1; char temp; while (start < end) { // Step 1: Swap characters at start and end positions temp = str[start]; str[start] = str[end]; str[end] = temp; // Step 2: Move pointers towards the center start++; end--; } } int main() { // Example 1: Static string char str1[] = "programming"; printf("Original string 1: %s\n", str1); reverseString(str1); printf("Reversed string 1: %s\n", str1); printf("\n"); // Example 2: Dynamically allocated string char* str2 = (char*)malloc(sizeof(char) * 20); // Allocate memory for up to 19 chars + null if (str2 == NULL) { printf("Memory allocation failed!\n"); return 1; } strcpy(str2, "C language"); // Copy content into allocated memory printf("Original string 2: %s\n", str2); reverseString(str2); printf("Reversed string 2: %s\n", str2); free(str2); // Free dynamically allocated memory str2 = NULL; return 0; }
Output
Clear
ADVERTISEMENTS