Reputation: 23
I have to move one character at a time in a string input by the user. At each iteration, the program moves characters to the right from their current place circularly. That is the first character is moved to 2nd place, 2nd character is moved to 3rd place and so on. The last character is moved to 1st place. After characters are moved, the program must also print the new string in each iteration. The iterations are continued till the original string is got back.
For example user enters the string: 'cat'
After first iteration string is: 'tca'
After second iteration string is: 'atc'
and third iteration: 'cat' (which is same as and program finish)
I wrote a code that reverses an entire string. But, I really have no idea how to move one character at a time. The code is as shown below:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
main ()
{
char word[20];
printf("enter word:");
int d,i;
scanf("%s",&word);
d = strlen(word);
for(i=d-1; i >= 0; i--)
printf("%c",word[i]);
}
Upvotes: 2
Views: 17037
Reputation: 1666
Possible Solution:
From the sample output it seems like you need to access the string like a circular array. In that case you may need to iterate the string from index (size - move_number) each time and then print the indices by accessing them like a circular array.
Updated Code:
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void main()
{
char word[20];
printf("enter word:");
int d, i;
scanf("%s", &word);
d = strlen(word);
for (i = d - 1; i >= 0; i--)
{
int j = i;
do
{
printf("%c", word[j]); //Printing each index
j = (j + 1) % d; //computing the next index to print
}
while (j != i); //Condition which determines that whole string is traversed
printf("\n");
}
}
Hope this helps you in understanding the logic behind the solution.
Upvotes: 2
Reputation: 3159
declare a var j and replace your for loop with this:
for (i = d-1; i >=0; i--) {
j = i;
printf("%c",word[j]);
j = (j + 1) % d;
while ( j != i) {
printf("%c",word[j]);
j = (j + 1) % d;
}
printf ("\n"):
}
Upvotes: 2