Sunday, June 16, 2013

Programming in C - 2. Input/Output Operations

C language does not have any built-in Input- Output (I/O) statements as a part of its syntax.
All the Input/Output operations are carried out through functions calls such as printf() and scanf()


scanf() 



  • General purpose console input function. Also used to input a data line containing mixed mode data.
  • syntax : scanf ("format specifier", variable_list); // end with semi-colon and case-sensitive.
  • 'format specifier' specifies the field format in which the data has to be entered.
  • 'variable list' specifies the address of the location where the data is stored.
  • use '%' before format sepecifier and '&' before a variable name
Format Specifier
  • It contains specifications for the interpretation of input data.
  • '%' conversion character.
  • list of format specifier
    • %c To read a single character
    • %d To read a decimal integer
    • %e To read a floating point value
    • %f  To read a floating point number
    • %g To read a floating point value
    • %o to read an octal value
    • %x To read an Hexadecimal value
    • %s To read a String
    • %u To read an unsigned integer
  • For reading a string 
    • scanf("%s", &st); // st contains the string value
  • For reading two values
    • scanf("%d,%d",&a,&b);\
  • Features :
    • format specification and variable list must correctly match the same order
    • The format specifier must be separated by space or comma and vairable list by comma
    • use of invalid match between format specifier and variable list will make the scanf() to terminate the reading of data

printf()

  • syntax : printf ( " format specifier ", variable list);
  • never takes the print to the new line so we use '\n' for a new line
  • eg : printf(" no of chocolates = %d \n no of sweets = %d",&a,&b); // ouput : no of chocolates = 12 [next line ] no of sweets = 13 // where a = 12 and b =13
  • list of escape sequences like \n 
    • \b     back space
    • \f      Form feed
    • \n     New line
    • \r     Carriage return
    • \t     Horizontal tab
    • \"     Double quote mark
    • \'     single quote mark
    • \0    null
    • \\     Back slash
    • \v    Vertical tab
    • \a    Alert ( rings a bell)
    • \o    Octal constant
    • \x     Hexadecimal constant

Sample Program :


First you need :
Compiler :
online compiler : codepad.org
offline compiler : http://edn.embarcadero.com/article/20633 (borlan c++ compiler)
                           http://www.digitalmars.com/ (digital mars c compiler)

01 #include <stdio.h> // imports the header file stdio.h which contains the definitions of scanf() and printf()
                                     functions.
02 void main() // execution of the program begins in the main() function
03 {
04       printf(" Hello world ");
05 } // main() ends here

output : Hello world 



Next Article : Programming in C - 3. Control Statements and Arrays

No comments:

Post a Comment