Tuesday, February 9, 2016

General Input/Output Statement

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 areprintf and scanfand they have following syntax.
  1. printf( "format", value_1, value_2, ...value_n);
  2. 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
  1. int value = 10;
  2. 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.
  1. int value;
  2. 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
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int a;
  5. float b;
  6. // No conversion characters in the first argument,
  7. // so it will be printed as it is
  8. printf("Enter an int number: ");
  9. scanf("%d", &a);
  10. printf("Enter a float number: ");
  11. scanf("%f", &b);
  12. printf("int you've entered is: %d and float you've entered is: %f", a, b);
  13. return 0;
  14. }
  15.  
  16. Output:
  17.  
  18. Enter an int number: 10
  19. Enter a float number: 99.5
  20. int you've entered is: 10 and float you've entered is: 99.500000

No comments: