Learn C - 100 Code Examples & CST Typing Practice Test
C is a general-purpose, procedural programming language that provides low-level access to memory, efficient performance, and a foundation for system and application software development.
View all 100 C code examples →
Learn C with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
Hello World in C
#include <stdio.h>
int main() {
printf("Hello, World!\n");
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum: %d\n", sum);
return 0;
}
A basic C program demonstrating array manipulation, loops, and printf. Calculates sum of numbers in an array.
Sum of First N Numbers
#include <stdio.h>
int main() {
int n = 10, sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
return 0;
}
Calculates the sum of first N natural numbers using a for loop and demonstrates basic arithmetic operations.
Basic C Program Structure
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Demonstrates the basic structure of a C program using the main() function, stdio.h header file, and printf() to display output. Introduces the compilation and execution flow of a simple C program.
Algorithm to C Program Conversion
#include <stdio.h>
int main() {
int a = 10, b = 20;
int sum;
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Demonstrates how a simple algorithm can be translated into a C program. Uses sequential statements to implement step-by-step problem-solving logic and illustrates the connection between algorithm design and code implementation.
Debugging and Testing Program
#include <stdio.h>
int main() {
int a = 15, b = 5;
int result;
result = a / b;
printf("Result = %d\n", result);
return 0;
}
Demonstrates a simple program that can be tested to verify correct output after fixing common syntax, logical, and runtime errors. Highlights the debugging process and program validation.
Debugging and Testing Program
#include <stdio.h>
int main() {
int a = 15, b = 5;
int result;
result = a / b;
printf("Result = %d\n", result);
return 0;
}
Demonstrates a simple program that can be tested to verify correct output after fixing common syntax, logical, and runtime errors. Highlights the debugging process and program validation.
Constants and Literals Program
#include <stdio.h>
int main() {
const float PI = 3.14159;
int radius = 5;
float area;
area = PI * radius * radius;
printf("Area = %.2f\n", area);
return 0;
}
Demonstrates the use of the const keyword and literal values in a C program. Shows how symbolic constants help create immutable data and improve code readability.
C Tokens and Expressions Program
#include <stdio.h>
int main() {
int a = 8;
int b = 4;
int result;
result = (a + b) * 2;
printf("Result = %d\n", result);
return 0;
}
Demonstrates the use of C tokens such as identifiers, keywords, operators, and constants to create arithmetic expressions. Introduces the lexical structure of a simple C program.
Comments and Documentation Program
#include <stdio.h>
/* This program demonstrates
the use of comments in C */
int main() {
// Display a welcome message
printf("Comments make code easier to understand.\n");
return 0;
}
Demonstrates the use of single-line (//) and multi-line (/* */) comments to document C code. Shows how comments improve code readability and make programs easier to understand and maintain.
Formatted Input/Output Program
#include <stdio.h>
int main() {
int age;
float height;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height: ");
scanf("%f", &height);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
return 0;
}
Demonstrates formatted input and output using scanf() and printf(). Shows how format specifiers are used to read values from the user and display them in a formatted manner.
Character Input/Output Program
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
printf("\n");
return 0;
}
Demonstrates character input and output using getchar() and putchar(). Shows how to read a single character from the keyboard and display it on the screen.
Conversion Specification Program
#include <stdio.h>
int main() {
int age = 20;
float marks = 89.5;
char grade = 'A';
char name[] = "Alice";
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Marks: %.1f\n", marks);
printf("Grade: %c\n", grade);
return 0;
}
Demonstrates the use of conversion specifiers such as %d, %f, %c, and %s for formatted input and output. Shows how different data types are represented and displayed correctly in C.
Arithmetic Operations Program
#include <stdio.h>
int main() {
int a = 20, b = 6;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %d\n", a / b);
printf("Modulus: %d\n", a % b);
return 0;
}
Demonstrates basic arithmetic operations using addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) operators. Shows how arithmetic expressions are evaluated in C.
Relational and Logical Program
#include <stdio.h>
int main() {
int a = 15, b = 10;
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 && b > 0): %d\n", a > b && b > 0);
printf("!(a == b): %d\n", !(a == b));
return 0;
}
Demonstrates the use of relational operators (==, !=, >, <, >=, <=) and logical operators (&&, ||, !) to compare values and evaluate conditions in C.
Assignment and Ternary Program
#include <stdio.h>
int main() {
int a = 10;
int b = 5;
a += b;
b -= 2;
printf("Value of a: %d\n", a);
printf("Value of b: %d\n", b);
printf("Larger value: %d\n", (a > b) ? a : b);
return 0;
}
Demonstrates the use of assignment operators (=, +=, -=) and the conditional (ternary) operator (?:) to modify variable values and make simple decisions in C.
Bitwise Operation Program
#include <stdio.h>
int main() {
int a = 12;
int b = 10;
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
return 0;
}
Demonstrates bitwise operations using &, |, ^, ~, <<, and >> operators. Shows how individual bits of integer values can be manipulated in C.
Increment/Decrement Program
#include <stdio.h>
int main() {
int a = 5;
printf("Initial value: %d\n", a);
printf("Post-increment: %d\n", a++);
printf("After post-increment: %d\n", a);
printf("Pre-decrement: %d\n", --a);
printf("Final value: %d\n", a);
return 0;
}
Demonstrates the use of increment (++) and decrement (--) operators. Shows the effect of pre-increment, post-increment, pre-decrement, and post-decrement on variable values.
Operator Precedence Program
#include <stdio.h>
int main() {
int a = 5, b = 3, c = 2;
int result;
result = a + b * c;
printf("a + b * c = %d\n", result);
result = (a + b) * c;
printf("(a + b) * c = %d\n", result);
return 0;
}
Demonstrates how operator precedence and associativity affect the evaluation of arithmetic expressions. Shows the order in which operators are applied in C.
If Statement Program
#include <stdio.h>
int main() {
int number = 18;
if (number >= 18)
printf("Eligible to vote.\n");
return 0;
}
Demonstrates decision making using the if statement. Executes a block of code only when the specified condition evaluates to true.
If-Else Program
#include <stdio.h>
int main() {
int number = 7;
if (number % 2 == 0)
printf("The number is even.\n");
else
printf("The number is odd.\n");
return 0;
}
Demonstrates two-way decision making using the if-else statement. Executes one block of code when a condition is true and another when it is false.
Nested If Program
#include <stdio.h>
int main() {
int age = 20;
int hasID = 1;
if (age >= 18) {
if (hasID)
printf("Entry allowed.\n");
else
printf("ID required.\n");
} else {
printf("Underage.\n");
}
return 0;
}
Demonstrates nested if statements for checking multiple conditions. Shows how one if statement can be placed inside another to make hierarchical decisions.
Switch Case Program
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Option One\n");
break;
case 2:
printf("Option Two\n");
break;
default:
printf("Invalid Option\n");
}
return 0;
}
Demonstrates multi-branch selection using the switch statement. Executes different blocks of code based on the value of an expression using case labels and a default case.
Looping Program (For Loop)
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++)
printf("%d\n", i);
return 0;
}
Demonstrates repeated execution of statements using the for loop. Shows how initialization, condition checking, and increment work together to control loop iterations.
While Loop Program
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Demonstrates an entry-controlled loop using the while statement. Repeats a block of code as long as the specified condition remains true.
Do-While Program
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Demonstrates an exit-controlled loop using the do-while statement. Ensures that the loop body executes at least once before the condition is evaluated.
Break and Continue Program
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3)
continue;
if (i == 5)
break;
printf("%d\n", i);
}
return 0;
}
Demonstrates the use of break and continue statements to control loop execution. Shows how break exits a loop immediately, while continue skips the current iteration and proceeds to the next.
Exit Function Program
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Program started.\n");
exit(0);
printf("This statement will not execute.\n");
return 0;
}
Demonstrates the use of the exit() function to terminate program execution immediately. Shows how different exit status codes can be returned to the operating system.
Single Dimensional Array Program
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++)
printf("%d\n", numbers[i]);
return 0;
}
Demonstrates the use of a single-dimensional array to store and process a list of values. Shows how to access array elements using indices and iterate through the array with a loop.
Multi-Dimensional Array Program
#include <stdio.h>
int main() {
int matrix[2][2] = {{1, 2}, {3, 4}};
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
return 0;
}
Demonstrates the use of a two-dimensional array to represent a matrix. Shows how to access and process matrix elements using nested loops.
Matrix Addition/Subtraction Program
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2], i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Demonstrates matrix addition and subtraction using two-dimensional arrays. Shows how corresponding elements of two matrices are processed using nested loops.
String Input/Output Program
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%49s", name);
printf("Hello, %s!\n", name);
return 0;
}
Demonstrates string input and output using a character array. Shows how to read a string with scanf() and display it using printf().
String Length Program
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Programming";
printf("String: %s\n", text);
printf("Length: %lu\n", strlen(text));
return 0;
}
Demonstrates the use of the strlen() function to determine the length of a string. Shows how to calculate the number of characters in a character array excluding the null terminator.
String Copy Program
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[50];
strcpy(destination, source);
printf("Source: %s\n", source);
printf("Copied: %s\n", destination);
return 0;
}
Demonstrates the use of the strcpy() function to copy one string into another. Shows how string copying works using character arrays in C.
String Concatenation Program
#include <stdio.h>
#include <string.h>
int main() {
char first[50] = "Hello";
char second[] = " World!";
strcat(first, second);
printf("Concatenated String: %s\n", first);
return 0;
}
Demonstrates the use of the strcat() function to concatenate two strings. Shows how one string can be appended to the end of another character array.
String Compare Program
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result;
result = strcmp(str1, str2);
printf("Comparison Result: %d\n", result);
return 0;
}
Demonstrates the use of the strcmp() function to compare two strings. Shows how the function determines whether two strings are equal or which one comes first lexicographically.
Character Array Program
#include <stdio.h>
int main() {
char word[] = "Computer";
int i;
for (i = 0; word[i] != '\0'; i++)
printf("%c\n", word[i]);
return 0;
}
Demonstrates the use of a character array to store and manipulate strings. Shows how individual characters can be accessed and displayed using array indexing.
User Defined Function Program
#include <stdio.h>
void greet() {
printf("Welcome to C Programming!\n");
}
int main() {
greet();
return 0;
}
Demonstrates how to create and call a user-defined function. Shows how functions improve code reusability by performing a specific task when invoked.
Function with Parameters Program
#include <stdio.h>
void add(int a, int b) {
printf("Sum = %d\n", a + b);
}
int main() {
add(10, 20);
return 0;
}
Demonstrates the use of function parameters and arguments. Shows how values are passed to a user-defined function to perform a specific operation.
Function with Return Type Program
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
int result;
result = square(6);
printf("Square = %d\n", result);
return 0;
}
Demonstrates a function with a return type. Shows how a function performs a calculation, returns a value to the calling function, and uses the returned result.
Recursive Function Program
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
printf("Factorial = %d\n", factorial(5));
return 0;
}
Demonstrates recursion by creating a function that calls itself. Shows how a recursive function solves a problem by reducing it to smaller subproblems until a base case is reached.
Call by Value Program
#include <stdio.h>
void increment(int num) {
num++;
printf("Inside Function: %d\n", num);
}
int main() {
int value = 10;
increment(value);
printf("Inside Main: %d\n", value);
return 0;
}
Demonstrates call by value, where a copy of the actual argument is passed to the function. Changes made inside the function do not affect the original variable.
Call by Reference Program
#include <stdio.h>
void increment(int *num) {
(*num)++;
}
int main() {
int value = 10;
increment(&value);
printf("Updated Value: %d\n", value);
return 0;
}
Demonstrates call by reference by passing the memory address of a variable to a function using pointers. Changes made inside the function affect the original variable.
Array in Function Program
#include <stdio.h>
void display(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d\n", arr[i]);
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
display(numbers, 5);
return 0;
}
Demonstrates passing an array to a function. Shows how array elements can be accessed and processed inside a function using the array name and its size.
String in Function Program
#include <stdio.h>
void display(char str[]) {
printf("String: %s\n", str);
}
int main() {
char message[] = "Hello, C!";
display(message);
return 0;
}
Demonstrates passing a string to a function. Shows how a character array can be passed as a function argument and processed without creating a copy of the string.
Scope and Lifetime Program
#include <stdio.h>
int globalVar = 10;
void display() {
static int staticVar = 0;
int localVar = 5;
staticVar++;
printf("Global = %d, Local = %d, Static = %d\n", globalVar, localVar, staticVar);
}
int main() {
display();
display();
return 0;
}
Demonstrates the scope and lifetime of local, global, and static variables. Shows how local variables exist within a function, global variables are accessible throughout the program, and static variables retain their values between function calls.
Structure Program
#include <stdio.h>
struct Student {
char name[20];
int age;
float marks;
};
int main() {
struct Student s = {"Alice", 20, 89.5};
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Marks: %.1f\n", s.marks);
return 0;
}
Demonstrates the use of a structure to group different data types under a single user-defined data type. Shows how to declare, initialize, and access structure members.
Array of Structure Program
#include <stdio.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student students[2] = {{"Alice", 20}, {"Bob", 22}};
int i;
for (i = 0; i < 2; i++)
printf("%s %d\n", students[i].name, students[i].age);
return 0;
}
Demonstrates the use of an array of structures to store multiple records. Shows how to initialize and access individual structure elements using array indexing.
Nested Structure Program
#include <stdio.h>
struct Address {
char city[20];
};
struct Student {
char name[20];
struct Address addr;
};
int main() {
struct Student s = {"Alice", {"Kathmandu"}};
printf("Name: %s\n", s.name);
printf("City: %s\n", s.addr.city);
return 0;
}
Demonstrates the use of a nested structure by defining one structure inside another. Shows how to access members of an inner structure through the outer structure.
Structure in Function Program
#include <stdio.h>
struct Student {
char name[20];
int age;
};
void display(struct Student s) {
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
}
int main() {
struct Student s = {"Alice", 20};
display(s);
return 0;
}
Demonstrates passing a structure to a function. Shows how a complete structure can be passed as a function argument and its members accessed within the function.
Union Program
#include <stdio.h>
union Data {
int i;
float f;
char c;
};
int main() {
union Data data;
data.i = 100;
printf("Integer: %d\n", data.i);
data.f = 25.5;
printf("Float: %.1f\n", data.f);
return 0;
}
Demonstrates the use of a union to share the same memory location among different data types. Shows how only one member can hold a valid value at a time.
Pointer to Structure Program
#include <stdio.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student s = {"Alice", 20};
struct Student *ptr = &s;
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
return 0;
}
Demonstrates the use of a pointer to access structure members. Shows how the arrow (->) operator is used to access members through a structure pointer.
Pointer Basics Program
#include <stdio.h>
int main() {
int a = 10;
int *p = &a;
printf("Value: %d\n", a);
printf("Address: %p\n", &a);
printf("Pointer stores: %p\n", p);
printf("Dereferenced value: %d\n", *p);
return 0;
}
Demonstrates basic pointer usage in C. Shows how a pointer stores the memory address of a variable and how to access the value using dereferencing.
Pointer Arithmetic Program
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", *p);
p++;
}
return 0;
}
Demonstrates pointer arithmetic in C. Shows how a pointer can be incremented to traverse through array elements in memory.
Pointer and Array Program
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
int i;
for (i = 0; i < 5; i++)
printf("%d\n", *(p + i));
return 0;
}
Demonstrates the relationship between pointers and arrays. Shows how array elements can be accessed using pointer notation and pointer arithmetic.
Pointer and String Program
#include <stdio.h>
int main() {
char str[] = "Hello";
char *p = str;
while (*p != '\0') {
printf("%c", *p);
p++;
}
printf("\n");
return 0;
}
Demonstrates string manipulation using pointers. Shows how a character pointer can be used to traverse and print a string character by character.
Array of Pointers Program
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *ptr[3];
int i;
ptr[0] = &a;
ptr[1] = &b;
ptr[2] = &c;
for (i = 0; i < 3; i++)
printf("%d\n", *ptr[i]);
return 0;
}
Demonstrates the use of an array of pointers in C. Shows how multiple pointers can store the addresses of different variables and how to access their values.
Pointer to Function Program
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*funcPtr)(int, int);
int result;
funcPtr = add;
result = funcPtr(10, 20);
printf("Result = %d\n", result);
return 0;
}
Demonstrates the use of function pointers in C. Shows how a pointer can store the address of a function and call it indirectly using the pointer.
Pointer to Structure Program
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student *ptr;
ptr = (struct Student *)malloc(sizeof(struct Student));
ptr->age = 21;
printf("Age: %d\n", ptr->age);
free(ptr);
return 0;
}
Demonstrates dynamic access of a structure using a pointer. Shows how a structure pointer can be used to access and modify structure members using the arrow operator.
Dynamic Memory Allocation Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n = 3;
int i;
arr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
arr[i] = i + 1;
arr = (int *)realloc(arr, 5 * sizeof(int));
for (i = 3; i < 5; i++)
arr[i] = i + 1;
for (i = 0; i < 5; i++)
printf("%d\n", arr[i]);
free(arr);
return 0;
}
Demonstrates dynamic memory allocation in C using malloc, calloc, realloc, and free. Shows how memory can be allocated, resized, and released during runtime.
File Write Program
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
fprintf(fp, "Hello, File Handling in C!\n");
fclose(fp);
return 0;
}
Demonstrates file handling in C by writing data to a file using fopen and fprintf. Shows how to create or open a file in write mode and store formatted text into it.
File Read Program
#include <stdio.h>
int main() {
FILE *fp;
char line[100];
fp = fopen("output.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
fgets(line, sizeof(line), fp);
printf("Read using fgets: %s", line);
fclose(fp);
return 0;
}
Demonstrates file handling in C by reading data from a file using fscanf and fgets. Shows how to open a file in read mode and retrieve formatted and line-based input.
File Read Program
#include <stdio.h>
int main() {
FILE *fp;
char word[50];
char line[100];
fp = fopen("output.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// Reading first word using fscanf
fscanf(fp, "%s", word);
printf("Read using fscanf: %s\n", word);
// Reading full line using fgets
fgets(line, sizeof(line), fp);
printf("Read using fgets: %s", line);
fclose(fp);
return 0;
}
Demonstrates file handling in C by reading data from a file using fscanf and fgets. Shows how to open a file in read mode and retrieve formatted input and line-based input.
Random Access File Program
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("output.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// Move pointer to 5th position
fseek(fp, 5, SEEK_SET);
printf("Character at position 5: %c\n", fgetc(fp));
// Current position
printf("Current position: %ld\n", ftell(fp));
// Rewind to beginning
rewind(fp);
printf("First character after rewind: %c\n", fgetc(fp));
fclose(fp);
return 0;
}
Demonstrates random access file operations in C using fseek, ftell, and rewind. Shows how to move the file pointer, get its position, and reset it to the beginning of the file.
File Error Handling Program
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("Error: File could not be opened!\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
if (ferror(fp)) {
printf("\nError while reading file!\n");
}
fclose(fp);
printf("\nFile closed successfully.\n");
return 0;
}
Demonstrates safe file handling in C with proper error checking. Shows how to verify file opening, reading, and closing operations to prevent runtime errors.
Graphics Initialization Program
#include <graphics.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
printf("Graphics error!\n");
return 1;
}
outtextxy(100, 100, "Graphics Initialized");
getch();
closegraph();
return 0;
}
Demonstrates initialization of graphics mode in C using initgraph. Shows how to set up the graphics driver and load graphics mode before drawing operations.
Line Drawing Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
return 1;
}
line(100, 100, 300, 300);
getch();
closegraph();
return 0;
}
Demonstrates drawing a straight line in C using the graphics.h library. Shows how the line() function is used after initializing graphics mode with initgraph().
Circle Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
return 1;
}
circle(200, 200, 50);
getch();
closegraph();
return 0;
}
Demonstrates drawing a circle in C using the graphics.h library. Shows how the circle() function is used after initializing graphics mode with initgraph().
Arc Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
return 1;
}
arc(200, 200, 0, 135, 100);
getch();
closegraph();
return 0;
}
Demonstrates drawing an arc in C using the graphics.h library. Shows how the arc() function is used after initializing graphics mode with initgraph() to draw a portion of a circle.
Ellipse Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
return 1;
}
ellipse(200, 200, 0, 360, 100, 50);
getch();
closegraph();
return 0;
}
Demonstrates drawing an ellipse in C using the graphics.h library. Shows how the ellipse() function is used after initializing graphics mode with initgraph() to draw an ellipse shape.
Flood Fill Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
if (graphresult() != grOk) {
return 1;
}
circle(200, 200, 50);
floodfill(200, 200, WHITE);
getch();
closegraph();
return 0;
}
Demonstrates the flood fill algorithm in C using the graphics.h library. Shows how floodfill() is used to fill a bounded region with a specified color.
Screen Dimension Program
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
int maxX = getmaxx();
int maxY = getmaxy();
printf("Screen Width: %d\n", maxX);
printf("Screen Height: %d\n", maxY);
getch();
closegraph();
return 0;
}
Demonstrates how to get screen dimensions in C using the graphics.h library. Shows the use of getmaxx() and getmaxy() to retrieve maximum screen width and height.
Type Conversion & Type Casting Program (VERY IMPORTANT)
#include <stdio.h>
int main() {
int a = 10;
float b = 5.5;
float result1;
int result2;
// Implicit conversion (int -> float)
result1 = a + b;
printf("Implicit Result = %.2f\n", result1);
// Explicit casting (float -> int)
result2 = (int)b;
printf("Explicit Cast Result = %d\n", result2);
// ASCII difference example
char c1 = 'A';
char c2 = 'C';
printf("ASCII Difference = %d\n", c2 - c1);
return 0;
}
Demonstrates implicit and explicit type conversion in C. Shows how mixed data types are promoted automatically and how explicit casting controls precision and data loss during conversion.
ASCII Value Program
#include <stdio.h>
int main() {
char ch = 'A';
int ascii;
// Character to ASCII
ascii = ch;
printf("Character: %c\n", ch);
printf("ASCII Value: %d\n", ascii);
// ASCII to Character
int num = 66;
printf("Number: %d -> Character: %c\n", num, (char)num);
// Alphabet shifting example
char next = ch + 1;
printf("Next Character: %c\n", next);
return 0;
}
Demonstrates ASCII value manipulation in C. Shows how characters are internally stored as integer ASCII codes and how to convert between characters and their numeric values using type casting and format specifiers.
Pattern Printing Programs (VERY HIGH FREQUENCY)
#include <stdio.h>
int main() {
int i, j, n = 5;
int num = 1;
// Pyramid pattern
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++)
printf(" ");
for (j = 1; j <= (2 * i - 1); j++)
printf("*");
printf("\n");
}
printf("\n");
// Inverted pyramid
for (i = n; i >= 1; i--) {
for (j = 1; j <= n - i; j++)
printf(" ");
for (j = 1; j <= (2 * i - 1); j++)
printf("*");
printf("\n");
}
printf("\n");
// Floyd’s triangle
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", num);
num++;
}
printf("\n");
}
return 0;
}
Demonstrates common pattern printing programs in C using nested loops. Includes star pyramid, inverted pyramid, diamond pattern, number triangle, and Floyd’s triangle using row-column logic.
Searching Algorithm Program
#include <stdio.h>
int main() {
int arr[] = {10, 25, 30, 45, 60};
int n = 5;
int key = 30;
int i, found = 0;
// Linear Search
for (i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break;
}
}
if (!found)
printf("Element not found\n");
// Binary Search (only works on sorted array)
int low = 0, high = n - 1, mid;
found = 0;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
printf("Binary Search: Found at index %d\n", mid);
found = 1;
break;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (!found)
printf("Binary Search: Element not found\n");
return 0;
}
Demonstrates linear search to find an element in an array and optional binary search for sorted arrays. Shows step-by-step element comparison using loops and condition checking.
Sorting Algorithm Program
#include <stdio.h>
int main() {
int arr1[] = {64, 34, 25, 12, 22};
int arr2[] = {64, 34, 25, 12, 22};
int n = 5;
int i, j, temp;
// Bubble Sort
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr1[j] > arr1[j + 1]) {
temp = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = temp;
}
}
}
printf("Bubble Sorted Array:\n");
for (i = 0; i < n; i++)
printf("%d ", arr1[i]);
printf("\n");
// Selection Sort
for (i = 0; i < n - 1; i++) {
int min = i;
for (j = i + 1; j < n; j++) {
if (arr2[j] < arr2[min])
min = j;
}
temp = arr2[min];
arr2[min] = arr2[i];
arr2[i] = temp;
}
printf("Selection Sorted Array:\n");
for (i = 0; i < n; i++)
printf("%d ", arr2[i]);
return 0;
}
Demonstrates sorting of array elements using Bubble Sort and Selection Sort. Shows nested loop logic, comparisons, and swapping of elements to arrange data in ascending order.
Swap Without Temporary Variable
#include <stdio.h>
int main() {
int a = 10, b = 20;
// Arithmetic swap
a = a + b;
b = a - b;
a = a - b;
printf("After arithmetic swap: a = %d, b = %d\n", a, b);
// Reset values
a = 10;
b = 20;
// XOR swap
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After XOR swap: a = %d, b = %d\n", a, b);
return 0;
}
Demonstrates swapping two variables in C without using a temporary variable. Shows both arithmetic method and XOR bitwise method used in programming logic questions.
Pointer NULL Safety Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = NULL;
// Safe check before dereferencing
if (ptr == NULL) {
printf("Pointer is NULL, cannot access memory\n");
} else {
printf("Value = %d\n", *ptr);
}
// Allocate memory safely
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
*ptr = 100;
printf("Value after allocation = %d\n", *ptr);
free(ptr);
ptr = NULL; // avoid dangling pointer
return 0;
}
Demonstrates safe handling of NULL pointers in C. Shows how to check pointer validity before dereferencing to prevent segmentation faults and ensure memory safety.
File Record Management Program (COMBINED CRUD FILE)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int id;
char name[50];
float marks;
};
void addRecord(FILE *fp) {
struct Student s;
printf("Enter ID: ");
scanf("%d", &s.id);
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter Marks: ");
scanf("%f", &s.marks);
fwrite(&s, sizeof(s), 1, fp);
}
void displayRecords(FILE *fp) {
struct Student s;
rewind(fp);
while (fread(&s, sizeof(s), 1, fp)) {
printf("ID: %d, Name: %s, Marks: %.2f\n", s.id, s.name, s.marks);
}
}
void searchRecord(FILE *fp, int id) {
struct Student s;
rewind(fp);
while (fread(&s, sizeof(s), 1, fp)) {
if (s.id == id) {
printf("Found -> ID: %d, Name: %s, Marks: %.2f\n", s.id, s.name, s.marks);
return;
}
}
printf("Record not found\n");
}
void updateRecord(FILE *fp, int id) {
struct Student s;
rewind(fp);
while (fread(&s, sizeof(s), 1, fp)) {
if (s.id == id) {
printf("Enter new name and marks: ");
scanf("%s %f", s.name, &s.marks);
fseek(fp, -sizeof(s), SEEK_CUR);
fwrite(&s, sizeof(s), 1, fp);
printf("Record updated\n");
return;
}
}
printf("Record not found\n");
}
int main() {
FILE *fp = fopen("records.dat", "rb+\");
if (fp == NULL) {
fp = fopen("records.dat", "wb+");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
}
int choice, id;
while (1) {
printf("\n1. Add\n2. Display\n3. Search\n4. Update\n5. Exit\nChoice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addRecord(fp);
break;
case 2:
displayRecords(fp);
break;
case 3:
printf("Enter ID: ");
scanf("%d", &id);
searchRecord(fp, id);
break;
case 4:
printf("Enter ID: ");
scanf("%d", &id);
updateRecord(fp, id);
break;
case 5:
fclose(fp);
return 0;
default:
printf("Invalid choice\n");
}
}
}
Demonstrates file-based record management in C using structures and binary file operations. Shows how to perform basic CRUD operations like insert, display, search, and update using fwrite and fread.
Structure + Array + File Combined Program
#include <stdio.h>
#include <stdlib.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s[100];
int n, i;
FILE *fp;
printf("Enter number of students: ");
scanf("%d", &n);
// Input records
for (i = 0; i < n; i++) {
printf("Enter ID, Name, Marks: ");
scanf("%d %s %f", &s[i].id, s[i].name, &s[i].marks);
}
// Write to file
fp = fopen("students.dat", "wb");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
fwrite(s, sizeof(struct Student), n, fp);
fclose(fp);
// Read from file
fp = fopen("students.dat", "rb");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
printf("\nRecords from file:\n");
for (i = 0; i < n; i++) {
fread(&s[i], sizeof(struct Student), 1, fp);
printf("ID: %d, Name: %s, Marks: %.2f\n", s[i].id, s[i].name, s[i].marks);
}
fclose(fp);
return 0;
}
Demonstrates storing multiple records using structure arrays and performing file operations in C. Shows how to save and load structured data using loops for data persistence.
Menu Driven Program (VERY IMPORTANT)
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float marks;
};
struct Student s[100];
int count = 0;
void addRecord() {
printf("Enter ID, Name, Marks: ");
scanf("%d %s %f", &s[count].id, s[count].name, &s[count].marks);
count++;
}
void displayRecords() {
int i;
for (i = 0; i < count; i++) {
printf("ID: %d, Name: %s, Marks: %.2f\n", s[i].id, s[i].name, s[i].marks);
}
}
void searchRecord() {
int id, i, found = 0;
printf("Enter ID to search: ");
scanf("%d", &id);
for (i = 0; i < count; i++) {
if (s[i].id == id) {
printf("Found -> ID: %d, Name: %s, Marks: %.2f\n", s[i].id, s[i].name, s[i].marks);
found = 1;
break;
}
}
if (!found)
printf("Record not found\n");
}
int main() {
int choice;
while (1) {
printf("\n--- MENU ---\n");
printf("1. Add Record\n");
printf("2. Display Records\n");
printf("3. Search Record\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addRecord();
break;
case 2:
displayRecords();
break;
case 3:
searchRecord();
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
}
}
Demonstrates a menu-driven program in C using switch-case, loops, and functions. Shows basic record operations like add, display, search, and exit using user input handling.
Function Pointer Program (ADVANCED BUT ASKED)
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
int operate(int x, int y, int (*fp)(int, int)) {
return fp(x, y);
}
int main() {
int a = 10, b = 5;
int (*funcPtr)(int, int);
// Function pointer points to add
funcPtr = add;
printf("Addition: %d\n", funcPtr(a, b));
// Function pointer points to multiply
funcPtr = multiply;
printf("Multiplication: %d\n", funcPtr(a, b));
// Callback style function call
printf("Callback Add: %d\n", operate(a, b, add));
printf("Callback Multiply: %d\n", operate(a, b, multiply));
return 0;
}
Demonstrates function pointers in C. Shows how a function address is stored in a pointer, and how functions can be called indirectly using callback-style execution.
Preprocessor Directive Program
#include <stdio.h>
#define PI 3.14
#define SQUARE(x) ((x) * (x))
#define DEBUG 1
int main() {
int r = 5;
int area;
area = PI * SQUARE(r);
printf("Area = %.2f\n", area);
#ifdef DEBUG
printf("Debug mode is ON\n");
#endif
#if DEBUG == 1
printf("Conditional compilation active\n");
#endif
return 0;
}
Demonstrates use of C preprocessor directives including #define macros, macro functions, and conditional compilation using #ifdef and #if. Shows how compilation-time decisions are made in C.
Storage Classes Program
#include <stdio.h>
int globalVar = 10; // extern storage class (global variable)
void demoExtern() {
extern int globalVar;
printf("Extern Global Variable = %d\n", globalVar);
}
void demoStatic() {
static int count = 0;
count++;
printf("Static Count = %d\n", count);
}
int main() {
auto int a = 5; // auto (default local variable)
register int r = 10; // register storage class
printf("Auto Variable = %d\n", a);
printf("Register Variable = %d\n", r);
demoExtern();
demoStatic();
demoStatic();
demoStatic();
return 0;
}
Demonstrates storage classes in C including auto, static, extern, and register. Shows variable scope, lifetime, and memory behavior using practical examples.
Command Line Arguments Program
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Total arguments: %d\n", argc);
printf("Program Name: %s\n", argv[0]);
if (argc > 1) {
printf("Arguments passed:\n");
for (int i = 1; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
} else {
printf("No additional arguments provided\n");
}
return 0;
}
Demonstrates how to use command line arguments in C using argc and argv[]. Shows how runtime inputs are passed to a program and accessed inside main function.
Exit-Control vs Entry-Control Loop Proof Program
#include <stdio.h>
int main() {
int x = 5;
printf("Entry-Control Loop (while):\n");
while (x < 5) {
printf("This will NOT execute\n");
}
printf("While loop skipped because condition is false\n");
printf("\nExit-Control Loop (do-while):\n");
do {
printf("This will execute at least once\n");
} while (x < 5);
printf("Do-while loop executed once even though condition is false\n");
return 0;
}
Demonstrates the difference between entry-controlled (while) and exit-controlled (do-while) loops in C. Shows how condition checking affects execution flow and ensures at least one execution in do-while.
Factorial of a Number
#include <stdio.h>
int main() {
int n = 5, fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf("Factorial: %d\n", fact);
return 0;
}
Calculates factorial of a number using iterative multiplication. Demonstrates loops and basic math operations.
Check Even or Odd
#include <stdio.h>
int main() {
int n = 7;
if (n % 2 == 0)
printf("%d is Even\n", n);
else
printf("%d is Odd\n", n);
return 0;
}
Uses modulo operator to determine if a number is even or odd. Basic conditional logic demonstration.
Reverse a Number
#include <stdio.h>
int main() {
int n = 1234, rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
printf("Reversed: %d\n", rev);
return 0;
}
Reverses a number using modulo and division operations. Shows digit manipulation and while loop usage.
Find Largest of Three Numbers
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 15;
if (a >= b && a >= c)
printf("Largest: %d\n", a);
else if (b >= a && b >= c)
printf("Largest: %d\n", b);
else
printf("Largest: %d\n", c);
return 0;
}
Finds the largest number among three using nested if-else statements. Demonstrates comparison operations.
Swap Two Numbers
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Demonstrates swapping two numbers using a temporary variable. Basic variable manipulation example.
Fibonacci Series
#include <stdio.h>
int main() {
int n = 10, a = 0, b = 1, c;
printf("%d %d ", a, b);
for (int i = 2; i < n; i++) {
c = a + b;
printf("%d ", c);
a = b;
b = c;
}
return 0;
}
Generates Fibonacci sequence using iteration. Shows sequence generation and variable updates.
Palindrome Check
#include <stdio.h>
int main() {
int n = 121, orig = n, rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
if (orig == rev)
printf("Palindrome\n");
else
printf("Not Palindrome\n");
return 0;
}
Checks if a number reads the same forwards and backwards. Uses digit extraction and reversal.
Prime Number Check
#include <stdio.h>
int main() {
int n = 29, isPrime = 1;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime)
printf("%d is Prime\n", n);
else
printf("%d is Not Prime\n", n);
return 0;
}
Determines if a number is prime by checking divisibility up to square root. Shows optimization in prime checking.
Print Personal Information
#include <stdio.h>
int main() {
printf("Name: Saurav\n");
printf("Address: Nepal\n");
printf("Age: 21\n");
return 0;
}
Prints personal details like name, address, and age using printf statements.
Structure of C Program
#include <stdio.h>
int main() {
printf("This is a basic C program\n");
return 0;
}
Demonstrates the basic structure of a C program.
Syntax Error Example
#include <stdio.h>
int main() {
int a = 10;
printf("Value of a: %d\n", a);
return 0;
}
Contains a syntax error for debugging practice.
Logical Error Example
#include <stdio.h>
int main() {
int l = 10, b = 5;
int area = l + b;
printf("Area = %d\n", area);
return 0;
}
Program runs but gives incorrect output due to logical error.
Runtime Error Example
#include <stdio.h>
int main() {
int a = 10, b = 0;
int c = a / b;
printf("Result = %d\n", c);
return 0;
}
Demonstrates runtime error caused by division by zero.
Comments and Documentation Example
#include <stdio.h>
/*
Program Name: Simple Addition
Description: Adds two integers
Author: Student
*/
int main() {
int a = 5, b = 7;
int sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}
Demonstrates use of comments and documentation in C.
Frequently Asked Questions about C
What is C?
C is a general-purpose, procedural programming language that provides low-level access to memory, efficient performance, and a foundation for system and application software development.
What are the primary use cases for C?
Operating system kernels (e.g., Linux, Windows). Embedded systems and microcontrollers. Device drivers and hardware interfaces. Compilers, interpreters, and runtime systems. High-performance computing and real-time applications
What are the strengths of C?
High performance and low overhead. Portable across platforms. Fine control over system resources. Large ecosystem and mature tooling. Foundation for many other programming languages
What are the limitations of C?
No built-in memory safety (manual management required). Lacks object-oriented features. Limited standard library compared to modern languages. Error handling via return codes, no exceptions. Steeper learning curve for beginners due to pointers and memory
How can I practice C typing speed?
CodeSpeedTest offers 100+ real C code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.