Printing Output:
The printf function is used to print text on the screen. The data to be printed on screen is text or variable.
- If it is text, it is enclosed in quotation marks.
printf("Text to be printed")
printf(variableName)
output.c
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Note : Do not forget to put ; at the end
Adding line breaks:
\n : it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.output.c
#include <stdio.h>
int main() {
printf("Hi there! \n I am good.");
return 0;
}
Different Escape Sequences:
Escape Sequence | Description | Code |
---|---|---|
\n | New line |
|
\t | Tab - prints four spaces |
|
\a | Beep sound |
|
\b | Backspace |
|
\f | Form feed |
|
\r | Carriage return |
|
\\ | It adds backslash |
|
\' | Single quote |
|
\? | Question mark |
|
\0 | Null character |
|
Printing Numbers:
If we want to print numbers in C, we store them in variables then print variables on screen using %d (for integers). We will discuss about this in detail in variable section. Here is a brief example.output.c
#include <stdio.h>
int main() {
int num = 10;
printf("%d", num);
return 0;
}
If we write numbers in double quotes, these are not treated as numbers. Everything inside double quotation marks is a string literal which is text.
Printing Different Types of Variables:
output.c
#include <stdio.h>
int main() {
// Declare and initialize variables
int age = 30;
double pi = 3.14159265359;
char grade = 'A';
// Printing variables
printf("My age is %d years.\n", age);
printf("Pi = %.2f\n", pi);
printf("My grade is %c\n", grade);
// Printing variables with additional text
printf("Age: %d, Grade: %c.\n", age, grade);
return 0;
}
Printing data stores in variables is not our concern for now. This is just for overview. You do not need to understand it here. Just go throught it once.