Input and Output Operations in C
Printf() - Show Output
printf()
This function is used to print data on console (output windows) in c program. For printing the data on screen we have to use format specifiers such as %d
for int (integers), %c
for char (character), %s
for string, and %f
for float number (decimal) etc. printf() function declared in built in <stdio.h>
header file. Before using the printf() function we have to include stdio.h header file.
Examples
#include <stdio.h> // header file
#include <stdlib.h> // header file
int main(int argc, char const *argv[])
{
char x = 'P'; // char
int number = 100; // number
char str[] = "PanditProgrammer.com"; // string
printf("The value of x is %c
", x);
printf("The value of number is %d
", number);
printf("The value of str is %s
", str);
return 0;
}
Scanf() - Taking User Input
scanf()
This function is used to take user input in c program. For taking user input in variable, we have to use format specifiers such as %d for int (integers), %c for char (character), %s for string, and %f for float number (decimal) etc. scanf() function declared in built in stdio.h header file. Before using the scanf() function we have to include stdio.h header file.
NOTE: scanf()
function cannot take multi word string because space is delimeter for this function. We can use get()
instead of scanf()
.
Here is Example for string input:
#include <stdio.h> // header file
#include <stdlib.h> // header file
int main(int argc, char const *argv[])
{
char x ; // char
int number; // number
char str[50]; // string
printf("Enter a Character ");
scanf("%c",&x); // char input
printf("Enter a number ");
scanf("%d",&number); // int input
printf("Enter a string ");
scanf("%s",str); // string input (&str or str equal)
printf("The value of x is %c
", x);
printf("The value of number is %d
", number);
printf("The value of str is %s
", str);
return 0;
}