C Programming - Strings

Exercise : Strings - Find Output of Program
31.
What will be the output of the program in Turbo C?
#include<stdio.h>

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

str[6] = "BIX"; - Nonportable pointer conversion.


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

int main()
{
    char str1[] = "Hello";
    char str2[] = "Hello";
    if(str1 == str2)
        printf("Equal\n");
    else
        printf("Unequal\n");
    return 0;
}
Equal
Unequal
Error
None of above
Answer: Option
Explanation:

Step 1: char str1[] = "Hello"; The variable str1 is declared as an array of characters and initialized with a string "Hello".

Step 2: char str2[] = "Hello"; The variable str2 is declared as an array of characters and initialized with a string "Hello".

We have use strcmp(s1,s2) function to compare strings.

Step 3: if(str1 == str2) here the address of str1 and str2 are compared. The address of both variable is not same. Hence the if condition is failed.

Step 4: At the else part it prints "Unequal".


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

int main()
{
    char t;
    char *p1 = "India", *p2;
    p2=p1;
    p1 = "BIX";
    printf("%s %s\n", p1, p2);
    return 0;
}
India BIX
BIX India
India India
BIX BIX
Answer: Option
Explanation:

Step 1: char *p1 = "India", *p2; The variable p1 and p2 is declared as an pointer to a character value and p1 is assigned with a value "India".

Step 2: p2=p1; The value of p1 is assigned to variable p2. So p2 contains "India".

Step 3: p1 = "BIX"; The p1 is assigned with a string "BIX"

Step 4: printf("%s %s\n", p1, p2); It prints the value of p1 and p2.

Hence the output of the program is "BIX India".


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

int main()
{
    printf("%c\n", "abcdefgh"[4]);
    return 0;
}
Error
d
e
abcdefgh
Answer: Option
Explanation:

printf("%c\n", "abcdefgh"[4]); It prints the 5 character of the string "abcdefgh".

Hence the output is 'e'.


35.
What will be the output of the following program in 16 bit platform assuming that 1022 is memory address of the string "Hello1" (in Turbo C under DOS) ?
#include<stdio.h>

int main()
{
    printf("%u %s\n", &"Hello1", &"Hello2");
    return 0;
}
1022 Hello2
Hello1 1022
Hello1 Hello2
1022 1022
Error
Answer: Option
Explanation:

In printf("%u %s\n", &"Hello", &"Hello");.

The %u format specifier tells the compiler to print the memory address of the "Hello1".

The %s format specifier tells the compiler to print the string "Hello2".

Hence the output of the program is "1022 Hello2".