C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

In C, arrays and strings are closely related. In fact, a string in C is simply an array of characters terminated by a null character ('\0'). When passing arrays and strings to functions, we can use similar concepts of call by value and call by reference.

  • Passing Arrays:
    Arrays are usually passed to functions by reference, meaning we are  passing the memory address of the first element of the array. This allows functions to directly modify the contents of the array.
  • #include <stdio.h>
    
    // Function to double each element of an array
    void doubleArray(int arr[], int size) {
        for (int i = 0; i < size; i++) {
            arr[i] *= 2;
        }
    }
    
    int main() {
        int numbers[] = {1, 2, 3, 4, 5};
        int size = sizeof(numbers) / sizeof(numbers[0]);
        
        doubleArray(numbers, size);
        
        for (int i = 0; i < size; i++) {
            printf("%d ", numbers[i]);
        }
        return 0;
    }
    

     

  • In the doubleArray function, int arr[] denotes an array parameter. It's treated as a pointer to the first element of the array.
  •  
  • Passing Strings:
    Strings in C are essentially arrays of characters terminated by a null character ('\0'). You can pass strings to functions just like arrays.
#include <stdio.h>

// Function to print the length of a string
void printStringLength(char str[]) {
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    printf("Length of the string: %d\n", length);
}

int main() {
    char message[] = "Hello, world!";
    
    printStringLength(message);
    
    return 0;
}
  • Here, char str[] denotes a string parameter. It's treated as a pointer to the first character of the string. The function printStringLength calculates the length of the string by iterating until it encounters the null terminator.