Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi. I need help understanding what this code does. I know it permutates the stri

ID: 3624116 • Letter: H

Question

Hi. I need help understanding what this code does. I know it permutates the string, but I want to know how the CODE works in plain english. Thanks:


#include<stdio.h>
#include<string.h>

void ror(char str1[],int a,int b)
{
char temp=str1[a];
int j;
for(j=a;j<b;j++)
{
str1[j]=str1[j+1];
}
str1[b]=temp;
}

void perm(char str[],int f,int l)
{
int i;
char str1[5];
strcpy(str1,str);
if(f==l)
{
printf("%s ",str1);
return;
}
for(i=f;i<=l;i++)
{
perm(str1,f+1,l);
ror(str1,f,l);
}
}

int main()
{
perm("vikas",0,4);
getchar();
}

Explanation / Answer

Ok, your main method calls the perm method which takes in a string (character array) with two int parameters 0 & 4. In the perm method, it copies the string into a temporary string. The if(f==l) is the base case for the recursion. In that if statement it prints the string. Otherwise, it goes into a for loop that calls perm again between f and l. It also calls ror on the string using the same integers passed in on the method. The ror method takes in the character at the ath position in the array. It then runs a for loop from a to b and shifts the letters in the string. It replaces the bth character in the string with the temporary character from str1[a]. So what it did was swap the two basically.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote