They cannot be used with other data type. What if you need to read a float or double value as input? C has functions for general input/output operations to handle this situation. These functions are
printf
and scanf
and they have following syntax.
- printf( "format", value_1, value_2, ...value_n);
- scanf("format", address_1, address_2, ...address_n);
Output Using printf
printf
is used to perform generic output operation. The first parameter, 'format' is a string that specifies how the output needs to be formatted. Other parameters are optional for printf
. The 'format' string can contain format specifiers (conversion characters) to specify how the other parameters needs to be handled. Each data type has an associated format specifier. For example, to print an integer value, you can use '%d' as format specifier, '%f' can be used for float etc. With the format specifiers, the printf
statement would look like
- int value = 10;
- printf( "%d", value);
If the first argument doesn't have any conversion characters, it will be written as it is to the standard output.
Input Using scanf
To read a data of specific type,
scanf
can be used. Same as printf
, conversion characters can be used with 'format' string of scanf
to specify the format of input data. For example, we can read an integer variable as given below.
- int value;
- scanf("%d", &value);
Note that, for
scanf
we need to pass the address of variable to which you want to read the data.
Example of
printf
and scanf
- #include <stdio.h>
- int main(void) {
- int a;
- float b;
- // No conversion characters in the first argument,
- // so it will be printed as it is
- printf("Enter an int number: ");
- scanf("%d", &a);
- printf("Enter a float number: ");
- scanf("%f", &b);
- printf("int you've entered is: %d and float you've entered is: %f", a, b);
- return 0;
- }
- Output:
- Enter an int number: 10
- Enter a float number: 99.5
- int you've entered is: 10 and float you've entered is: 99.500000
No comments:
Post a Comment