Exercise: Strings

Questions for: Strings

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;
}
A:
Kagpur, Kanpur
B:
Nagpur, Kanpur
C:
Kagpur, anpur
D:
Error
Answer: D

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"

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

int main()
{
    char str = "ExamAdept";
    printf("%s\n", str);
    return 0;
}
A:
Error
B:
ExamAdept
C:
Base address of str
D:
No output
Answer: A

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

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

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

Then it prints "ExamAdept".

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

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

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

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 "ExamAdept". Therefore &str+2 is another memory location.

Hence it prints the Garbage value.

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

int main()
{
    char str[] = "India\0BIX\0";
    printf("%d\n", sizeof(str));
    return 0;
}
A:
10
B:
6
C:
5
D:
11
Answer: D

The following examples may help you understand this problem:

1. sizeof("") returns 1 (1*).

2. sizeof("India") returns 6 (5 + 1*).

3. sizeof("BIX") returns 4 (3 + 1*).

4. sizeof("India\0BIX") returns 10 (5 + 1 + 3 + 1*).
    Here '\0' is considered as 1 char by sizeof() function.

5. sizeof("India\0BIX\0") returns 11 (5 + 1 + 3 + 1 + 1*).
    Here '\0' is considered as 1 char by sizeof() function.

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

int main()
{
    char str1[] = "Hello";
    char str2[10];
    char *t, *s;
    s = str1;
    t = str2;
    while(*t=*s)
        *t++ = *s++;
    printf("%s\n", str2);
    return 0;
}
A:
Hello
B:
HelloHello
C:
No output
D:
ello
Answer: A
No answer description is available. Let's discuss.
Ad Slot (Above Pagination)
Quiz