Exercise: Library Functions

Questions for: Library Functions

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

int main()
{
    int i;
    i = printf("How r u\n");
    i = printf("%d\n", i);
    printf("%d\n", i);
    return 0;
}
A:
How r u
7
2
B:
How r u
8
2
C:
How r u
1
1
D:
Error: cannot assign printf to variable
Answer: B
In the program, printf() returns the number of charecters printed on the console

i = printf("How r u\n"); This line prints "How r u" with a new line character and returns the length of string printed then assign it to variable i.
So i = 8 (length of '\n' is 1).

i = printf("%d\n", i); In the previous step the value of i is 8. So it prints "8" with a new line character and returns the length of string printed then assign it to variable i. So i = 2 (length of '\n' is 1).

printf("%d\n", i); In the previous step the value of i is 2. So it prints "2".

What will the function randomize() do in Turbo C under DOS?
A:
returns a random number.
B:
returns a random number generator in the specified range.
C:
returns a random number generator with a random value based on time.
D:
return a random number with a given seed value.
Answer: C

The randomize() function initializes the random number generator with a random value based on time. You can try the sample program given below in Turbo-C, it may not work as expected in other compilers.

/* Prints a random number in the range 0 to 99 */

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(void)
{
    randomize();
    printf("Random number in the 0-99 range: %d\n", random (100));
    return 0;
}

Can you use the fprintf() to display the output on the screen?
A:
Yes
B:
No
C:
D:
Answer: A
Do like this fprintf(stdout, "%s %d %f", str, i, a);
What is the purpose of fflush() function.
A:
flushes all streams and specified streams.
B:
flushes only specified stream.
C:
flushes input/output buffer.
D:
flushes file buffer.
Answer: A
"fflush()" flush any buffered output associated with filename, which is either a file opened for writing or a shell command for redirecting output to a pipe or coprocess.

Example:
fflush(FilePointer);
fflush(NULL); flushes all streams.

Does there any function exist to convert the int or float to a string?
A:
Yes
B:
No
C:
D:
Answer: A

1. itoa() converts an integer to a string.
2. ltoa() converts a long to a string.
3. ultoa() converts an unsigned long to a string.
4. sprintf() sends formatted output to a string, so it can be used to convert any type of values to string type.

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
   int   num1 = 12345;
   float num2 = 5.12;
   char str1[20];
   char str2[20];

   itoa(num1, str1, 10); /* 10 radix value */
   printf("integer = %d string = %s \n", num1, str1);

   sprintf(str2, "%f", num2);
   printf("float = %f string = %s", num2, str2);

   return 0;
}

// Output:
// integer = 12345 string = 12345
// float = 5.120000 string = 5.120000

Ad Slot (Above Pagination)
Quiz