C Programming - Strings

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

int main()
{
    char str[25] = "IndiaBIX";
    printf("%s\n", &str+2);
    return 0;
}
Garbage value
Error
No output
diaBIX
Answer: Option
Explanation:

Step 1: char str[25] = "IndiaBIX"; The variable str is declared as an array of characteres and initialized with a string "IndiaBIX".

Step 2: printf("%s\n", &str+2);

=> In the printf statement %s is string format specifier tells the compiler to print the string in the memory of &str+2

=> &str is a location of string "IndiaBIX". Therefore &str+2 is another memory location.

Hence it prints the Garbage value.


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

int main()
{
    char str = "IndiaBIX";
    printf("%s\n", str);
    return 0;
}
Error
IndiaBIX
Base address of str
No output
Answer: Option
Explanation:

The line char str = "IndiaBIX"; generates "Non portable pointer conversion" error.

To eliminate the error, we have to change the above line to

char *str = "IndiaBIX"; (or) char str[] = "IndiaBIX";

Then it prints "IndiaBIX".


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

int main()
{
    char str[] = "Nagpur";
    str[0]='K';
    printf("%s, ", str);
    str = "Kanpur";
    printf("%s", str+1);
    return 0;
}
Kagpur, Kanpur
Nagpur, Kanpur
Kagpur, anpur
Error
Answer: Option
Explanation:

The statement str = "Kanpur"; generates the LVALUE required error. We have to use strcpy function to copy a string.

To remove error we have to change this statement str = "Kanpur"; to strcpy(str, "Kanpur");

The program prints the string "anpur"


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

int main()
{
    printf(5+"IndiaBIX\n");
    return 0;
}
Error
IndiaBIX
BIX
None of above
Answer: Option
Explanation:

printf(5+"IndiaBIX\n"); In the printf statement, it skips the first 5 characters and it prints "BIX"


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

int main()
{
    char sentence[80];
    int i;
    printf("Enter a line of text\n");
    gets(sentence);
    for(i=strlen(sentence)-1; i >=0; i--)
        putchar(sentence[i]);
    return 0;
}
The sentence will get printed in same order as it entered
The sentence will get printed in reverse order
Half of the sentence will get printed
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.