C Exercises: Reverse a string partially

C Basic-II: Exercise-2 with Solution

Write a C program that takes a string and two integers (n1, n2). Now reverse the sequence of characters of the string between n1 and n2.
Let l be the length of the string.


  • 1 ≤ n1 ≤ n2 ≤ l ≤100
  • Each letter of the string is an uppercase or lowercase letter.

Sample Date:

("abcdxyabcd", 5, 6) -> "abcdyxabcd" ("Exercises", 1, 3) -> "exercises"

C Code:

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

int main(void)
    char text[101] = {0};
    char result[101] = {0};
    int n1, n2, l; 
    printf("Input a string: ");
    scanf("%s", text);
    printf("Input position-1 for reverse the string: ");
    scanf("%d", &n1);
    printf("\nInput position-2 for reverse the string: ");
    scanf("%d", &n2);
    l = strlen(text);
    int i = 0;
    for(; i < n1-1; i++) {
        result[i] = text[i];
    for(int j = n2-1; i < n2; i++, j--) {
        result[i] = text[j];
    for(; i <= l; i++) {
        result[i] = text[i];

    printf("Reverse string (partly): %s\n", result);

    return 0;

Sample Output:

Input a string: Input position-1 for reverse the string: abcdxyabcd 5 6
Input position-2 for reverse the string: Reverse string (partly): abcdyxabcd


C Programming Flowchart: Reverse a string partially.

C Programming Code Editor:

Contribute your code and comments through Disqus.

Previous C Programming Exercise: Find the integer that appears the least often.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M