Reverse A String In C Exercise 3

  • while (start < end)
  • while (str != NULL)
  • while (str != '\0')

Explanation:

The correct answer is option (b). If the start index is not less than the end index, it is a valid condition to terminate the loop, which means that all character swaps have been completed.

  1. Which of the following prototypes for the function is correct to reverse a string in C?
  • void reverseString(char *str);
  • void reverseString(const char *str);
  • char reverseString(char str);
  • int reverseString(char *str);

Explanation:

The accurate choice is alternative (a). The function takes the transformed string (char *str) as a parameter and does not return any value (void).

  1. What will be the result of the provided code snippet?
  2. Example
    
    #include<stdio.h>
    #include<string.h>
    void reverseString(char *Str, int n){
        int i = 0, j = n - 1;
        while (i < j) {
            char temp = Str[i];
            Str[i] = Str[j];
            Str[j] = temp;
            i++;
            j--;
        }
    }
    int main() {
        char Str[] = "reverse";
        int len = strlen(Str);
        reverseString(Str, len);
        printf("%s\n", Str);
        return 0;
    }
    
  • esrever
  • reverse
  • reveser
  • eserver

Explanation:

The accurate choice is alternative (a). The software transforms the string precisely by altering characters at the start and end, while preserving the middle intact.

  1. What is the computational complexity of the following algorithm for reversing a string?
  2. Example
    
    void reverseString(char *str){
    int n=strlen(str);
    for(int i=0;i<n/2;i++){
            char temp = str[i];
            str[i] = str[n - i - 1];
            str[n - i - 1] = temp;
        }
    }
    
  • a.O(n)
  • b.O(n^2)
  • c.O(log n)
  • d.O(n log n)

Explanation:

The correct answer is option (a). After completing the assigned task for each character swap, the algorithm loops through half of the string. Here, the linear complexity is O(n).

  1. What is the main reason for using temporary variables when swapping characters in string reversal functions?
  • For storing string length
  • For storing the original value of character during swapping variables.
  • For checking the null pointers.
  • For printing the string.

Explanation:

The accurate choice is alternative (b). To avoid losing data, a temporary variable is employed to temporarily hold the value of a character while the swapping process is completed.

Input Required

This code uses input(). Please provide values below: