printf()
/scanf()
, and more.Input means to provide the program with some data to be used in it and Output means to display data on the screen or write the data to a printer or a file.
The C programming language provides standard library functions to read any given input and display output on the console.
Before moving forward with input and output in C language, check these topics to understand the concept better :
While dealing with input-output operations in C, we use the following two streams:
Standard input or stdin is used for taking input and Standard output or stdout is used for giving output. The functions used for standard input and output are present in the stdio.h header file. Hence, to use those functions, we need to include the stdio.h header file in our program, as shown below.
#include <stdio.h>
C language offers us several built-in functions for performing input/output operations. Following are the functions used for standard input and output:
printf()
function - Show Output
scanf()
function - Take Input
getchar()
and putchar()
function
gets()
and puts()
function
In C Language, output devices like computer monitor, printer, etc. are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.
printf()
functionThe printf()
function is the most used function in the C language. This function is defined in the stdio.h header file and is used to show output on the console (standard output).
Following is how the printf()
function is defined in the C stdio.h library.
int printf(const char *format, ...);
It writes the C string pointed by the format pointer to the standard output (stdout). On success, the total number of characters written is returned.
This function is used to print a simple text sentence or value of any variable which can be of int
, char
, float
, or any other datatype.
printf()
Code ExamplesLet's start with a simple example.
1. Print a sentence
Let's print a simple sentence using the printf()
function.
#include <stdio.h>
int main() {
// using printf()
printf("Welcome to Studytonight");
return 0;
}
Welcome to Studytonight
We have seen many code examples like above, up until now in this tutorial series.
To understand the complete code and structure of a basic C language program, check Hello World Program in C.
2. Print an Integer value
We can use the printf()
function to print integer value coming from a variable using the %d
format specifier.
For example,
#include <stdio.h>
int main() {
int x = 10;
// using printf()
printf("Value of x is: %d", x);
return 0;
}
Value of x is: 10
In the program, above we have used the %d
format specifier, to specify the type of the value that will be added there. The format specifiers %d
and %i
are used for integer value.
3. Print a Character value
The %c
format specifier is used to print character variable value using the printf()
function.
#include <stdio.h>
int main() {
// using printf()
char gender = 'M';
printf("John's Gender is: %c", gender);
return 0;
}
John's Gender is: M
Inside the printf()
function we have used a single quotation, it will work fine because we have used double quotation outside. We can also use backslash character to escape the single quote like this \'
4. Print a Float and a Double value
In the code example below, we have used the printf()
function to print values of a float
and double
variable.
For float
value we use the %f
format specifier and for double
value we use the %lf
format specifier.
#include <stdio.h>
int main() {
// using printf()
float num1 = 15.50;
double num2 = 15556522.0978678;
printf("Value of num1 is: %f \n", num1);
printf("Value of num2 is: %lf", num2);
return 0;
}
Value of num1 is: 15.500000
Value of num2 is: 15556522.097868
We have used the \n
Escape sequence which is used for newline at the end of the first printf()
statement so that the next printf()
statement output is shown in the next line.
5. Print multiple outputs
We can use a single printf()
function to display values of multiple variables.
#include <stdio.h>
int main() {
// using printf() for multiple outputs
int day = 20;
int month = 11;
int year = 2021;
printf("The date is: %d-%d-%d", day, month, year);
return 0;
}
The date is: 20-11-2021
As you can see in the code example above, we can do formatting as well while printing values of multiple variables using the printf()
function.
We can also perform some simple calculations inside printf()
. Here is a simple example for that,
#include <stdio.h>
int main()
{
int a = 5, b = 6;
printf("%d", a + b);
return 0;
}
11
scanf()
functionWhen we want to take input from the user, we use the scanf()
function and store the input value into a variable.
Following is how the scanf()
function is defined in the C stdio.h library.
int scanf(const char *format, ...);
It reads data from stdin and stores it according to the parameter format into the locations pointed by the additional arguments. On success, the function returns the number of items of the argument list successfully filled.
The scanf()
function can be used to take any datatype input from user, all we have to take care is that the variable in which we store the value should have the same datatype.
Here is the syntax for scanf()
:
scanf("%x", &variable);
where, %x
is the format specifier.
Using the format specifier, we tell the compiler what type of data is in a variable and & is the address operator which tells the compiler the address of the variable so that the compiler can assign the variable with the value entered by the user.
scanf()
Code ExamplesLet's start with a simple example.
1. Input Integer value
If we have to take an integer value input from the user, we have to define an integer variable and then use the scanf()
function.
#include <stdio.h>
int main() {
// using scanf()
int user_input;
printf("Please enter a number: ");
scanf("%d", &user_input);
printf("You entered: %d", user_input);
return 0;
}
Please enter a number: 7
You entered: 7
While running the code example above, there is a button for Input at top-right corner of editor, you can click on it and provide custom value for input.
In the above code example, we have used %d
format specifier to inform the scanf()
function that user input will be of type int.
And we have also used &
symbol before the name of the variable, because &user_input
refers to the address of the user_input
variable where the input value will be stored.
2. Input Float value
Just like integer value, we can take input for any different datatype. Let's see an example for float type value.
#include <stdio.h>
int main() {
// using scanf()
float user_input;
printf("Please enter a decimal number: ");
scanf("%f", &user_input);
printf("You entered: %f", user_input);
return 0;
}
Please enter a decimal number: 7.007
You entered: 7.007
We have used the %f
format specifier and defined a float
type variable. Try doing the same for taking a double
type value as user input. The format specifier for double
is %lf
.
3. Input Character value
Let's see how we can take a simple character input from user.
#include <stdio.h>
int main() {
// using scanf()
char gender;
printf("Please enter your gender (M, F or O): ");
scanf("%c", &gender);
printf("Your gender: %c", gender);
return 0;
}
Please enter your gender (M, F or O): M
Your gender: M
4. Take Multiple Inputs from User
In the below code example, we are taking multiple inputs from the user and saving them into different variables.
#include <stdio.h>
int main() {
// using scanf() for multiple inputs
char gender;
int age;
printf("Enter your age and then gender(M, F or O): ");
scanf("%d %c", &age, &gender);
printf("You entered: %d and %c", age, gender);
return 0;
}
Enter your age and then gender(M, F or O): 32 M
You entered: 32 and M
printf()
& scanf()
The printf()
function returns the number of characters printed by it, and scanf()
function returns the number of characters read by it.
int i = printf("studytonight");
printf("Value of i is: %d", i);
studytonightValue of i is: 12
In this program printf("studytonight");
will return 12
as result, which will be stored in the variable i
, because the word studytonight has 12 characters.
The first printf()
statement will print the statement studytonight on the output too.
To print values of different data types using the printf()
statement and while taking input using the scanf()
function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable. Some examples are %c
, %d
, %f
, etc.
Here is a list of all the format specifiers.
Datatype | Format Specifier |
---|---|
int |
%d , %i |
char |
%c |
float |
%f |
double |
%lf |
short int |
%hd |
unsigned int |
%u |
long int |
%li |
long long int |
%lli |
unsigned long int |
%lu |
unsigned long long int |
%llu |
signed char |
%c |
unsigned char |
%c |
long double |
%Lf |
getchar()
& putchar()
functionsThe getchar()
function reads a character from the terminal and returns it as an integer. This function reads only a single character at a time.
Here is the syntax for the getchar()
function:
int getchar(void);
You can use this method in a loop in case you want to read more than one character.
The putchar()
function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time.
Here is the syntax for the putchar()
function:
int putchar(int character);
In case you want to display more than one character, use putchar()
method in a loop.
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}
Enter a character: Studytonight
S
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.
gets()
& puts()
functionsThe gets()
function reads a line from stdin(standard input) into the buffer pointed to by str
pointer, until either a terminating newline or EOF (end of file) occurs.
Here is the syntax for the gets()
function:
char* gets(char* str);
The puts()
function writes the string str
with a newline character ('\n') at the end to stdout. On success, a non-negative value is returned.
Here is the syntax for the gets()
function:
int puts(const char* str);
str
is the pointer to an array of chars where the C string is stored. (Don't worry if you are not able to understand this now.)
#include <stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string: ");
gets(str);
puts(str);
getch();
return 0;
}
Enter a string: Studytonight
Studytonight
When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.
The gets()
function is considered dangerous to use and should be avoided. We get a warning when we compile any code in which we have used gets()
function. This is because the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given. We can use alternatives to gets()
function, like the fgets()
function.
fgets()
functionHere is the syntax for the fgets()
function:
char* fgets(char* str, int num, FILE* stream);
It reads characters and stores them as a C string into str
until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets
stop reading, but it is considered a valid character by the function and included in the string copied to str
. On success, the function returns the str
.
For example,
#include <stdio.h>
#define MAX 10
int main()
{
char str[MAX];
fgets(str, MAX, stdin);
printf("The string is: %s", str);
return 0;
}
abcdefghijkl
The string is: abcdefghij
scanf()
and gets()
The main difference between these two functions is that scanf()
stops reading characters when it encounters a space, but gets()
reads space as a character too.
If you enter a name as Study Tonight using scanf()
it will only read and store Study and will leave the part of the string after space. But gets()
function will read it completely.
Let's see the scanf()
function in action:
#include <stdio.h>
int main() {
// using scanf()
char n1[50], n2[50];
printf("Please enter n1: ");
scanf("%s", n1);
printf("You entered: %s", n1);
return 0;
}
Please enter n1: study tonight
You entered: study
Now let's see the gets()
function in action:
#include <stdio.h>
int main() {
// using scanf()
char n1[50], n2[50];
printf("Please enter n1: ");
gets(n1);
printf("You entered: %s", n1);
return 0;
}
Please enter n1: study tonight
You entered: study tonight
In this tutorial we learned about Input and Output in the C language. With many code examples, we understood how to use printf()
function and scanf()
function to show output to user and take input from the user.
We also learned about a few other functions used for showing output and taking user input.