I have to write a program that takes a string input and inverts it, so basically reverses the text. I also wanted to try and reuse one of my codes that had bubble sort and thought it could work.
So this is my code:
#include <stdio.h>
int main(){
int n;
char arr[n];
printf("Input length:\n");
scanf("%d",&n);
printf("Input string:\n");
scanf("%s",&arr);
bsort(arr);
printf("%s",arr);
}
void swap(char *x,char *y){
char temp=*x;
*x=*y;
*y=temp;
}
void bsort(char *arr, int n){
int i, j;
for(i=0;i<n;i ){
for(j=0;j<n;j ){
if(&arr[j]<&arr[j 1]){
swap(arr[j],arr[j 1]);
}
}
}
}
I don't know if I messed up data types, operators, or the functions altogether. When I run the program, there's nothing printed out. I'd appreciate any suggestions.
CodePudding user response:
#include <stdio.h>
#include <string.h>
void reverseString(char* str)
{
int l, i;
char *beginPtr, *endPtr, ch;
// Get the length of the string using this func instead of aking input
l = strlen(str);
// Setting the beginPtr
// to start of string
beginPtr = str;
//Setting the endPtr the end of
//the string
endPtr = str l - 1;
//basically we add the (len-1)
// Swap the char from start and end
// index using beginPtr and endPtr
for (i = 0; i < (l - 1) / 2; i ) {
// swap character
ch = *endPtr;
*endPtr = *beginPtr;
*beginPtr = ch;
// update pointers positions
beginPtr ;
endPtr--;
}
}
// Driver code
int main()
{
// Get the string
char str[100];
printf("Enter a string: ");
scanf("%s",&str);
// Reverse the string
reverseString(str);
// Print the result
printf("Reverse of the string: %s\n", str);
return 0;
}
I have tried to explain this code using comments if u dont wanna use string.h then u can ask input for length of the string