Tuesday, November 6, 2018

String - Predict Output-2 Answer

Predict Program Output Based on C String

Output of following C Programs are not very simple. These are simple but very interesting top c programs based on C Strings asked during viva and interviews.

Program-1

#include<stdio.h>
int main()
{
    char str[] = "%d";
    str[1] = 'c';
    printf(str, 97);
    return 0;
}

Output: a
Justification:
-> Statement char str[] = "%d" will initialize str[] to "%d".
-> str[1] = 'c'; assigns 'c' to str[1] which replaces "%d" with "%c".
-> printf() function prints character of ASCII value 97; hence final output is a.
 
Program-2

#include<stdio.h>
int main()
{
    printf("C Program Practicals", "C Programming", "ICP");
    return 0;
}

Output: C Program Practicals
Justification: Comma operator has Left to Right associativity; printf() starts printing with first double quote and ends at second double quote hence final output is C Program Practicals.

Program-3

#include<stdio.h>
int main()
{
    char *names[] = { "AAA", "BBB", "CCC"};
    int i;
    char *temp;
   
  temp = names[0];
    names[0] = names[1];
    names[1] = temp;
   
  for(i=0; i<=2; i++)
        printf("%s ", names[i]);
    return 0;
}

Output: BBB AAA CCC
Justification: Array names[] will be initialized with AAA BBB CCCThen using temp variable, first and second array elements are inter-changed; resulting in final output as BBB AAA CCC.

Program-4

#include<stdio.h>
#include<string.h>
int main()
{
    char name[] = "Gujarat\0India\0";
    printf("%d", strlen(name));
    return 0;
}

Output: 7

Justification: String initialization terminates are first ' \0 '; hence name[] contains only "Gujarat"; strlen(name) function return 7 which is finally printed.

Read more interesting programs at C Program Practicals - Question Bank.

No comments:

Post a Comment