C Printf Scanf


The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library functions, defined in stdio.h (header file).


printf() function

The printf() function is used for output. It prints the given statement to the console.

Syntax

printf("format string",argument_list);  

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.


scanf() function

The scanf() function is used for input. It reads the input data from the console.

Syntax

scanf("format string",argument_list);  

Program to print cube of given number

#include <stdio.h>  
#include <conio.h>  
void main(){  
int num;  
clrscr();  
  
printf("enter a num:");  
scanf("%d",&num);  
  
printf("cube of num is:%d ",num*num*num);  
  
getch();  
}

The scanf("%d",&number) statement reads integer number from the console and stores the given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on the console.

Output
enter a number:2
cube of number is:8

Program to print sum of 2 numbers

#include <stdio.h>  
#include <conio.h>  
void main(){  
int x=0,y=0,result=0;  
clrscr();  
  
printf("enter first number:");  
scanf("%d",&x);  
printf("enter second number:");  
scanf("%d",&y);  
  
result=x+y;  
printf("sum of 2 numbers:%d ",result);  
  
getch();  
}  
Output
enter first number:9
enter second number:9
sum of 2 numbers:18

Share this article on