C Programming
In this tutorial we will learn to handle input output operations in C programming language using the scanf and printf function.
In the previous tutorial we learned to handle single character input output operation using the getchar() and putchar() functions.
getchar()
putchar()
We use the scanf() function to get input data from keyboard.
scanf()
Format of scanf() function.
scanf("control string", &variable1, &variable2, ...);
The control string holds the format of the data being received. variable1, variable2, ... are the names of the variables that will hold the input value.
The & ampersand symbol is the address operator specifying the address of the variable where the input value will be stored.
&
Lets explore some code to see scanf in action.
In the following example we will take two integer numbers as input from the keyboard and then print the sum.
#include <stdio.h> int main(void) { int a, b, sum; printf("Enter two integer numbers:\n"); scanf("%d %d", &a, &b); sum = a + b; printf("Sum: %d\n", sum); return 0; }
Output
Enter two integer numbers: 10 20 Sum: 30
We use the printf() function to print output.
printf()
The format of printf function to print output string.
printf("some-output-text");
In the following example we will print "Hello World" string using the printf function.
#include <stdio.h> int main(void) { printf("Hello World"); return 0; }
Format of printf function to output result using format code.
printf("some-output-text format-code", variable1, variable2, ...);
In the following example we will take an integer, double and a character value as input from the user and will output the entered data.
#include <stdio.h> int main(void) { //declare variables char ch; int i; double d; //take input from user printf("Enter an integer, a character and a double value: "); scanf("%d %c %lf", &i, &ch, &d); //output printf("Entered data\n"); printf("Integer: %d\n", i); printf("Character: %c\n", ch); printf("Double: %lf\n", d); return 0; }
Enter an integer, a character and a double value: 10 a 12.34 Entered data Integer: 10 Character: a Double: 12.340000