C Strings and Arrays Interview Questions

Last Updated : 23 Aug, 2025

An array in C is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow efficient indexed access using zero-based indexing.

In C, a string is simply a character array terminated with a special null character '\0'. C does not have a dedicated string type like higher-level languages. You must manage strings manually using character arrays and functions from <string.h>.

1. What is the difference between an array and a string in C?

An array in C is a collection of elements of the same data type stored in contiguous memory locations, while a string is a character array terminated with a null character ('\0').

C
#include <stdio.h>

int main() {

    int arr[5] = {1, 2, 3, 4, 5};  
    char str[] = "Hello"; 
    printf("%d",arr[3]);
    return 0;
}

2. How do arrays work in C?

Arrays store fixed-size sequential data of the same type in contiguous memory. They are zero-indexed and accessed using the subscript operator [ ].

C
#include <stdio.h>

int main() {
    int arr[3] = {10, 20, 30};
    for (int i = 0; i < 3; i++)
        printf("arr[%d] = %d\n", i, arr[i]);
    return 0;
}

3. What is the purpose of the null character ('\0) in strings?

The null character marks the end of a string in C. Without it, C cannot determine where the string terminates, which can lead to undefined behavior when functions like printf, strlen, or strcpy are used.\

C
#include <stdio.h>

int main() {
    char str[] = "Hello"; // automatically ends with '\0'
    printf("%s\n", str);  // knows where to stop
    return 0;
}

4. How are strings stored in memory?

Strings are stored as arrays of characters in contiguous memory locations. The last character is always the null character ('\0') which signals the end of the string to functions that process strings.

C
#include <stdio.h>

int main() {
    char str[] = "CProg";
    for (int i = 0; i <= 5; i++)  // including '\0'
        printf("str[%d] = %c\n", i, str[i]);
    return 0;
}

5. What are some standard library functions used with strings?

Commonly used string functions from <string.h> include:

  • strlen() – returns length
  • strcpy() – copies one string to another
  • strcmp() – compares two strings
  • strcat() – appends one string to another
  • strchr() – searches for a character in a string
C
#include <stdio.h>
#include <string.h>

int main() {
    char a[] = "Hello", b[] = "World", c[20];

    printf("Length: %zu\n", strlen(a));           // strlen
    strcpy(c, a);                                   // strcpy
    strcat(c, b);                                   // strcat
    printf("Combined: %s\n", c);                    // strcat result
    printf("Compare: %d\n", strcmp("Hi", "Hi"));   // strcmp
    printf("Found: %s\n", strchr("Test", 'e'));    // strchr
    return 0;
}

6. What happens when you access an array out of bounds?

Accessing an array beyond its limits causes undefined behavior, as C does not perform bounds checking. It may lead to accessing garbage values, crashing, or memory corruption.

C
#include <stdio.h>

int main() {
    int arr[3] = {1, 2, 3};
    printf("%d\n", arr[5]); //  Undefined behavior (garbage or crash)
    return 0;
}

7. What is the difference between strlen() and sizeof() for strings?

  • strlen(str) gives the number of characters before the null terminator.
  • sizeof(str) gives the total memory allocated, including the null character.

char arr[] = "Hi"; // sizeof(arr) == 3, strlen(arr) == 2

char *p = arr; // sizeof(p) == sizeof(char*) (e.g., 8), strlen(p) == 2

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

int main() {
    char str[] = "Hi";
    printf("strlen: %lu\n", strlen(str));  // 2
    printf("sizeof: %lu\n", sizeof(str));  // 3 (includes '\0')
    return 0;
}

8. How to convert a string to numbers in C?

In C we have 2 main methods to convert strings to numbers i.e, Using string stream, Using stoi() library Function or using atoi() library function. 

  • sscanf(): It reads input from a string rather than standard input.
  • stoi() or atoi(): These functions takes a string literal or a character array as an argument and an integer value is returned.

For more information, refer to the article -String to Numbers in C

C
#include <stdio.h>
#include <stdlib.h>

int main() {
    char numStr[] = "123";
    int num = atoi(numStr);  // string to int
    printf("Converted number: %d\n", num);
    return 0;
}

9. How do you reverse a string in C?

To reverse a string in C using two pointers, the idea is simple:

  • Use one pointer (start) pointing to the beginning of the string.
  • Use another pointer (end) pointing to the last character (before the null terminator \0).
  • Swap the characters at these two positions.
  • Move start forward and end backward, and repeat until they meet or cross.

This in-place method efficiently reverses the string without using extra memory.

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

// Function to reverse a string in-place
void reverse(char *str)
{
    int i = 0, j = strlen(str) - 1;
    while (i < j)
    {
        char temp = str[i];
        str[i++] = str[j];
        str[j--] = temp;
    }
}

int main()
{
    char str[]= "hello";
    reverse(str);
    printf("Reversed string: %s\n", str);

    return 0;
}

10. Write a Program to Count number of subarrays with even sum

The function countEvenSum() counts how many subarrays of an array have an even sum.

  • It uses two nested loops:
    • Outer loop picks the starting index of a subarray.
    • Inner loop adds elements from the current start to end index.
  • For each subarray, it checks if the sum is even (sum % 2 == 0).
  • If yes, it increases the count.
C
#include <stdio.h>

int countEvenSum(int arr[], int n) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = i; j < n; j++) {
            sum += arr[j];
            if (sum % 2 == 0) count++;
        }
    }
    return count;
}


