Practical code examples and solutions for all C concepts
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
The most basic C program that outputs "Hello, World!" to the console.
#include <stdio.h> // Header file
/*
* Main function - program entry point
*/
int main() {
// Variable declaration
int number = 10;
// Output statement
printf("Number is: %d\n", number);
// Return statement
return 0;
}
Shows the basic structure of a C program with comments explaining each part.
#include <stdio.h>
#include <stdbool.h>
int main() {
// Integer types
int age = 25;
short s = 32767;
long l = 100000L;
// Floating point types
float price = 19.99f;
double pi = 3.14159;
// Character type
char grade = 'A';
// Boolean type (C99+)
bool isValid = true;
// Output values
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
printf("Is Valid: %s\n", isValid ? "true" : "false");
return 0;
}
Demonstrates different data types available in C.
#include <stdio.h>
// Define a constant using #define
#define PI 3.14159
// Define a constant using const keyword
const int MAX_SIZE = 100;
int main() {
// Literals examples
int decimal = 100; // Decimal literal
int octal = 0144; // Octal literal
int hex = 0x64; // Hexadecimal literal
float f1 = 3.14f; // Float literal
double d1 = 3.14; // Double literal
char ch = 'A'; // Character literal
char str[] = "Hello"; // String literal
// Boolean literal (C99+)
_Bool flag = 1; // Boolean literal (1 for true, 0 for false)
printf("PI: %.5f\n", PI);
printf("MAX_SIZE: %d\n", MAX_SIZE);
printf("Hexadecimal 0x64: %d\n", hex);
return 0;
}
Shows how to define constants and use different types of literals in C.
#include <stdio.h>
int main() {
int age;
float height;
char name[50];
// Getting input from user
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height (in meters): ");
scanf("%f", &height);
// Clear input buffer
while (getchar() != '\n');
// Displaying output
printf("\n--- User Information ---\n");
printf("Name: %s", name);
printf("Age: %d\n", age);
printf("Height: %.2f meters\n", height);
return 0;
}
Demonstrates basic input and output operations in C.
#include <stdio.h>
int main() {
int a = 10, b = 3;
// Arithmetic operators
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n\n", a % b);
// Relational operators
printf("a == b: %d\n", a == b);
printf("a != b: %d\n", a != b);
printf("a > b: %d\n\n", a > b);
// Logical operators
int x = 1, y = 0; // In C, 0 is false, non-zero is true
printf("x && y: %d\n", x && y);
printf("x || y: %d\n", x || y);
printf("!x: %d\n\n", !x);
// Assignment operators
int c = a;
c += b;
printf("c += b: %d\n\n", c);
// Increment/Decrement
printf("a++: %d\n", a++); // Post-increment
printf("++a: %d\n", ++a); // Pre-increment
// Bitwise operators
unsigned int u = 5, v = 9;
printf("u & v: %d\n", u & v); // AND
printf("u | v: %d\n", u | v); // OR
printf("u ^ v: %d\n", u ^ v); // XOR
return 0;
}
Shows different types of operators available in C.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
// Simple if statement
if (number > 0) {
printf("The number is positive.\n");
}
// If-else statement
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
// If-else if ladder
if (number > 0) {
printf("Positive number\n");
} else if (number < 0) {
printf("Negative number\n");
} else {
printf("Zero\n");
}
// Conditional (ternary) operator
number >= 0 ? printf("Non-negative\n") : printf("Negative\n");
return 0;
}
Demonstrates different forms of if-else conditional statements.
#include <stdio.h>
int main() {
char grade;
printf("Enter your grade (A, B, C, D, F): ");
scanf(" %c", &grade);
switch (grade) {
case 'A':
case 'a':
printf("Excellent!\n");
break;
case 'B':
case 'b':
printf("Well done!\n");
break;
case 'C':
case 'c':
printf("Good job!\n");
break;
case 'D':
case 'd':
printf("You passed, but could do better.\n");
break;
case 'F':
case 'f':
printf("Sorry, you failed.\n");
break;
default:
printf("Invalid grade entered.\n");
}
// Switch with integers
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n");
}
return 0;
}
Shows how to use switch statements for multiple conditional branches.
#include <stdio.h>
int main() {
// Basic for loop
printf("Counting from 1 to 5:\n");
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n\n");
// Nested for loop (multiplication table)
printf("Multiplication Table (1-5):\n");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%d\t", i * j);
}
printf("\n");
}
printf("\n");
// For loop with array
int numbers[] = {10, 20, 30, 40, 50};
printf("Array elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Infinite for loop (with break)
printf("Counting until 10:\n");
int count = 1;
for (;;) {
printf("%d ", count);
if (count++ >= 10) break;
}
printf("\n");
return 0;
}
Demonstrates different uses of for loops in C.
#include <stdio.h>
int main() {
// While loop example
printf("While loop - counting from 1 to 5:\n");
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n\n");
// Do-while loop example
printf("Do-while loop - counting from 1 to 5:\n");
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= 5);
printf("\n\n");
// Practical example: Sum of numbers until 0 is entered
int number, sum = 0;
printf("Enter numbers to sum (enter 0 to stop):\n");
while (1) {
scanf("%d", &number);
if (number == 0) {
break;
}
sum += number;
}
printf("Sum of entered numbers: %d\n\n", sum);
// Continue statement example
printf("Odd numbers between 1 and 10:\n");
int k = 0;
while (k < 10) {
k++;
if (k % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", k);
}
printf("\n");
return 0;
}
Shows how to use while and do-while loops in C.
#include <stdio.h>
int main() {
// Array declaration and initialization
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing array elements
printf("First element: %d\n", numbers[0]);
printf("Third element: %d\n", numbers[2]);
// Modifying array elements
numbers[1] = 25;
printf("Modified second element: %d\n", numbers[1]);
// Looping through an array
printf("All elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Calculating sum of array elements
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum of elements: %d\n", sum);
// Finding maximum element
int max = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
printf("Maximum element: %d\n", max);
// Array of characters (string)
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
printf("Vowels: ");
for (int i = 0; i < 5; i++) {
printf("%c ", vowels[i]);
}
printf("\n");
return 0;
}
Demonstrates how to work with single dimensional arrays in C.
#include <stdio.h>
int main() {
// 2D array declaration and initialization
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing and displaying 2D array
printf("2D Array elements:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Sum of all elements in 2D array
int total = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
total += matrix[i][j];
}
}
printf("Sum of all elements: %d\n\n", total);
// 3D array example
int threeD[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
printf("3D Array elements:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", threeD[i][j][k]);
}
printf("\n");
}
printf("\n");
}
// Matrix multiplication (for 2x2 matrices)
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int result[2][2] = {{0, 0}, {0, 0}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
printf("Matrix multiplication result:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Shows how to work with multi-dimensional arrays in C.
#include <stdio.h>
// Function declaration (prototype)
int add(int a, int b);
void greet();
int factorial(int n);
int main() {
// Calling functions
greet();
int result = add(5, 3);
printf("5 + 3 = %d\n", result);
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
void greet() {
printf("Hello from the greet function!\n");
}
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursion
}
}
Demonstrates basic function declaration, definition, and usage.
#include <stdio.h>
// Function with different return types
int getInteger();
float getFloat();
double getDouble();
char getChar();
void printMessage(char message[]);
// Function with different parameter types
void processNumbers(int a, float b, double c);
int findMax(int arr[], int size);
int main() {
// Calling functions with different return types
int num = getInteger();
printf("Integer: %d\n", num);
float f = getFloat();
printf("Float: %.2f\n", f);
double d = getDouble();
printf("Double: %.4f\n", d);
char c = getChar();
printf("Character: %c\n", c);
printMessage("Hello from function!");
// Function with array parameter
int numbers[] = {23, 45, 12, 67, 34};
int max = findMax(numbers, 5);
printf("Maximum number: %d\n", max);
return 0;
}
int getInteger() {
return 42;
}
float getFloat() {
return 3.14f;
}
double getDouble() {
return 3.14159;
}
char getChar() {
return 'A';
}
void printMessage(char message[]) {
printf("Message: %s\n", message);
}
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Shows functions with different parameter types and return values.
#include <stdio.h>
int main() {
int num = 10;
int *ptr; // Pointer declaration
ptr = # // Pointer assignment
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value pointed by ptr: %d\n", *ptr);
// Modifying value through pointer
*ptr = 20;
printf("Modified value of num: %d\n", num);
// Pointer to pointer
int **pptr = &ptr;
printf("Value of pptr: %p\n", pptr);
printf("Value pointed by pptr: %p\n", *pptr);
printf("Value pointed by *pptr: %d\n", **pptr);
// Pointer arithmetic
int arr[] = {10, 20, 30, 40, 50};
int *arrPtr = arr;
printf("\nArray elements using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, *(arrPtr + i));
}
// Pointer comparison
int *ptr1 = &arr[0];
int *ptr2 = &arr[4];
printf("\nPointer comparison:\n");
printf("ptr1 < ptr2: %d\n", ptr1 < ptr2);
printf("ptr1 > ptr2: %d\n", ptr1 > ptr2);
return 0;
}
Demonstrates the basics of pointers in C.
#include <stdio.h>
// Function using pointers (call by reference)
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function returning pointer
int* findMax(int *a, int *b) {
return (*a > *b) ? a : b;
}
// Function with array and pointer parameters
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
// Function to demonstrate pointer to function
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
// Using function that returns pointer
int *maxPtr = findMax(&x, &y);
printf("Maximum value: %d\n", *maxPtr);
// Array with pointer function
int numbers[] = {5, 2, 8, 1, 9};
printf("Array elements: ");
printArray(numbers, 5);
// Pointer to function
int (*operation)(int, int);
operation = add;
printf("Addition: %d\n", operation(10, 5));
operation = subtract;
printf("Subtraction: %d\n", operation(10, 5));
// Array of function pointers
int (*operations[2])(int, int) = {add, subtract};
printf("Using array of function pointers:\n");
printf("Add: %d\n", operations[0](10, 5));
printf("Subtract: %d\n", operations[1](10, 5));
return 0;
}
Shows how to use pointers with functions in C.
#include <stdio.h>
#include <string.h>
// Structure definition
struct Student {
int id;
char name[50];
float gpa;
};
// Structure with typedef
typedef struct {
int day;
int month;
int year;
} Date;
// Nested structure
typedef struct {
char title[100];
char author[50];
int pages;
Date publishedDate;
} Book;
int main() {
// Structure variable declaration and initialization
struct Student student1;
student1.id = 101;
strcpy(student1.name, "John Doe");
student1.gpa = 3.8;
printf("Student ID: %d\n", student1.id);
printf("Student Name: %s\n", student1.name);
printf("Student GPA: %.2f\n\n", student1.gpa);
// Structure initialization at declaration
struct Student student2 = {102, "Jane Smith", 3.9};
printf("Student 2 Name: %s\n\n", student2.name);
// Using typedef structure
Date today = {15, 9, 2023};
printf("Date: %d/%d/%d\n\n", today.day, today.month, today.year);
// Nested structure
Book book1;
strcpy(book1.title, "The C Programming Language");
strcpy(book1.author, "Kernighan and Ritchie");
book1.pages = 272;
book1.publishedDate.day = 22;
book1.publishedDate.month = 2;
book1.publishedDate.year = 1978;
printf("Book Title: %s\n", book1.title);
printf("Author: %s\n", book1.author);
printf("Published: %d/%d/%d\n\n",
book1.publishedDate.day,
book1.publishedDate.month,
book1.publishedDate.year);
// Array of structures
struct Student class[3] = {
{201, "Alice Johnson", 3.7},
{202, "Bob Williams", 3.5},
{203, "Charlie Brown", 3.9}
};
printf("Class Students:\n");
for (int i = 0; i < 3; i++) {
printf("%s (GPA: %.2f)\n", class[i].name, class[i].gpa);
}
// Pointer to structure
struct Student *ptr = &student1;
printf("\nAccessing via pointer: %s\n", ptr->name);
return 0;
}
Demonstrates how to define and use structures in C.
#include <stdio.h>
#include <string.h>
// Union definition
union Data {
int i;
float f;
char str[20];
};
// Union with structures
typedef struct {
char name[30];
union {
int age;
float height;
} info;
} Person;
int main() {
union Data data;
printf("Memory size occupied by union: %lu bytes\n\n", sizeof(data));
// Using integer member
data.i = 10;
printf("data.i: %d\n", data.i);
// Using float member (overwrites the same memory)
data.f = 220.5;
printf("data.f: %.2f\n", data.f);
// Using string member (overwrites the same memory)
strcpy(data.str, "C Programming");
printf("data.str: %s\n\n", data.str);
// The following would not give correct values because
// the memory has been overwritten by the last assignment
printf("data.i after string assignment: %d (incorrect)\n", data.i);
printf("data.f after string assignment: %.2f (incorrect)\n\n", data.f);
// Proper usage of union
data.i = 100;
printf("Using integer: %d\n", data.i);
data.f = 3.14;
printf("Using float: %.2f\n", data.f);
// Using union with structures
Person person;
strcpy(person.name, "John");
// Store age
person.info.age = 25;
printf("%s's age: %d\n", person.name, person.info.age);
// Store height (overwrites age)
person.info.height = 5.9;
printf("%s's height: %.1f feet\n", person.name, person.info.height);
// Practical example: storing different data types
union Number {
int intVal;
float floatVal;
double doubleVal;
};
union Number num;
num.intVal = 42;
printf("Integer value: %d\n", num.intVal);
num.floatVal = 3.14159f;
printf("Float value: %.5f\n", num.floatVal);
num.doubleVal = 2.718281828;
printf("Double value: %.9f\n", num.doubleVal);
return 0;
}
Shows how to define and use unions in C.
#include <stdio.h>
int main() {
FILE *file;
char ch;
// Writing to a file
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(file, "Hello, File I/O in C!\n");
fprintf(file, "This is a second line.\n");
fputs("This is written using fputs.\n", file);
fclose(file);
printf("Data written to file successfully.\n\n");
// Reading from a file character by character
printf("Reading file character by character:\n");
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
printf("\n\n");
// Reading from a file line by line
printf("Reading file line by line:\n");
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
printf("\n");
// Appending to a file
file = fopen("example.txt", "a");
if (file == NULL) {
printf("Error opening file for appending!\n");
return 1;
}
fprintf(file, "This line is appended to the file.\n");
fclose(file);
printf("Data appended to file successfully.\n\n");
// Binary file operations
int numbers[] = {10, 20, 30, 40, 50};
int readNumbers[5];
// Write binary data
file = fopen("data.bin", "wb");
if (file == NULL) {
printf("Error opening binary file for writing!\n");
return 1;
}
fwrite(numbers, sizeof(int), 5, file);
fclose(file);
printf("Binary data written successfully.\n");
// Read binary data
file = fopen("data.bin", "rb");
if (file == NULL) {
printf("Error opening binary file for reading!\n");
return 1;
}
fread(readNumbers, sizeof(int), 5, file);
fclose(file);
printf("Binary data read: ");
for (int i = 0; i < 5; i++) {
printf("%d ", readNumbers[i]);
}
printf("\n");
return 0;
}
Demonstrates file input/output operations in C.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file;
// Attempt to open a non-existent file for reading
file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("Error opening file: %s\n", strerror(errno));
perror("perror() output");
}
printf("\n");
// Proper error handling with file operations
file = fopen("data.txt", "w");
if (file == NULL) {
fprintf(stderr, "Failed to create data.txt\n");
return 1;
}
// Write some data
for (int i = 1; i <= 5; i++) {
if (fprintf(file, "Line %d\n", i) < 0) {
fprintf(stderr, "Error writing to file\n");
fclose(file);
return 1;
}
}
// Check for errors during write operation
if (ferror(file)) {
fprintf(stderr, "Error occurred during writing\n");
clearerr(file); // Clear error indicators
}
fclose(file);
// Using feof() to detect end of file
file = fopen("data.txt", "r");
if (file == NULL) {
fprintf(stderr, "Failed to open data.txt for reading\n");
return 1;
}
printf("Reading file contents:\n");
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
if (feof(file)) {
printf("\nReached end of file.\n");
} else if (ferror(file)) {
printf("\nError reading file.\n");
}
fclose(file);
// File positioning functions
file = fopen("data.txt", "r");
if (file == NULL) {
fprintf(stderr, "Failed to open data.txt\n");
return 1;
}
// Move to beginning of file
rewind(file);
// Get current position
long position = ftell(file);
printf("\nCurrent position: %ld\n", position);
// Read first line
fgets(buffer, sizeof(buffer), file);
printf("First line: %s", buffer);
// Get new position
position = ftell(file);
printf("Position after reading first line: %ld\n", position);
// Move to end of file
fseek(file, 0, SEEK_END);
position = ftell(file);
printf("File size: %ld bytes\n", position);
fclose(file);
return 0;
}
Shows file handling with proper error checking and positioning.