C Programming - Strings

Exercise : Strings - Find Output of Program
6.
What will be the output of the program If characters 'a', 'b' and 'c' enter are supplied as input?
#include<stdio.h>

int main()
{
    void fun();
    fun();
    printf("\n");
    return 0;
}
void fun()
{
    char c;
    if((c = getchar())!= '\n')
        fun();
    printf("%c", c);
}
abc abc
bca
Infinite loop
cba
Answer: Option
Explanation:

Step 1: void fun(); This is the prototype for the function fun().

Step 2: fun(); The function fun() is called here.

The function fun() gets a character input and the input is terminated by an enter key(New line character). It prints the given character in the reverse order.

The given input characters are "abc"

Output: cba


7.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    printf("India", "BIX\n");
    return 0;
}
Error
India BIX
India
BIX
Answer: Option
Explanation:

printf("India", "BIX\n"); It prints "India". Because ,(comma) operator has Left to Right associativity. After printing "India", the statement got terminated.


8.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char str[7] = "IndiaBIX";
    printf("%s\n", str);
    return 0;
}
Error
IndiaBIX
Cannot predict
None of above
Answer: Option
Explanation:
Here str[] has declared as 7 character array and into a 8 character is stored. This will result in overwriting of the byte beyond 7 byte reserved for '\0'.

9.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    char *names[] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"};
    int i;
    char *t;
    t = names[3];
    names[3] = names[4];
    names[4] = t;
    for(i=0; i<=4; i++)
        printf("%s,", names[i]);
    return 0;
}
Suresh, Siva, Sona, Baiju, Ritu
Suresh, Siva, Sona, Ritu, Baiju
Suresh, Siva, Baiju, Sona, Ritu
Suresh, Siva, Ritu, Sona, Baiju
Answer: Option
Explanation:

Step 1: char *names[] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"}; The variable names is declared as an pointer to a array of strings.

Step 2: int i; The variable i is declared as an integer type.

Step 3: char *t; The variable t is declared as pointer to a string.

Step 4: t = names[3]; names[3] = names[4]; names[4] = t; These statements the swaps the 4 and 5 element of the array names.

Step 5: for(i=0; i<=4; i++) printf("%s,", names[i]); These statement prints the all the value of the array names.

Hence the output of the program is "Suresh, Siva, Sona, Ritu, Baiju".


10.
What will be the output of the program ?
#include<stdio.h>
#include<string.h>

int main()
{
    char str[] = "India\0\BIX\0";
    printf("%d\n", strlen(str));
    return 0;
}
10
6
5
11
Answer: Option
Explanation:

The function strlen returns the number of characters int the given string.

Therefore, strlen(str) becomes strlen("India") contains 5 characters. A string is a collection of characters terminated by '\0'.

The output of the program is "5".