int main() {

    int arr[]={3,5,2,46,44,3,5};
    printf("%d",countEvenSum(arr,7));
    return 0;
}

11. How do you reverse each word in a sentence in C?

  • A word is a sequence of characters separated by spaces.
  • You need to reverse each word in-place, without affecting the positions of spaces or the word order.

Algorithm:

  1. Traverse the string using an index.
  2. For every word: Identify the start and end index of the word (delimited by space or \0).
  3. Use the two-pointer technique to reverse characters between start and end.
  4. Continue until the end of the string.
C
#include <stdio.h>
#include <string.h>

void reverse(char *s, int start, int end) {
    while (start < end) {
        char t = s[start];
        s[start++] = s[end];
        s[end--] = t;
    }
}

void reverseWords(char *str) {
    int i = 0, start = 0;
    while (str[i]) {
        if (str[i] == ' ') {
            reverse(str, start, i - 1);
            start = i + 1;
        }
        i++;
    }
    reverse(str, start, i - 1); // reverse last word
}

int main() {
    char str[] = "hello world coder";
    reverseWords(str);
    printf("%s\n", str); // Output: "olleh dlrow redoc"
    return 0;
}

12. Write a Program to Find the Largest Element in an Array.

To find the largest element in an array:

  1. Assume the first element is the largest (max = arr[0]).
  2. Traverse the array from the second element.
  3. For each element, compare it with max.
  4. If it’s greater, update max.

After the loop, max holds the largest value.

C
#include <stdio.h>

int main() {
    int arr[] = {12, 45, 7, 89, 32};
    int n = sizeof(arr) / sizeof(arr[0]);
    int max = arr[0];

    for (int i = 1; i < n; i++) {
        if (arr[i] > max)
            max = arr[i];
    }

    printf("Largest element: %d\n", max);
    return 0;
}

13. Write a program that checks if a given string is a palindrome (reads the same forward and backward).

A palindrome is a string that reads the same forward and backward (e.g., "madam", "racecar"). To check if a string is a palindrome:

  1. Use two pointers: one starting at the beginning and one at the end.
  2. Compare characters at both positions.
  3. If they are equal, move inward.
  4. If any pair doesn't match, it’s not a palindrome.
  5. If all characters match, it's a palindrome.
C
#include <stdio.h>
#include <string.h>

