Wednesday, October 31, 2018

C String - Predict output- 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 greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    printf("Greeting message: %s\n", greeting ); 
    return 0; 
}

Output: Greeting message: Hello
Justification: Variable greetings will be initialized at compile time. '\0' is end of string character, and will not be printed along with Hello.


Program-2

#include "stdio.h" 
int main() 

    char str[] = { 'A', 'B', 'C', 'D' }; 
    char *p = &str[1]; 
    *p++;
    printf("%c ", *p);
    *p++;
    printf("%c ", *p);


Output: C D
Justification: Memory address of str[1] will be assigned to character pointer (*p). The value stored ar str[1] is 'B'. Statement *p++ will increment its value by one; which results in value 'C' which is printed. Again *p++ will increment its value by one; which results in 'D' which is printed resulting in final output as C D



Program-3


#include<stdio.h>
#include<string.h>
int main()
{
    char str1[20] = "C Program";
    char str2[20] = "C Practicals";
    printf("%s\n", strcpy(strcat(str1, str2), str2));
    return 0;
}

Output: C Practicals
Justification: Inner function strcat will be executed first, which will append the str2 (i.e. C Practicals) into str1 variable. Then, str2 (i.e. C Practicals) will be copied to str1; which will be the final output printed on screen.


Program-4


#include<stdio.h>
#include<string.h>
int main()
{
    printf("%d", strlen("01234567"));
    return 0;
}

Output: 8
Justification: strlen() function find the length of "01234567" which will be printed on screen.


Program-5


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

Output: Practicals
Justification: First 10 characters will be ignored while printing a string "C Program Practicals"; hence output is Practicals.


No comments:

Post a Comment