Home / Programs / Input & Output on Console
Programming Example

Input & Output on Console

👁 1,828 Views
💻 Practical Program
📘 Step by Step Learning
You may want to show message on console using C. You can use printf() to write message on console. printf() also can be passed parameters inside using %d for integer numeric and %f for floating numeric. For char data type, we can use %c for passing parameter.

Program Code

#include <stdio.h>
int main() {
	int n = 10;
	float m = 1.245;
	char c = 'A';
	printf("%d \n",n);
	printf("%f \n",m);
	printf("%.2f \n",m);
	printf("%.3f \n",m);
	printf("%c \n",c);
	return 0;
}

Output

10
1.245000
1.25
1.245
A
Press any key to continue . . .

Explanation

You can see on %f that wrote floating data with 6 decimal digits. You can specify the number of decimal digit by passing numeric after dot (.), for instance, %.2f and %.3f.


The given code is a C program that demonstrates how to print values of variables of different data types to the console using the printf() function with different format specifiers.

Here's how it works:

  • The #include line includes the standard input/output library in the program.
  • The main() function is the entry point of the program.
  • Three variables n, m, and c are declared and initialized with values of integer, float, and character data types respectively.
  • The printf() function is used to print the values of the variables to the console using different format specifiers:
    • %d format specifier is used to print the integer value of n.
    • %f format specifier is used to print the floating-point value of m.
    • %.2f format specifier is used to print the floating-point value of m with two decimal places.
    • %.3f format specifier is used to print the floating-point value of m with three decimal places.
    • %c format specifier is used to print the character value of c.
  • The \n character is used to insert a newline after each output is printed.
  • Finally, the return 0; statement terminates the program and returns 0 to the operating system indicating that the program executed successfully.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.