/* This program does not run; it's an info example */
// C language was created in early 1970s by Dennis Ritchie.
/* Example of procedural style in C */
// Function to add two numbers
int add(int a, int b) {
return a + b; // Return sum of a and b
}
#include <stdio.h> // Include standard input-output library
int main() { // Main function where execution starts
printf("Hello, World!\n"); // Print message to console
return 0; // Exit program with success code
}
/* First program to print Hello World */
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // Output text to screen
return 0; // End of program
}
/* Command-line example */
// gcc program.c -o program
// Steps: preprocessing → compiling → assembling → linking
/* Example: Opening file in Vim */
// vim program.c
#include <stdio.h>
int main() {
// Print Hello World to console
printf("Hello, World!\n");
return 0; // Program ends successfully
}
#include <stdio.h>
int main() {
// Single line comment
printf("Comments example\n"); /* This is a
multi-line comment */
return 0;
}
#include <stdio.h>
int main() {
int num;
printf("Enter a number: "); // Prompt user
scanf("%d", &num); // Read integer input
printf("You entered: %d\n", num); // Display input
return 0;
}
/* Terminal commands */
// gcc hello.c -o hello
// ./hello
int age = 30; // Integer type
char grade = 'A'; // Single character
float pi = 3.14f; // Floating-point number
double e = 2.7182818; // Double precision float
int count; // Declared without initial value
int total = 100; // Declared with initial value
const float TAX_RATE = 0.07f; // Constant value, cannot be changed
unsigned int positive = 100; // Only positive values
long int bigNumber = 1000000L; // Large integer value
int i = 10;
float f = (float)i; // Explicit cast from int to float
printf("Size of int: %zu bytes\n", sizeof(int));
enum Color { RED, GREEN, BLUE };
enum Color favorite = GREEN;
int globalVar = 5; // Global variable
void func() {
int localVar = 10; // Local variable
}
static int counter = 0; // Retains value between calls
extern int sharedVar; // Defined in another file
int totalScore = 0; // Clear, initialized variable
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3
int remainder = a % b;// 1
int x = 5, y = 10;
if (x < y) {
printf("x is less than y\n");
}
int a = 5, b = 10;
if (a < 10 && b > 5) {
printf("Both conditions true\n");
}
int c = 10;
c += 5; // c = c + 5 = 15
int i = 0;
i++; // i becomes 1
++i; // i becomes 2
i--; // i becomes 1
int a = 5; // 0101
int b = 3; // 0011
int c = a & b; // 0001 = 1
int a = 10, b = 20;
int max = (a > b) ? a : b;
int result = 3 + 4 * 5; // result is 23, not 35
int a = 5 + 3; // Expression
printf("%d\n", a); // Statement
int val = (a + b) * c; // Clear grouping
int a = 10;
if (a > 5) {
printf("a is greater than 5\n");
}
int a = 3;
if (a > 5) {
printf("a is greater than 5\n");
} else {
printf("a is not greater than 5\n");
}
int score = 75;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 80) {
printf("Grade B\n");
} else {
printf("Grade C or below\n");
}
char grade = 'B';
switch (grade) {
case 'A': printf("Excellent\n"); break;
case 'B': printf("Good\n"); break;
default: printf("Needs Improvement\n");
}
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
for (int i = 0; i < 10; i++) {
if (i == 5)
break; // Exit loop when i is 5
printf("%d\n", i);
}
for (int i = 0; i < 10; i++) {
if (i % 2 == 0)
continue; // Skip even numbers
printf("%d\n", i);
}
// Use early returns or switches to simplify complex logic
int add(int a, int b) {
return a + b; // Return sum
}
int multiply(int x, int y); // Declaration
int multiply(int x, int y) { // Definition
return x * y;
}
void printNumber(int num) {
printf("Number: %d\n", num);
}
int square(int n) {
return n * n;
}
int result = add(5, 10);
printf("Result: %d\n", result);
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
void greet() {
printf("Hello!\n");
}
void increment(int x) {
x = x + 1; // Changes local copy only
}
// Single responsibility principle
int numbers[5]; // Array of 5 integers
int numbers[5] = {1, 2, 3, 4, 5};
int first = numbers[0]; // Access first element
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
char name[6] = {'H','e','l','l','o','\0'};
// Use size variables and loops carefully
char str[] = "Hello";
char greeting[] = "Hi there";
char name[20];
printf("Enter name: ");
scanf("%19s", name); // Read string safely
printf("Hello %s\n", name);
#include <string.h>
int len = strlen("Hello"); // 5
char dest[20];
strcpy(dest, "Copy this");
if (strcmp("abc", "def") < 0) {
printf("abc is less than def\n");
}
char s1[20] = "Hello ";
strcat(s1, "World");
char *pos = strchr("Hello", 'e'); // points to 'e'
struct Point {
int x;
int y;
};
struct Person {
char name[50];
int age;
};
struct Point p1;
p1.x = 10;
p1.y = 20;
struct Date {
int day, month, year;
};
struct Person {
char name[50];
struct Date birthday;
};
struct Point points[5];
points[0].x = 1;
void printPoint(struct Point p) {
printf("X: %d, Y: %d\n", p.x, p.y);
}
struct Point *ptr = &p1;
printf("%d\n", ptr->x);
typedef struct {
int x;
int y;
} Point;
int x = 10;
int *ptr = &x; // Pointer to x
int *p; // Pointer to int
char *c; // Pointer to char
printf("%d\n", *ptr); // Prints value of x
int arr[3] = {1, 2, 3};
int *p = arr;
p++; // Points to arr[1]
int *p = NULL;
int arr[5];
int *p = arr; // Same as &arr[0]
int **pp;
int add(int a, int b) { return a + b; }
int (*funcPtr)(int, int) = &add;
int *p = (int*)malloc(sizeof(int) * 10);
int *arr = (int*)malloc(sizeof(int) * 5);
if (arr == NULL) {
printf("Memory allocation failed\n");
}
int *arr = (int*)calloc(5, sizeof(int));
arr = (int*)realloc(arr, sizeof(int) * 10);
free(arr);
free(arr);
arr = NULL; // Avoid dangling pointer
for (int i = 0; i < 10; i++) {
p[i] = i;
}
if (p == NULL) {
printf("Allocation failed\n");
exit(1);
}
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // Open file for writing
if (file == NULL) {
printf("Failed to open file.\n");
return 1;
}
fprintf(file, "Hello File Handling!\n"); // Write to file
fclose(file); // Close the file
return 0;
}
FILE *fp = fopen("data.txt", "r"); // Open for reading
if (fp == NULL) {
printf("Cannot open file.\n");
}
fclose(fp); // Close the opened file
char buffer[100];
FILE *fp = fopen("data.txt", "r");
if (fp) {
while (fgets(buffer, sizeof(buffer), fp)) {
printf("%s", buffer); // Print each line read
}
fclose(fp);
}
FILE *fp = fopen("data.txt", "a"); // Open for appending
if (fp) {
fprintf(fp, "Appending a new line.\n");
fclose(fp);
}
FILE *fp = fopen("file.bin", "rb"); // Open binary file for reading
if (fopen("file.txt", "r") == NULL) {
perror("Error opening file");
}
fseek(fp, 0, SEEK_END); // Move to end of file
long size = ftell(fp); // Get current position (file size)
rewind(fp); // Go back to beginning
#include <stdio.h> // Includes standard input-output library before compilation
#include <stdio.h> // System header
#include "myheader.h" // User-defined header file
#define PI 3.14159
#define MAX 100
#define SQUARE(x) ((x) * (x))
int val = SQUARE(5); // val will be 25
#ifdef DEBUG
printf("Debug mode enabled\n");
#endif
#undef MAX
#pragma warning(disable:4996) // Disable specific warnings in MSVC
#error "Unsupported compiler version"
#warning "This feature is deprecated"
printf("File: %s, Line: %d\n", __FILE__, __LINE__);
// Syntax error example: missing semicolon
int x = 10
int x = 5;
printf("x = %d\n", x); // Debug output
// Compile with debugging info:
// gcc -g program.c -o program
// Run in gdb:
// gdb ./program
if (ptr == NULL) {
printf("Null pointer detected\n");
}
#include <assert.h>
assert(x > 0);
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
int fact(int n) {
if (n <= 1) return 1;
else return n * fact(n - 1);
}
int fib(int n) {
if (n <= 1) return n;
else return fib(n - 1) + fib(n - 2);
}
struct Node {
int data;
struct Node *next;
};
struct Node {
int data;
struct Node *next;
};
struct Node *head = NULL; // Start empty
head = malloc(sizeof(struct Node));
head->data = 10;
head->next = NULL;
struct Node *temp = head;
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = 5;
newNode->next = head;
head = newNode;
struct Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = 15;
newNode->next = NULL;
temp->next = newNode;
#define MAX 100
int stack[MAX];
int top = -1;
void push(int val) {
if (top < MAX - 1) {
stack[++top] = val;
}
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target)
return i; // Return index if found
}
return -1; // Not found
}
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
#include <stdlib.h>
int *ptr = (int *)malloc(sizeof(int) * 5); // Allocate memory for 5 integers
if (ptr == NULL) {
printf("Memory allocation failed.\n");
}
int *arr = (int *)calloc(5, sizeof(int)); // Allocate and zero initialize 5 ints
if (arr == NULL) {
printf("Calloc failed.\n");
}
ptr = (int *)realloc(ptr, sizeof(int) * 10); // Resize to hold 10 ints
if (ptr == NULL) {
printf("Reallocation failed.\n");
}
free(ptr); // Free dynamically allocated memory
struct Point {
int x;
int y;
};
struct Point p1;
p1.x = 10;
p1.y = 20;
void printPoint(struct Point p) {
printf("X: %d, Y: %d\n", p.x, p.y);
}
union Data {
int i;
float f;
char str[20];
};
int x = 10;
int *p = &x; // Pointer to x
printf("Value: %d\n", *p);
int arr[3] = {1, 2, 3};
int *p = arr;
printf("%d\n", *p); // 1
p++;
printf("%d\n", *p); // 2
int x = 5;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp); // 5
char str1[] = "Hello";
char *str2 = "World";
#include <string.h>
char src[] = "Hello";
char dest[10];
strcpy(dest, src);
printf("%s\n", dest);
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
#include <stdio.h>
int main() {
float pi = 3.14159;
printf("Pi rounded to 2 decimals: %.2f\n", pi);
return 0;
}
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
#include <stdio.h>
int main() {
FILE *f = fopen("data.txt", "w");
fprintf(f, "Saving this to a file.\n");
fclose(f);
return 0;
}
#include <stdio.h>
int main() {
char c;
printf("Type a character: ");
c = getchar();
printf("You typed: ");
putchar(c);
return 0;
}
#include <stdio.h>
int main() {
int x;
printf("Enter a number: ");
if (scanf("%d", &x) != 1) {
printf("Invalid input!\n");
}
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) printf("First arg: %s\n", argv[1]);
return 0;
}
#include <stdio.h>
int main() {
printf("Loading...");
fflush(stdout);
// simulate delay
for (int i = 0; i < 100000000; i++);
printf(" Done!\n");
return 0;
}
#include <stdio.h>
int main() {
printf("%-10s %5d\n", "Apples", 12);
printf("%-10s %5d\n", "Oranges", 45);
return 0;
}
#include <stdio.h>
int main() {
char input[20];
printf("Enter name: ");
if (fgets(input, sizeof(input), stdin)) {
printf("Welcome %s", input);
}
return 0;
}
#include <stdio.h>
int main() {
FILE *f = fopen("data.txt", "w");
fprintf(f, "Hello, File!\n");
fclose(f);
return 0;
}
FILE *f = fopen("example.txt", "r");
if (f == NULL) printf("File not found!\n");
else fclose(f);
char line[100];
FILE *f = fopen("readme.txt", "r");
if (fgets(line, sizeof(line), f)) printf("%s", line);
fclose(f);
FILE *f = fopen("output.txt", "w");
fprintf(f, "Writing to file.\n");
fclose(f);
FILE *f1 = fopen("file.txt", "r"); // read
FILE *f2 = fopen("file.txt", "w"); // write
FILE *f3 = fopen("file.txt", "a"); // append
FILE *f = fopen("log.txt", "r");
fseek(f, 0, SEEK_END);
long size = ftell(f);
rewind(f);
fclose(f);
FILE *f = fopen("missing.txt", "r");
if (!f) perror("Open error");
int data[3] = {1, 2, 3};
FILE *f = fopen("data.bin", "wb");
fwrite(data, sizeof(int), 3, f);
fclose(f);
// POSIX file locking (Linux/Unix only)
#include <fcntl.h>
int fd = open("file.txt", O_WRONLY);
struct flock lock = {F_WRLCK, SEEK_SET, 0, 0};
fcntl(fd, F_SETLK, &lock);
FILE *f = fopen("data.txt", "r");
if (!f) return 1;
// read or write operations
fclose(f);
int factorial(int n) {
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive call
}
int a = 5; // 0101
int b = 3; // 0011
int c = a & b; // 0001 (1)
int c = a | b; // 0111 (7)
int c = a ^ b; // 0110 (6)
int c = ~a; // Bitwise NOT of 0101
#include <stdio.h>
int main() {
int x = 5, y = 0;
printf("Before bug fix: x = %d, y = %d\n", x, y);
y = x + 3; // Fixed logic bug
printf("After bug fix: x = %d, y = %d\n", x, y);
return 0;
}
// Syntax bug fixed:
#include <stdio.h>
int main() {
int a = 10;
printf("Value: %d\n", a); // Added missing semicolon
return 0;
}
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += i;
printf("i=%d, sum=%d\n", i, sum);
}
return 0;
}
// Compile with: gcc -g prog.c -o prog
// Run GDB: gdb ./prog
// Inside GDB:
// break main
// run
// print variable
// next
// Run static analyzer (example: cppcheck):
// cppcheck your_file.c
#include <stdlib.h>
int main() {
int *arr = malloc(5 * sizeof(int));
for (int i = 0; i < 5; i++) arr[i] = i * 2;
free(arr); // Prevent memory leak
return 0;
}
#include <stdio.h>
int main() {
int *ptr = NULL;
if (ptr == NULL) {
printf("Null pointer!\n");
return 1;
}
return 0;
}
#include <pthread.h>
#include <stdio.h>
int count = 0;
void* task(void* arg) {
for (int i = 0; i < 100000; ++i) count++;
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, task, NULL);
pthread_create(&t2, NULL, task, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Final count: %d\n", count);
return 0;
}
#include <assert.h>
int square(int x) { return x * x; }
int main() {
assert(square(2) == 4);
assert(square(3) == 9);
return 0;
}
// Good practice:
// Log inputs, use assertions, and track down issue scope
#include <stdio.h>
int main() {
int x = -1;
if (x < 0) printf("Error: x is negative\n");
return 0;
}
#include <stdio.h>
#include <pthread.h>
void* run(void* arg) {
printf("Thread is running!\n");
return NULL;
}
int main() {
pthread_t t;
pthread_create(&t, NULL, run, NULL);
pthread_join(t, NULL);
return 0;
}
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t lock;
int counter = 0;
void* increase(void* arg) {
pthread_mutex_lock(&lock);
counter++;
printf("Counter: %d\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&lock, NULL);
pthread_create(&t1, NULL, increase, NULL);
pthread_create(&t2, NULL, increase, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main() {
int fd[2];
char buffer[20];
pipe(fd);
write(fd[1], "Hello", 6);
read(fd[0], buffer, 6);
printf("Received: %s\n", buffer);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server = {AF_INET, htons(8080), inet_addr("127.0.0.1")};
connect(sock, (struct sockaddr*)&server, sizeof(server));
send(sock, "Hello", strlen("Hello"), 0);
close(sock);
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) printf("Child process\n");
else printf("Parent process\n");
return 0;
}
// Example only. Requires SQLite library.
#include <sqlite3.h>
sqlite3 *db;
sqlite3_open("test.db", &db);
sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS users(id INT, name TEXT);", 0, 0, 0);
sqlite3_close(db);
#include <stdio.h>
int main() {
char name[10];
printf("Enter name: ");
fgets(name, sizeof(name), stdin);
printf("Hello %s\n", name);
return 0;
}
#include <stdio.h>
void fast_loop() {
for (int i = 0; i < 1000000; ++i);
}
int main() {
fast_loop();
return 0;
}
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
int main() {
printf("%d\n", add(2, 3));
return 0;
}
// No code, but advice:
// Practice daily challenges on platforms like LeetCode or HackerRank
// Read books like "The C Programming Language" by Kernighan & Ritchie
#include <stdio.h>
#include <stdlib.h>
int *ptr = (int *)malloc(sizeof(int) * 5);
if (ptr != NULL) {
ptr[0] = 10;
printf("%d\n", ptr[0]);
free(ptr);
}
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
#define MAX 100
int stack[MAX];
int top = -1;
void push(int val) { if (top < MAX-1) stack[++top] = val; }
#define SIZE 100
int queue[SIZE], front = 0, rear = -1;
void enqueue(int val) { if (rear < SIZE-1) queue[++rear] = val; }
struct Node {
int data;
struct Node *left, *right;
};
struct Node* root = NULL;
int graph[10][10];
graph[0][1] = 1; // edge from node 0 to 1
void bubbleSort(int a[], int n) {
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++)
if (arr[i] == key) return i;
return -1;
}
#define SIZE 10
int hash(int key) { return key % SIZE; }
int table[SIZE] = {0};
table[hash(25)] = 25;
int fib[100];
int dp(int n) {
if (n <= 1) return n;
if (fib[n]) return fib[n];
return fib[n] = dp(n-1) + dp(n-2);
}