134k views
5 votes
C PROGRAM NEED SAME OUTPUT DONOT GIVE IRRELEVANT OUTPUT

1 - WAP to reverse the given string using iterative method
Description:
Read a string from user.
Implement using loops.
Do not print character by character.
Pr-requisites:-
Strings
Loops
Objective: -
To understand the concept of
Reversing the string
Inputs: -
String
Sample execution: -
Test Case 1:
Enter a string : Hello World
Reverse string is : dlroW olleH
Test Case 2:
Enter a string : EMERTXE
Reverse string is : EXTREME
REQUESTED FILE ALSO NEED
#include
void reverse_iterative(char str[]);
int main()
{
char str[30];
printf("Enter any string : ");
scanf("%[^\\]", str);
reverse_iterative(str);
printf("Reversed string is %s\\", str);
}
\\
2
A42 - WAP to reverse the given string using recursive method
Description:
Read a string from user.
Implement using recursive function without using any loops
Do not print character by character.
Pr-requisites:-
Strings
Loops
Objective: -
To understand the concept of
Reversing the string
Inputs: -
String
NOTE : Should not use static, global variables and loops
Sample execution: -
Test Case 1:
Enter a string : Hello World
Reverse string is : dlroW olleH
Test Case 2:
Enter a string : EMERTXE
Reverse string is : EXTREME
REQUESTED FILE
#include
void reverse_recursive(char str[], int ind, int len);
int main()
{
char str[30];
printf("Enter any string : ");
scanf("%[^\\]", str);
reverse_recursive(str, ?, ?);
printf("Reversed string is %s\\", str);
}

1 Answer

6 votes

Answer:

See below.

Step-by-step explanation:

Let's start with the first problem: reversing a string using an iterative method in C.

-------------------------------------------------------------------------------------------------------

#include <stdio.h>

#include <string.h>

void reverse_iterative(char str[]) {

int len = strlen(str);

int start = 0;

int end = len - 1;

// Swap characters from start and end indices until they meet in the middle

while (start < end) {

char temp = str[start];

str[start] = str[end];

str[end] = temp;

start++;

end--;

}

}

int main() {

char str[30];

printf("Enter any string: ");

scanf("%[^\\]", str);

reverse_iterative(str);

printf("Reversed string is: %s\\", str);

return 0;

}

-----------------------------------------------------------------------------------------

In this code, we define the function reverse_iterative that takes a character array (str) as input. We use the strlen function from the string.h library to find the length of the string.

Then, we initialize two indices (start and end) to the beginning and end of the string, respectively. We iterate through the string, swapping the characters at the start and end indices, and incrementing start and decrementing end until they meet in the middle.

Finally, in the main function, we prompt the user to enter a string, call the reverse_iterative function to reverse the string, and print the reversed string.

User Nditah
by
8.1k points