#include <stdio.h>
int main() {
int k;
char str[1001];
scanf("%d", &k);
scanf("%s", str);
int len = 0;
while (str[len] != '\0') {
len++;
}
k = k % len;
for (int i = len - k; i < len; i++) {
printf("%c", str[i]);
}
for (int i = 0; i < len - k; i++) {
printf("%c", str[i]);
}
return 0;
}
This code reads a string and a number k, then rotates the string to the right by k positions and prints the result. It calculates the string length manually, takes k modulo the length to handle large k values, and prints the last k characters followed by the first len-k characters.
- The code does not handle the case where k is 0 or a multiple of len. When k is 0, len - k equals len, so the first loop runs from len to len (no iterations) and the second loop runs from 0 to len, which works correctly. But if k is negative, the modulo operation may produce unexpected results because C's % operator with negative numbers can give a negative remainder. Consider what happens if k is negative and how to ensure k is always in the range 0 to len-1.
- The code assumes the input string will not exceed 1000 characters, but it does not check if the string length is 0. If len is 0, the modulo operation k % 0 causes undefined behavior (division by zero). Think about how to guard against an empty string input.