int isPalindrome(char *str) {
    int i = 0, j = strlen(str) - 1;
    while (i < j) {
        if (str[i] != str[j])
            return 0;
        i++; j--;
    }
    return 1;
}

int main() {
    char str1[]="hello";
    char str2[]="naman";

    if (isPalindrome(str1))
        printf("Palindrome\n");
    else
        printf("Not a Palindrome\n");
        
        
    if (isPalindrome(str2))
        printf("Palindrome\n");
    else
        printf("Not a Palindrome\n");

    return 0;
}

14. Given a string, write a C program to remove all duplicate characters, keeping the first occurrence only.

To remove duplicate characters from a string while keeping only the first occurrence:

  1. Create a lookup array (e.g., int seen[256] = {0}) to track if a character has appeared.
  2. Traverse the original string
  3. If a character hasn’t been seen before, keep it and mark it as seen.
  4. If it’s a duplicate, skip it.
  5. Build the result in-place using a second pointer or index.
C
#include <stdio.h>

void removeDuplicates(char *str) {
    int seen[256] = {0};
    int i, j = 0;
    for (i = 0; str[i] != '\0'; i++) {
        if (!seen[(unsigned char)str[i]]) {
            seen[(unsigned char)str[i]] = 1;
            str[j++] = str[i];
        }
    }
    str[j] = '\0';
}

int main() {
    char str[]="hello";

    removeDuplicates(str);
    printf("String after removing duplicates: %s\n", str);
    return 0;
}

15. Write a program to merge two arrays into a third array and display the result.

To merge two arrays into a third array:

  1. Let’s say we have two arrays arr1 and arr2 of sizes n1 and n2.
  2. Create a third array merged of size n1 + n2.
  3. Copy all elements of arr1 into merged.
  4. Then copy all elements of arr2 after the last element of arr1.
  5. Finally, display the merged array.
C
#include <stdio.h>

int main() {
    int arr1[] = {1, 3, 5};
    int arr2[] = {2, 4, 6};
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
    int merged[100], i, j, k = 0;

    for (i = 0; i < n1; i++)
        merged[k++] = arr1[i];
    for (j = 0; j < n2; j++)
        merged[k++] = arr2[j];

    printf("Merged array: ");
    for (i = 0; i < k; i++)
        printf("%d ", merged[i]);
    printf("\n");

    return 0;
}

16. Write a Program to Detect if a string has all unique characters (ASCII only)

1. There are 256 possible ASCII characters.

2. If a string has more characters than 256, it cannot have all unique characters.

3. Use an array of size 256 to track the occurrence of each character.

4. Traverse the string:

  • If a character is seen for the first time, mark it.
  • If it’s already marked, it's a duplicate -> return false.
C
#include <stdio.h>

int isUnique(char *str) {
    int seen[256] = {0};
    while (*str) {
        if (seen[(unsigned char)*str]) return 0;
        seen[(unsigned char)*str++] = 1;
    }
    return 1;
}


int main() {
    char str1[]="hello world";
    char str2[]="hel word";
    printf("%d\n",isUnique(str1));
    printf("%d",isUnique(str2));
    return 0;
}

17. Write a Program to Remove all spaces in a string without using extra space

  • Strings in C are null-terminated character arrays.
  • To remove spaces without extra space, we can use a two-pointer technique:

i: used to read the string.
j: used to write the non-space characters at the correct place.

How it works:

  1. Start with both i = 0 and j = 0.
  2. Traverse the string using i.
  3. If str[i] is not a space, copy it to str[j] and increment j.
  4. If str[i] is a space, just skip it (don’t increment j).
  5. After the loop, terminate the string with str[j] = '\0'.
C
#include <stdio.h>

void removeSpaces(char *str) {
    int i = 0, j = 0;
    while (str[i]) {
        if (str[i] != ' ') str[j++] = str[i];
        i++;
    }
    str[j] = '\0';
}
 
int main() {

    char str[]="hello world";
    removeSpaces(str);
    printf("%s",str);
    return 0;
}

