c
examples
examples.c🔧c
/*
* ============================================================================
* INPUT/OUTPUT IN C - EXAMPLES
* ============================================================================
* This file demonstrates printf, scanf, and other I/O functions.
*
* Compile: gcc -Wall examples.c -o examples
* Run: ./examples
* ============================================================================
*/
#include <stdio.h>
#include <string.h>
/*
* Example 1: Basic printf
* -----------------------
* Printing strings and basic values.
*/
void example_basic_printf() {
printf("\n=== Example 1: Basic printf ===\n");
// Simple string output
printf("Hello, World!\n");
printf("This is ");
printf("on the same line.\n");
// Printing variables
int age = 25;
float height = 5.9f;
char grade = 'A';
char name[] = "John";
printf("\nPrinting variables:\n");
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.1f feet\n", height);
printf("Grade: %c\n", grade);
}
/*
* Example 2: Format Specifiers
* ----------------------------
* All common format specifiers.
*/
void example_format_specifiers() {
printf("\n=== Example 2: Format Specifiers ===\n");
// Integer formats
int num = 42;
printf("Integer formats:\n");
printf("%%d: %d\n", num);
printf("%%i: %i\n", num);
printf("%%u: %u\n", (unsigned)num);
printf("%%o: %o (octal)\n", num);
printf("%%x: %x (hex lowercase)\n", num);
printf("%%X: %X (hex uppercase)\n", num);
// Floating-point formats
double d = 1234.56789;
printf("\nFloating-point formats:\n");
printf("%%f: %f\n", d);
printf("%%e: %e\n", d);
printf("%%E: %E\n", d);
printf("%%g: %g\n", d);
printf("%%G: %G\n", d);
// Character and string
char ch = 'A';
char str[] = "Hello";
printf("\nCharacter and string:\n");
printf("%%c: %c\n", ch);
printf("%%s: %s\n", str);
// Pointer
int x = 100;
printf("\nPointer format:\n");
printf("%%p: %p\n", (void*)&x);
// Special
printf("\nSpecial:\n");
printf("%%%%: %%\n");
}
/*
* Example 3: Width and Alignment
* ------------------------------
* Controlling output width and alignment.
*/
void example_width_alignment() {
printf("\n=== Example 3: Width and Alignment ===\n");
int num = 42;
// Width
printf("Width examples:\n");
printf("[%d]\n", num); // Default
printf("[%5d]\n", num); // Width 5, right-aligned
printf("[%10d]\n", num); // Width 10, right-aligned
// Left alignment
printf("\nAlignment:\n");
printf("[%10d] right-aligned\n", num);
printf("[%-10d] left-aligned\n", num);
// Zero padding
printf("\nZero padding:\n");
printf("[%05d]\n", num);
printf("[%010d]\n", num);
// With strings
char name[] = "Alice";
printf("\nString alignment:\n");
printf("[%10s] right-aligned\n", name);
printf("[%-10s] left-aligned\n", name);
// Dynamic width using *
int width = 15;
printf("\nDynamic width:\n");
printf("[%*d] width from variable\n", width, num);
}
/*
* Example 4: Precision
* --------------------
* Controlling decimal places and string length.
*/
void example_precision() {
printf("\n=== Example 4: Precision ===\n");
double pi = 3.14159265358979;
// Float precision
printf("Float precision:\n");
printf("%%.0f: %.0f\n", pi);
printf("%%.1f: %.1f\n", pi);
printf("%%.2f: %.2f\n", pi);
printf("%%.5f: %.5f\n", pi);
printf("%%.10f: %.10f\n", pi);
// Combined width and precision
printf("\nWidth + Precision:\n");
printf("[%10.2f]\n", pi);
printf("[%-10.2f]\n", pi);
// String precision (truncation)
char str[] = "Hello, World!";
printf("\nString precision (truncation):\n");
printf("%%.5s: %.5s\n", str);
printf("%%.10s: %.10s\n", str);
printf("%%10.5s: [%10.5s]\n", str);
}
/*
* Example 5: Sign and Space Flags
* -------------------------------
* Controlling sign display.
*/
void example_sign_flags() {
printf("\n=== Example 5: Sign and Space Flags ===\n");
int positive = 42;
int negative = -42;
// Default (no sign for positive)
printf("Default:\n");
printf("%d and %d\n", positive, negative);
// Always show sign
printf("\nAlways show sign (+):\n");
printf("%+d and %+d\n", positive, negative);
// Space for positive
printf("\nSpace for positive:\n");
printf("% d and % d\n", positive, negative);
// Combining with width
printf("\nCombined with width:\n");
printf("[%+10d]\n", positive);
printf("[%+10d]\n", negative);
}
/*
* Example 6: Alternate Form (#)
* -----------------------------
* Using # flag for alternate representations.
*/
void example_alternate_form() {
printf("\n=== Example 6: Alternate Form ===\n");
int num = 255;
// Hex with 0x prefix
printf("Hexadecimal:\n");
printf("%%x: %x\n", num);
printf("%%#x: %#x\n", num);
printf("%%#X: %#X\n", num);
// Octal with 0 prefix
printf("\nOctal:\n");
printf("%%o: %o\n", num);
printf("%%#o: %#o\n", num);
// Float with decimal point
double d = 3.0;
printf("\nFloat:\n");
printf("%%.0f: %.0f\n", d);
printf("%%#.0f: %#.0f\n", d);
}
/*
* Example 7: Basic scanf
* ----------------------
* Reading input from user.
*/
void example_basic_scanf() {
printf("\n=== Example 7: Basic scanf ===\n");
int age;
float height;
char initial;
// Reading integer
printf("Enter your age: ");
if (scanf("%d", &age) == 1) {
printf("Age: %d\n", age);
}
// Reading float
printf("Enter your height (feet): ");
if (scanf("%f", &height) == 1) {
printf("Height: %.1f feet\n", height);
}
// Reading character (with space to skip whitespace)
printf("Enter your initial: ");
if (scanf(" %c", &initial) == 1) {
printf("Initial: %c\n", initial);
}
}
/*
* Example 8: Reading Strings
* --------------------------
* Different ways to read strings.
*/
void example_string_input() {
printf("\n=== Example 8: Reading Strings ===\n");
char word[50];
char line[100];
// Clear input buffer first
int c;
while ((c = getchar()) != '\n' && c != EOF);
// Method 1: %s (stops at whitespace)
printf("Enter a single word: ");
if (scanf("%49s", word) == 1) {
printf("Word: '%s'\n", word);
}
// Clear buffer again
while ((c = getchar()) != '\n' && c != EOF);
// Method 2: %[^\n] (reads until newline)
printf("Enter a full line: ");
if (scanf(" %99[^\n]", line) == 1) {
printf("Line: '%s'\n", line);
}
// Method 3: fgets (safest)
while ((c = getchar()) != '\n' && c != EOF);
printf("Enter another line (using fgets): ");
if (fgets(line, sizeof(line), stdin) != NULL) {
// Remove newline if present
line[strcspn(line, "\n")] = '\0';
printf("Line: '%s'\n", line);
}
}
/*
* Example 9: Multiple Values
* --------------------------
* Reading multiple values at once.
*/
void example_multiple_values() {
printf("\n=== Example 9: Multiple Values ===\n");
int a, b, c;
float x, y;
// Reading multiple integers
printf("Enter three integers (space-separated): ");
if (scanf("%d %d %d", &a, &b, &c) == 3) {
printf("Values: %d, %d, %d\n", a, b, c);
printf("Sum: %d\n", a + b + c);
}
// Reading mixed types
printf("Enter an int and a float: ");
int num;
float fval;
if (scanf("%d %f", &num, &fval) == 2) {
printf("Integer: %d, Float: %.2f\n", num, fval);
}
}
/*
* Example 10: Character I/O
* -------------------------
* Using getchar and putchar.
*/
void example_char_io() {
printf("\n=== Example 10: Character I/O ===\n");
// Clear buffer
int c;
while ((c = getchar()) != '\n' && c != EOF);
printf("Enter a character: ");
c = getchar();
printf("You entered: ");
putchar(c);
putchar('\n');
printf("ASCII value: %d\n", c);
printf("Next character: ");
putchar(c + 1);
putchar('\n');
// putchar examples
printf("\nPutchar examples:\n");
putchar('H');
putchar('e');
putchar('l');
putchar('l');
putchar('o');
putchar('\n');
}
/*
* Example 11: Return Value Checking
* ---------------------------------
* Proper input validation.
*/
void example_validation() {
printf("\n=== Example 11: Input Validation ===\n");
int num;
int result;
// Clear buffer
int c;
while ((c = getchar()) != '\n' && c != EOF);
printf("Enter a number: ");
result = scanf("%d", &num);
if (result == 1) {
printf("Valid input: %d\n", num);
} else if (result == 0) {
printf("Invalid input: not a number\n");
// Clear invalid input
while ((c = getchar()) != '\n' && c != EOF);
} else {
printf("End of input or error\n");
}
}
/*
* Example 12: Formatted Table
* ---------------------------
* Creating aligned output.
*/
void example_table() {
printf("\n=== Example 12: Formatted Table ===\n");
// Table header
printf("┌────────────┬────────┬──────────┐\n");
printf("│ %-10s │ %6s │ %8s │\n", "Product", "Price", "Quantity");
printf("├────────────┼────────┼──────────┤\n");
// Table data
printf("│ %-10s │ %6.2f │ %8d │\n", "Apple", 1.50, 100);
printf("│ %-10s │ %6.2f │ %8d │\n", "Banana", 0.75, 150);
printf("│ %-10s │ %6.2f │ %8d │\n", "Orange", 2.00, 80);
printf("│ %-10s │ %6.2f │ %8d │\n", "Mango", 3.50, 50);
// Table footer
printf("└────────────┴────────┴──────────┘\n");
}
/*
* Example 13: puts() Function
* ---------------------------
* Simple string output.
*/
void example_puts() {
printf("\n=== Example 13: puts() Function ===\n");
// puts automatically adds newline
puts("This is line 1");
puts("This is line 2");
puts("This is line 3");
// Comparison with printf
printf("\nComparison:\n");
printf("printf needs \\n\n");
puts("puts adds \\n automatically");
// puts returns non-negative on success
char message[] = "Hello, World!";
int result = puts(message);
if (result >= 0) {
printf("puts succeeded\n");
}
}
/*
* Example 14: sprintf - Format to String
* --------------------------------------
* Formatting output to a string buffer.
*/
void example_sprintf() {
printf("\n=== Example 14: sprintf ===\n");
char buffer[100];
int day = 15;
int month = 8;
int year = 2024;
// Format date into string
sprintf(buffer, "%02d/%02d/%04d", day, month, year);
printf("Formatted date: %s\n", buffer);
// Build complex string
char name[] = "Alice";
int age = 25;
float score = 95.5f;
sprintf(buffer, "Name: %s, Age: %d, Score: %.1f", name, age, score);
printf("Built string: %s\n", buffer);
// Use snprintf for safety (limits characters)
char small[20];
snprintf(small, sizeof(small), "Long text that won't fit");
printf("Truncated: %s\n", small);
}
/*
* Main Function
*/
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ INPUT/OUTPUT IN C - EXAMPLES ║\n");
printf("║ Understanding printf and scanf ║\n");
printf("╚════════════════════════════════════════════════╝\n");
example_basic_printf();
example_format_specifiers();
example_width_alignment();
example_precision();
example_sign_flags();
example_alternate_form();
// Interactive examples (uncomment to run)
// example_basic_scanf();
// example_string_input();
// example_multiple_values();
// example_char_io();
// example_validation();
example_table();
example_puts();
example_sprintf();
printf("\n=== All Examples Completed! ===\n");
printf("Uncomment interactive examples in main() to test input.\n");
return 0;
}