Tuesday, 28 November 2017

printf() & scanf() in C Programming

  • printf() and scanf() functions are inbuilt library functions in C programming language. These are available in C library by default. These functions are included in <stdio.h> library fucntion.
  • We have to include the <stdio.h> library function file at the beginning of our C Programming to use the printf() and scanf() function.

1. printf() Function in C Programming:

  • In C Programming, printf() function is used to print an output to the output window.
  • We could print Characters, String, Float, Integer, Octal and Hexadecimal values to the output screen.
  • We use printf() function with format specifiers (%d, %c, %s, %f, %x, %lf) to display the value of the diferent datatypes.
  • To generate a newline, we have to use "\n" within C printf() statement.
  • We have to use "\t" to generate a tab horizontally and "\v" for a vertical line.
N.B.:

  • C Programming Language is case sensitive.
  • So we have to write the keywords in lower case letter only.

Example Program for printf() Function:

#include <stdio.h>
int main()
{
   char ch = 'O';
   char str[20] = "Odia Guru Online";
   float flt = 68.322;
   int no = 143;
   double dbl = 92.123456;
   printf("Character is %c \n", ch);
   printf("String is %s \n" , str);
   printf("Float value is %f \n", flt);
   printf("Integer value is %d\n" , no);
   printf("Double value is %lf \n", dbl);
   return 0;
}

Output:

Character is O
String is Odia Guru Online
Float value is 68.322000
Integer value is 143
Double value is 92.123456

2. scanf() Function in C Programming:

  • In C Programming, scanf() function is used to get an input from the keyboard. 
  • We could get Characters, String, Float, Integer, Octal and Hexadecimal values from the keyboard.
  • We use scanf() function with format specifiers (%d, %c, %s, %f, %x, %lf) to take the value of the different datatypes from the keyboard.
  • We have to use the "&" to assign the inputted value to the variable.

Example Program for scanf() Function:

#include <stdio.h>
int main()
{
   char ch;
   char str[50];
   printf("Enter any character \n");
   scanf("%c", &ch);
   printf("Entered character is = %c \n", ch);
   printf("Enter any string ( up to 50 character ) \n");
   scanf("%s", &str);
   printf("Entered string is %s \n", str);
}

Output:

Enter any character
i
Entered character is i
Enter any string ( up to 50 character )
hello
Entered string is hello