Interview Questions
What is printf() function in C
What is scanf: The function int printf(const char *format, …); writes a formatted string to stdout(standard output device). If format contains format specifiers (subsequences beginning with %), the additional arguments following format are inserted after formatting in the resulting string by replacing their respective format specifiers.
Function prototype of printf:
int printf(const char *format, ...);
format : This is a null-terminated string containing the text to be written to stdout. It may contains some embedded format specifiers.
additional arguments : These arguments will substitute the value of format specifiers in output string.
#include <stdio.h> int main(){ printf("Printing characters"); printf("%c %c %c %c\n\n", 'a', 'A', '#', '1'); printf("Printing integers"); printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015); printf("Printing floating point numbers"); printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412); printf("Printing string"); printf("%s\n\n", "TechCrashCourse"); return 0; }
Output
Printing characters a A # 1 Printing integers 2015 2015 2015 0000002015 Printing floating point numbers 1.414120 1.41 +1e+000 1.414120E+000 Printing string TechCrashCourse
What is scanf() function in C
The function int scanf(const char *format, …); reads formatted data from stdin(standard input device) and stores them in the variables pointed by the additional arguments. Additional arguments must point to variables of the same type as specified in the format.
Function prototype of scanf
int scanf(const char *format, ...);
format : This is a null terminated string that contains Whitespace character, Non-whitespace character and Format specifiers.
additional arguments : As per the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the data read from stdin to be stored.
Return value of scanf
On success, scanf function returns the total number of objects successfully read, it may or may not be same as the expected number of items specified in format string.
#include <stdio.h> int main(){ int a, b, sum; printf("Enter to integers to add\n"); /* Taking input from user using scanf */ scanf("%d %d", &a, &b); sum = a + b; printf("%d + %d = %d", a, b, sum); return 0; }
Output
Enter to integers to add 3 9 3 + 9 = 12