C documentation V1 Help

Displaying Output

Displaying output is a fundamental aspect of C programming, allowing you to communicate information to users through the console. In this section, we'll explore various techniques and functions used to display output in C, focusing on the commonly used printf() function.

The printf() Function

The printf() function is the primary tool for output in C. It allows you to format and display text, variables, and other data on the console. Here's a basic example:

#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }

In this example, the string "Hello, World!\n" is printed to the console, where \n represents a newline character.

Formatting Output

printf() supports various format specifiers that control the display of different types of data. Here are some common ones:

  • %d: Integer

  • %f: Float

  • %c: Character

  • %s: String

#include <stdio.h> int main() { int age = 25; float height = 5.8; char grade = 'A'; char name[] = "John"; printf("Age: %d\n", age); printf("Height: %.1f feet\n", height); printf("Grade: %c\n", grade); printf("Name: %s\n", name); return 0; }

Escape Sequences

Escape sequences are special characters that represent non-printable characters or provide specific formatting. Common escape sequences include \n for a newline, \t for a tab, and " for a double quote.

#include <stdio.h> int main() { printf("This is a new line.\n"); printf("This text is\ttabbed.\n"); printf("He said, \"Hello!\"\n"); return 0; }

Field Width and Precision

You can control the field width and precision of the displayed values using numeric parameters in the format specifier. For example, %5d specifies a field width of 5 for an integer.

#include <stdio.h> int main() { int num1 = 123; float num2 = 12.3456; printf("Number 1: %5d\n", num1); printf("Number 2: %.2f\n", num2); return 0; }

Concatenating Strings

You can concatenate strings using the %s specifier. Additionally, you can use multiple specifiers in a single printf() statement.

#include <stdio.h> int main() { char first_name[] = "John"; char last_name[] = "Doe"; printf("Full Name: %s %s\n", first_name, last_name); return 0; }

Conclusion

Displaying output in C is achieved through the versatile printf() function. By understanding format specifiers, escape sequences, and additional options, you can present information effectively to users. This is a fundamental skill that lays the groundwork for creating interactive and informative C programs.

In the upcoming sections, we'll explore more advanced concepts in C programming. If you have specific questions or areas you'd like to explore further, feel free to ask. Happy coding!

Last modified: 25 February 2024