18. Write a Program Convert uppercase to lowercase without using library

Key Concept- ASCII Values:

In C, characters are stored as ASCII values.

'A' to 'Z' -> ASCII 65 to 90
'a' to 'z' -> ASCII 97 to 122

The difference between lowercase and uppercase letters in ASCII is:

C
#include <stdio.h>

void toLower(char *s) {
    while (*s) {
        if (*s >= 'A' && *s <= 'Z')
            *s += 32;
        s++;
    }
}
 
int main() {

    char str[]="Hello world";
    toLower(str);
    printf("%s",str);
    return 0;
}

19. Write a program to find the length of Longest common prefix among strings.

  • Start by assuming the first string is the prefix.
  • Compare the prefix with every other string in the array: Shorten the prefix until it matches the start of the current string.
  • If the prefix becomes an empty string, no common prefix exists.

Algorithm Steps:

  1. Assume prefix = strings[0]
  2. For each string in the array:
  3. While the string does not start with the current prefix:
  4. Remove the last character from prefix
  5. Return the final value of prefix
C
#include <stdio.h>

int commonPrefix(char *s1, char *s2) {
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i]) i++;
    return i;
}
 

int main() {

    char str1[]="hello world";
    char str2[]="helicopter";
    printf("%d",commonPrefix(str1,str2));
    return 0;
}

20. Write a Program to detect Duplicates in an array in O(n) Worst case time complexity.

To detect duplicates in an array in O(n) worst-case time, we can use hashing (like a frequency array or hash set):

  • Traverse the array once.
  • Keep track of seen elements in a hash table (e.g., int freq[1000] = {0}).
  • If an element is already marked as seen, it’s a duplicate.
C
#include <stdio.h>

int hasDuplicate(int arr[], int n) {
    int seen[1000] = {0};
    for (int i = 0; i < n; i++) {
        if (seen[arr[i]]) return 1;
        seen[arr[i]] = 1;
    }
    return 0;
}


int main() {

    int arr1[]={6,4,8,6,9,3,4,6,87,55};
    int arr2[]={6,4,8,9,3,87,55};
    printf("%d\n%d",hasDuplicate(arr1,10),hasDuplicate(arr2,7));
    return 0;
}

21. Write a Program to Find the second largest number.

To find the second largest number in an array:

  • Maintain two variables:

first for the largest number
second for the second largest

  • Traverse the array once:

If the current number is greater than first, update second = first and first = current.
Else if current number is between first and second, update second = current.

C
#include <stdio.h>

int secondLargest(int arr[], int n) {
    int first = arr[0], second = -1;
    for (int i = 1; i < n; i++) {
        if (arr[i] > first) {
            second = first;
            first = arr[i];
        } else if (arr[i] > second && arr[i] != first)
            second = arr[i];
    }
    return second;
}


int main() {
    int arr[]={3,4,6,43,12,76,1,34};
    printf("%d",secondLargest(arr,8));
    return 0;
}

22. Write a Program to Sort 0s, 1s, 2s without sorting.

  • Use three pointers:

low -> next position for 0
mid -> current element being checked
high -> next position for 2

  • Traverse the array:

If element is 0 -> swap with low, move both low and mid
If element is 1 -> just move mid
If element is 2 -> swap with high, move high backward

C
#include <stdio.h>

void sort012(int arr[], int n) {
    int low = 0, mid = 0, high = n - 1;
    while (mid <= high) {
        if (arr[mid] == 0) {
            int t = arr[low]; arr[low++] = arr[mid]; arr[mid++] = t;
        } else if (arr[mid] == 1) mid++;
        else {
            int t = arr[mid]; arr[mid] = arr[high]; arr[high--] = t;
        }
    }
}


int main() {
    int arr[]={1,2,1,2,2,0,0,1,1};
    sort012(arr,9);
    for(int i=0;i<9;i++) printf("%d ",arr[i]);
    return 0;
}
Comment