Search Placementyogi.com
 

printf() and scanf() in C

printf() is an inbuilt library function used to display output on the console (screen).

General form:  printf(“<format string(s)>”, <list of variable(s)>)

Example:

Lets assume: name='A', age=21, sal=50000.0

printf("Hello!");                                   /* Line 1 */
printf("%c %d %f",name,age,sal);                    /* Line 2 */
printf("name=%c age=%d salary=%f",name,age,sal);    /* Line 3 */
printf("name=%c\n age=%d\n salary=%f",name,age,sal);/* Line 4 */

Output:
------------------------------------------
Hello!                  /* Line 1 output*/
A 21 50000.000000       /* Line 2 output*/
name=A age=21 salary    /* Line 3 output*/ 
name=A                  /* Line 4 output*/
age=21
salary=50000.000000

Here %c,%d and %d etc. are called format specifiers in c

%c : for printing characters

%d : for printing integers

%f : for floating point

%s : for strings

%lf : for double

 

scanf() is an inbuilt library function used to accept input that users enter through the keyboard.

General form:  scanf(“<format string(s)>”, & <list of variable(s)>)

Note the ‘&’ symbol indicates address. 

Example:

/*Addition of two numbers*/
#include<stdio.h>
int main()
{
 int a, b, sum;
 printf("please enter the value of a and b\n");
 scanf("%d%d",&a,&b);    /* reading values from console in variables a and b */
 sum=a+b;
 printf("a=%d, b=%d, sum=%d", a,b,sum);
}

Output:
----------------------------------
please enter the value of a and b
23
45
a=23, b=45, sum=68

Syntax wise scanf() is almost similar to printf(), except for two main important differences :

  1. Within the pair of double quotes there should occur only format specifiers like %c %d %f etc.
  2. The variable name must always be preceded by the 'address of' operator & .

Note: Header file to be included for printf() and scanf() function is : #include<stdioh.> 

 

Banner to LogicGuns.com

Hide Page Information

printf and scanf in c

print and scan in c with example explanation, console input and output in c with example