Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. C

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 →
Hello World in CSum of First N NumbersBasic C Program StructureAlgorithm to C Program ConversionDebugging and Testing ProgramDebugging and Testing ProgramConstants and Literals ProgramC Tokens and Expressions ProgramComments and Documentation ProgramFormatted Input/Output ProgramCharacter Input/Output ProgramConversion Specification ProgramArithmetic Operations ProgramRelational and Logical ProgramAssignment and Ternary ProgramBitwise Operation ProgramIncrement/Decrement ProgramOperator Precedence ProgramIf Statement ProgramIf-Else ProgramNested If ProgramSwitch Case ProgramLooping Program (For Loop)While Loop ProgramDo-While ProgramBreak and Continue ProgramExit Function ProgramSingle Dimensional Array ProgramMulti-Dimensional Array ProgramMatrix Addition/Subtraction Program+70 more examples

Learn C with Real Code Examples

Updated Nov 27, 2025

Explain

C is widely used for operating systems, embedded systems, and high-performance applications.

It provides fine-grained control over memory through pointers and manual allocation.

Supports structured programming with functions, loops, and conditional statements.

Offers a minimal runtime environment, making it lightweight and fast.

Forms the basis for many modern languages like C++, C#, and Objective-C.

Core Features

Data types: int, char, float, double, arrays, structs, unions

Control structures: if, switch, for, while, do-while

Functions and modular programming

Pointers and dynamic memory management (malloc/free)

