CSE1002 Recursive reverse (Id-1250)
Given a string, write a recursive routine to reverse it. For example, given the string 'and, the reversal of the string is 'dna'.Input FormatA stringOutput FormatReverse of the string
Solution:
C-code:
#include <stdio.h>
#include <string.h>
void reverse(char [], int, int);
int main()
{
char s[20];
int size;
scanf("%s", s);
size = strlen(s);
reverse(s, 0, size - 1);
printf("%s", s);
return 0;
}
void reverse(char s[], int i, int size)
{
char temp;
temp = s[i];
s[i] = s[size - i];
s[size - i] = temp;
if (i == size / 2)
{
return;
}
reverse(s, i + 1, size);
}
Input:
Read a string.
Processing:
void reverse(char [], int, int);
int main()
{
char s[20];
int size;
scanf("%s", s);
size = strlen(s);
reverse(s, 0, size - 1);
printf("%s", s);
return 0;
}
void reverse(char s[], int i, int size)
{
char temp;
temp = s[i];
s[i] = s[size - i];
s[size - i] = temp;
if (i == size / 2)
{
return;
}
reverse(s, i + 1, size);
}
Output:
Display of the reverse string
Pseduo code:
1)Start
2)Create a function which takes string as input
3)Read the string.
4)call the funtion.
5)Display the reverse of the string
6)End.
Given a string, write a recursive routine to reverse it. For example, given the string 'and, the reversal of the string is 'dna'.Input FormatA stringOutput FormatReverse of the string
Solution:
C-code:
#include <stdio.h>
#include <string.h>
void reverse(char [], int, int);
int main()
{
char s[20];
int size;
scanf("%s", s);
size = strlen(s);
reverse(s, 0, size - 1);
printf("%s", s);
return 0;
}
void reverse(char s[], int i, int size)
{
char temp;
temp = s[i];
s[i] = s[size - i];
s[size - i] = temp;
if (i == size / 2)
{
return;
}
reverse(s, i + 1, size);
}
Read a string.
Processing:
void reverse(char [], int, int);
int main()
{
char s[20];
int size;
scanf("%s", s);
size = strlen(s);
reverse(s, 0, size - 1);
printf("%s", s);
return 0;
}
void reverse(char s[], int i, int size)
{
char temp;
temp = s[i];
s[i] = s[size - i];
s[size - i] = temp;
if (i == size / 2)
{
return;
}
reverse(s, i + 1, size);
}
Display of the reverse string
Pseduo code:
1)Start
2)Create a function which takes string as input
3)Read the string.
4)call the funtion.
5)Display the reverse of the string
6)End.
0 Comments