Preprocessor directives (#include, #define, #ifdef)

Basic Concepts Overview

Variables and data types - store and manipulate data

Operators - arithmetic, logical, bitwise, assignment

Control flow - loops and conditional statements

Functions - modular reusable code

Pointers - memory addresses and dynamic allocation

Project Structure

src/ - C source code files

include/ - header files (.h)

Makefile or build scripts - compilation instructions

bin/ - compiled binaries

lib/ - external libraries

Building Workflow

Write source code in `.c` files

Include necessary headers and libraries

Compile using a C compiler

Debug compile-time and runtime errors

Execute the program and test functionality

Difficulty Use Cases

Beginner: write a simple 'Hello World' program

Intermediate: implement data structures (linked lists, stacks)

Advanced: develop system utilities or embedded programs

Expert: write device drivers, kernel modules, or compiler components

Enterprise: maintain large C codebases in OS or real-time systems

Comparisons

C vs C++: C procedural, C++ object-oriented with OOP features

C vs Java: C compiled, low-level; Java runs on JVM with garbage collection

C vs Python: C high-performance, manual memory; Python interpreted, slower but higher-level

C vs Rust: C manual memory management; Rust provides safety and ownership

C vs Go: C low-level and fast; Go offers concurrency and garbage collection

Versioning Timeline

1972 - C created by Dennis Ritchie

1978 - K&R C standard published

1989 - ANSI C standard (C89) formalized

1999 - C99 standard introduced new features (inline, long long, etc.)

2018 - C18 latest standard with minor updates

Glossary

Pointer - variable storing memory address

Struct - composite data type

Array - contiguous memory storage of elements

Function - reusable code block

Preprocessor - handles macros and includes before compilation

Installation Setup

Install a C compiler (GCC, Clang, or MSVC)

Set up an IDE or text editor (VS Code, Code::Blocks, CLion)

Write source code in `.c` files

Compile using `gcc filename.c -o output`

Run the compiled program via command line or IDE

Environment Setup

Install GCC/Clang or MSVC

Set PATH to compiler binaries

Choose IDE or text editor

Write .c source files

Compile and test programs

Config Files

Makefile - build instructions

.c files - source code

.h files - header declarations

bin/ - compiled binaries

lib/ - external libraries

Cli Commands

gcc file.c -o output - compile C program

./output - run program

make - build using Makefile

gdb ./output - debug program

valgrind ./output - check memory errors

Internationalization

Supports ASCII, UTF-8, and other encodings

Wide character support via wchar.h

Strings can be localized externally

Libraries exist for multi-language support

Program logic remains independent of locale

Accessibility

Code accessible via compiler and editor

Cross-platform source code possible

Standardized libraries for portability

Supports internationalization via char encoding

Can interface with external APIs for accessibility

Ui Styling

Primarily console/CLI applications

Optional libraries for GUI (GTK, Qt with C bindings)

Text-based UIs possible via ncurses

Graphics handled via external libraries

Focus on system and logic rather than styling

State Management

Variables store temporary state

Pointers reference memory directly

Heap and stack manage dynamic and automatic memory

Global variables maintain shared state

Functions encapsulate state for modularity

Data Management

Arrays and structs organize data

Pointers manage dynamic memory

File I/O persists data externally

Memory leaks monitored via tools

Efficient memory layout for performance

Architecture

Compiled language with direct translation to machine code

Supports procedural modular design

Memory and hardware accessed via pointers and addresses

Standard libraries provide I/O, string, math, and utility functions

Preprocessor handles macro expansion and conditional compilation

Rendering Model

Source code written in .c files

Preprocessor handles macros/includes

Compiler translates code to machine instructions

Linker combines object files and libraries

Executable runs on target hardware

Architectural Patterns

Modular programming using functions

Structs for composite data

Pointers for memory and hardware access

Preprocessor for compile-time directives

Manual memory management via malloc/free

Real World Architectures

Embedded firmware for microcontrollers

Operating system kernels and drivers

High-performance scientific computation

Network and database systems

Compilers, interpreters, and system utilities

Design Principles

Procedural programming

Efficiency and performance

Low-level memory control

Portability across platforms

Minimal runtime and standard library

Scalability Guide

Use efficient algorithms and data structures

Manage memory and resources carefully

Modularize code for maintainability

Use compiler optimization flags

Profile and optimize performance-critical sections

Migration Guide

Update code to comply with C99/C18 standards

Replace deprecated functions (e.g., gets -> fgets)

Test compilation on new compilers

Verify pointer and memory usage

Refactor for portability and maintainability

Performance Notes

Compile with optimization flags (`-O2` or `-O3` for GCC/Clang)

Minimize unnecessary memory allocation

Use efficient algorithms and data structures

Inline small functions for performance

Profile with tools like gprof or Valgrind

Security Notes

Avoid buffer overflows by validating input

Free dynamically allocated memory to prevent leaks

Sanitize user input to prevent injection attacks

Use static analysis tools to detect vulnerabilities

Follow secure coding standards (CERT C, MISRA)

Monitoring Analytics

Profiling with gprof

Memory leak detection with Valgrind

Static analysis for bugs and vulnerabilities

Logging runtime metrics in applications

Performance benchmarking for optimization

Code Quality

Follow C coding standards (K&R, MISRA)

Write modular and reusable functions

Comment code and document APIs

Use static and dynamic analysis tools

Perform unit and integration tests

Practical Examples

Develop a command-line calculator

Implement a linked list or binary tree

Write a file I/O program for parsing text

Build a microcontroller firmware

Develop a network socket application

Troubleshooting

Check compiler error messages

Use debugging tools like gdb or lldb

Validate pointer usage and memory allocation

Check for buffer overflows and segmentation faults

Ensure correct header inclusion and linking

Testing Guide

Write unit tests for functions

Use assertions to validate expected behavior

Run tests under different inputs

Use Valgrind to check for memory issues

Perform integration testing for multiple modules

Deployment Options

Compile for target OS or embedded system

Cross-compile for different architectures

Package binaries with dependencies

Use static linking for portability

Deploy firmware or software in production environment

Tools Ecosystem

GCC, Clang, or MSVC compilers

Make, CMake, or Ninja build systems

GDB or LLDB debugger

Valgrind for memory analysis

Static analysis tools (Cppcheck, Clang-Tidy)

Integrations

Embedded toolchains (ARM, AVR, PIC)

Linking with C libraries or system APIs

Cross-platform development via build scripts

Integration with scripting languages via FFI

Unit testing frameworks (Unity, CMocka)

Productivity Tips

Modularize code with functions

Use header files for interface definitions

Leverage standard libraries

Debug early with GDB

Profile and optimize critical code paths

Challenges

Managing memory manually

Debugging segmentation faults

Ensuring cross-platform compatibility

Handling complex pointer logic

Writing secure and efficient code

Learning Path

Learn basic syntax and control structures

Understand pointers and memory management

Master structs, arrays, and functions

Implement standard data structures and algorithms

Build system-level or embedded applications

Skill Improvement Plan

Week 1: Learn variables, loops, and functions

Week 2: Practice pointers and arrays

Week 3: Implement structs and file I/O

Week 4: Work on memory management and dynamic allocation

Week 5: Build small system programs and practice debugging

Interview Questions

What is C and why is it important?

Explain pointers and memory management

How does C handle I/O operations?

What are structs and unions used for?

Compare C with C++ and other modern languages

Cheat Sheet

gcc file.c -o output - compile C program

./output - run compiled program

#include <stdio.h> - include standard I/O library

int *ptr; - declare pointer

malloc/free - dynamic memory allocation and deallocation

Books

The C Programming Language (K&R)

C Primer Plus

Expert C Programming

Head First C

21st Century C

Tutorials

Getting started with C programming

Pointers and memory management

Structs, arrays, and functions

File I/O and standard libraries

Advanced topics: concurrency, networking, and embedded programming

Official Docs

https://en.cppreference.com/w/c

ISO/IEC C standards documentation

GCC and Clang manuals

Community Links

StackOverflow C tag

Reddit r/C_Programming

C GitHub repositories

Online tutorials and courses

Open-source projects in C

Community Support

C GitHub repositories

StackOverflow C tag

C programming forums and mailing lists

Books and online tutorials

Open-source C projects for reference

Monetization

C is open-source and widely used

Enterprise embedded systems rely on C

Foundation for other languages increases employability

Optimized software reduces operational costs

Enables high-performance commercial software

Future Roadmap

Incremental updates via ISO C standards

Better tooling and compiler optimizations

Improved static analysis for safety

Expanded support for embedded and IoT platforms

Community-driven library ecosystem growth

When Not To Use

Rapid prototyping of applications (Python or JavaScript may be faster)

Projects requiring automatic memory management

Applications with heavy GUI development (C# or Java more suitable)

High-level web applications where frameworks simplify development

Teams lacking experience with manual memory management

Final Summary

C is a foundational, high-performance procedural programming language.

Offers manual memory management, low-level hardware access, and portability.

Ideal for system programming, embedded devices, and performance-critical applications.

Forms the basis for many modern programming languages and systems.

Requires careful coding practices for security and stability.

Faq

Is C open-source? -> C itself is a language; compilers like GCC are open-source.

Can C run on microcontrollers? -> Yes, widely used in embedded systems.

Does C have garbage collection? -> No, manual memory management required.

Is C suitable for beginners? -> Yes, but pointers and memory require careful learning.

What is the difference between C and C++? -> C is procedural, C++ adds OOP and templates.

Code Sample Descriptions

1

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.

Let’s Try →
2

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.

Let’s Try →
3

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.

Let’s Try →
4

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.

Let’s Try →
5

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.

Let’s Try →
6

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.

Let’s Try →
7

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.

Let’s Try →
8

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.

Let’s Try →
9

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.

Let’s Try →
10

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.

Let’s Try →
11

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.

Let’s Try →
12

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.

Let’s Try →
13

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.

Let’s Try →
14

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.

Let’s Try →
15

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.

Let’s Try →
16

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.

Let’s Try →
17

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.

Let’s Try →
18

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.

Let’s Try →
19

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.

Let’s Try →
20

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.

Let’s Try →
21

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.

Let’s Try →
22

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.

Let’s Try →
23

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.

Let’s Try →
24

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.

Let’s Try →
25

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.

Let’s Try →
26

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.

Let’s Try →
27

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.

Let’s Try →
28

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.

Let’s Try →
29

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.

Let’s Try →
30

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.

Let’s Try →
31

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().

Let’s Try →
32

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.

Let’s Try →
33

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.

Let’s Try →
34

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.

Let’s Try →
35

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.

Let’s Try →
36

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.

Let’s Try →
37

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.

Let’s Try →
38

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.

Let’s Try →
39

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.

Let’s Try →
40

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.

Let’s Try →
41

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.

Let’s Try →
42

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.

Let’s Try →
43

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.

Let’s Try →
44

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.

Let’s Try →
45

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.

Let’s Try →
46

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.

Let’s Try →
47

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.

Let’s Try →
48

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.

Let’s Try →
49

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.

Let’s Try →
50

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.

Let’s Try →
51

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.

Let’s Try →
52

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.

Let’s Try →
53

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.

Let’s Try →
54

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.

Let’s Try →
55

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.

Let’s Try →
56

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.

Let’s Try →
57

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.

Let’s Try →
58

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.

Let’s Try →
59

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.

Let’s Try →
60

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.

Let’s Try →
61

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.

Let’s Try →
62

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.

Let’s Try →
63

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.

Let’s Try →
64

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.

Let’s Try →
65

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.

Let’s Try →
66

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().

Let’s Try →
67

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().

Let’s Try →
68

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.

Let’s Try →
69

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.

Let’s Try →
70

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.

Let’s Try →
71

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.

Let’s Try →
72

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.

Let’s Try →
73

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.

Let’s Try →
74

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.

Let’s Try →
75

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.

Let’s Try →
76

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.

Let’s Try →
77

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.

Let’s Try →
78

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.

Let’s Try →
79

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.

Let’s Try →
80

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.

Let’s Try →
81

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.

Let’s Try →
82

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.

Let’s Try →
83

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.

Let’s Try →
84

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.

Let’s Try →
85

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.

Let’s Try →
86

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.

Let’s Try →
87

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.

Let’s Try →
88

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.

Let’s Try →
89

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.

Let’s Try →
90

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.

Let’s Try →
91

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.

Let’s Try →
92

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.

Let’s Try →
93

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.

Let’s Try →
94

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.

Let’s Try →
95

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.

Let’s Try →
96

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.

Let’s Try →
97

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.

Let’s Try →
98

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.

Let’s Try →
99

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.

Let’s Try →
100

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.

Let’s Try →

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.

Learn Other Programming Languages

ReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpJuliaView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.