C Language Programming Examples: Simple and Easy Code Samples

Faraz Logo

By Faraz -

Explore simple and easy C language programming examples. Perfect for beginners looking to practice and learn basic C coding skills.


c-language-programming-examples-simple-and-easy-code-samples.webp

Table of Contents

  1. Hello World Program
  2. Adding Two Numbers
  3. Finding the Largest Number
  4. Simple Calculator
  5. Checking for Even or Odd Number
  6. Finding the Factorial of a Number
  7. Swapping Two Numbers
  8. Printing the Fibonacci Sequence
  9. Reversing a String
  10. Palindrome Checker
  11. Counting Vowels in a String
  12. Bubble Sort
  13. Matrix Multiplication
  14. Linked List Operations
  15. Binary Search
  16. Simple File Handling
  17. Prime Number Checker
  18. Find the Largest Element in an Array
  19. Number Conversion (Decimal to Binary)
  20. Simple Interest Calculator
  21. Temperature Conversion (Fahrenheit to Celsius)

C programming is a powerful and versatile language used in a wide range of applications, from operating systems to game development. Whether you are a beginner or looking to brush up on your coding skills, practicing with simple examples can help you understand the basics and improve your coding abilities.

In this blog, we will go through various C programming examples, each designed to help you grasp the core concepts of the language. These examples will cover basic to intermediate levels, making it easy for you to follow along and learn.

Setting Up Your Development Environment for C Programming

  1. Install a C Compiler:
    • Windows: Install MinGW from MinGW or use Microsoft Visual Studio.
    • macOS: Install Xcode Command Line Tools by running xcode-select --install in Terminal.
    • Linux: Install GCC using sudo apt-get install build-essential (for Debian-based) or the equivalent for your distro.
  2. Choose an IDE or Text Editor:
  3. Write and Save Your Code:
    • Create a .c file with your code using your chosen editor or IDE.
  4. Compile and Run:
    • Using GCC: Open Terminal or Command Prompt, navigate to your file's directory, and run:
      gcc -o outputFileName fileName.c
      ./outputFileName
    • Using an IDE: Open the project, build, and run it using the IDE's build and run commands.

1. Hello World Program

Let's start with the most basic program in C: the "Hello, World!" program. This example helps you understand the structure of a C program.

#include <stdio.h>

int main() {
    printf("Hello, World!");
    return 0;
}

Explanation:

  • #include <stdio.h>: This line includes the Standard Input Output library, which allows you to use functions like printf.
  • int main() { }: This is the main function where the execution of the program begins.
  • printf("Hello, World!");: This line prints "Hello, World!" to the screen.
  • return 0;: This returns 0 to the operating system, indicating that the program executed successfully.

2. Adding Two Numbers

This example demonstrates how to add two numbers in C.

#include <stdio.h>

int main() {
    int num1, num2, sum;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    sum = num1 + num2;
    printf("Sum: %d", sum);

    return 0;
}

Explanation:

  • int num1, num2, sum;: These are integer variables to store the numbers and their sum.
  • scanf("%d %d", &num1, &num2);: This function reads two integers from the user.
  • sum = num1 + num2;: This line adds the two integers.
  • printf("Sum: %d", sum);: This prints the sum.

3. Finding the Largest Number

In this example, we'll write a program to find the largest of three numbers.

#include <stdio.h>

int main() {
    int num1, num2, num3;

    printf("Enter three integers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    if (num1 >= num2 && num1 >= num3)
        printf("Largest number is %d", num1);
    else if (num2 >= num1 && num2 >= num3)
        printf("Largest number is %d", num2);
    else
        printf("Largest number is %d", num3);

    return 0;
}

Explanation:

  • This program uses if-else statements to compare the three numbers and prints the largest one.

4. Simple Calculator

Let's create a basic calculator that performs addition, subtraction, multiplication, and division.

#include <stdio.h>

int main() {
    char operator;
    double num1, num2;

    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);

    printf("Enter two operands: ");
    scanf("%lf %lf", &num1, &num2);

    switch (operator) {
        case '+':
            printf("%.2lf + %.2lf = %.2lf", num1, num2, num1 + num2);
            break;
        case '-':
            printf("%.2lf - %.2lf = %.2lf", num1, num2, num1 - num2);
            break;
        case '*':
            printf("%.2lf * %.2lf = %.2lf", num1, num2, num1 * num2);
            break;
        case '/':
            printf("%.2lf / %.2lf = %.2lf", num1, num2, num1 / num2);
            break;
        default:
            printf("Error! Operator is not correct");
    }

    return 0;
}

Explanation:

  • switch (operator) { ... }: The switch statement selects the operation based on the operator entered by the user.
  • Each case within the switch handles one of the four basic operations: addition, subtraction, multiplication, and division.

5. Checking for Even or Odd Number

This program checks whether a number is even or odd.

#include <stdio.h>

int main() {
    int num;

    printf("Enter an integer: ");
    scanf("%d", &num);

    if (num % 2 == 0)
        printf("%d is even.", num);
    else
        printf("%d is odd.", num);

    return 0;
}

Explanation:

  • The modulus operator % is used to check if the number is divisible by 2. If the remainder is 0, the number is even; otherwise, it's odd.

6. Finding the Factorial of a Number

This program calculates the factorial of a given number.

#include <stdio.h>

int main() {
    int num, i;
    unsigned long long factorial = 1;

    printf("Enter an integer: ");
    scanf("%d", &num);

    if (num < 0)
        printf("Factorial of a negative number doesn't exist.");
    else {
        for (i = 1; i <= num; ++i) {
            factorial *= i;
        }
        printf("Factorial of %d = %llu", num, factorial);
    }

    return 0;
}

Explanation:

  • for (i = 1; i <= num; ++i): This loop multiplies all integers from 1 to the entered number.
  • The result is stored in the factorial variable.

7. Swapping Two Numbers

This example shows how to swap the values of two variables.

#include <stdio.h>

int main() {
    int num1, num2, temp;

    printf("Enter first number: ");
    scanf("%d", &num1);
    printf("Enter second number: ");
    scanf("%d", &num2);

    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping, first number = %d\n", num1);
    printf("After swapping, second number = %d\n", num2);

    return 0;
}

Explanation:

  • temp = num1;: The value of num1 is stored in temp.
  • num1 = num2;: The value of num2 is assigned to num1.
  • num2 = temp;: The original value of num1 stored in temp is now assigned to num2.

8. Printing the Fibonacci Sequence

This program prints the Fibonacci sequence up to a certain number of terms.

#include <stdio.h>

int main() {
    int i, n, t1 = 0, t2 = 1, nextTerm;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Sequence: %d, %d, ", t1, t2);

    for (i = 3; i <= n; ++i) {
        nextTerm = t1 + t2;
        printf("%d, ", nextTerm);
        t1 = t2;
        t2 = nextTerm;
    }

    return 0;
}

Explanation:

  • The first two terms of the Fibonacci sequence are always 0 and 1. The next terms are obtained by adding the two preceding terms.

9. Reversing a String

This program reverses a string entered by the user.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100], temp;
    int i, j;

    printf("Enter a string: ");
    gets(str);

    j = strlen(str) - 1;

    for (i = 0; i < j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    printf("Reversed string: %s", str);

    return 0;
}

Explanation:

  • strlen(str) - 1;: This function returns the length of the string.
  • The loop swaps the characters from the start and end of the string until it reaches the middle.

10. Palindrome Checker

This program checks if a string is a palindrome.

#include <stdio.h>
#include <stdio.h>

int main() {
    char str[100], reversedStr[100];
    int length, i, j;

    printf("Enter a string: ");
    gets(str);

    length = strlen(str);
    j = length - 1;

    for (i = 0; i < length; i++) {
        reversedStr[i] = str[j];
        j--;
    }
    reversedStr[i] = '\0';

    if (strcmp(str, reversedStr) == 0)
        printf("%s is a palindrome.", str);
    else
        printf("%s is not a palindrome.", str);

    return 0;
}

Explanation:

  • Input Handling:
    • The program starts by asking the user to enter a string and reads it using gets(). This function reads the entire line of input, including spaces, and stores it in the str array.
  • String Length Calculation:
    • It calculates the length of the input string using strlen(str). This length is stored in the variable length.
  • Reversing the String:
    • The program then reverses the input string by copying characters from the end of str to the beginning of reversedStr. It uses a loop to achieve this:
      • j starts at the last index of the original string (length - 1).
      • In each iteration, it assigns str[j] to reversedStr[i] and then decrements j.
      • After the loop, it appends the null character \0 to the end of reversedStr to properly terminate the string.
  • Palindrome Check:
    • It compares the original string str with the reversed string reversedStr using strcmp(). If the strings are identical (i.e., strcmp returns 0), it means the string is a palindrome. Otherwise, it is not.
  • Output:
    • Based on the comparison, the program prints whether the input string is a palindrome or not.
  • 11. Counting Vowels in a String

    This program counts the number of vowels in a given string.

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[100];
        int i, count = 0;
    
        printf("Enter a string: ");
        gets(str);
    
        for (i = 0; str[i] != '\0'; i++) {
            if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
                str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
                count++;
            }
        }
    
        printf("Number of vowels: %d", count);
    
        return 0;
    }

    Explanation:

    • This program iterates through each character in the string and checks if it is a vowel. If so, it increments the count.

    12. Bubble Sort

    This example demonstrates the bubble sort algorithm, a simple way to sort an array.

    #include <stdio.h>
    
    int main() {
        int n, i, j, temp;
        int arr[100];
    
        printf("Enter number of elements: ");
        scanf("%d", &n);
    
        printf("Enter %d integers: ", n);
        for (i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }
    
        for (i = 0; i < n-1; i++) {
            for (j = 0; j < n-i-1; j++) {
                if (arr[j] > arr[j+1]) {
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    
        printf("Sorted array: ");
        for (i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }
    
        return 0;
    }

    Explanation:

    • The bubble sort algorithm compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the array is sorted.

    13. Matrix Multiplication

    This program multiplies two matrices and displays the result.

    #include <stdio.h>
    
    #define MAX 10
    
    int main() {
        int m, n, p, q;
        int a[MAX][MAX], b[MAX][MAX], result[MAX][MAX];
        int i, j, k;
    
        printf("Enter rows and columns of matrix A: ");
        scanf("%d %d", &m, &n);
    
        printf("Enter rows and columns of matrix B: ");
        scanf("%d %d", &p, &q);
    
        if (n != p) {
            printf("Matrix multiplication is not possible.");
            return 1;
        }
    
        printf("Enter elements of matrix A:\n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                scanf("%d", &a[i][j]);
            }
        }
    
        printf("Enter elements of matrix B:\n");
        for (i = 0; i < p; i++) {
            for (j = 0; j < q; j++) {
                scanf("%d", &b[i][j]);
            }
        }
    
        // Initialize result matrix
        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                result[i][j] = 0;
            }
        }
    
        // Matrix multiplication
        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                for (k = 0; k < n; k++) {
                    result[i][j] += a[i][k] * b[k][j];
                }
            }
        }
    
        printf("Resultant matrix:\n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                printf("%d ", result[i][j]);
            }
            printf("\n");
        }
    
        return 0;
    }

    Explanation:

    • This program multiplies two matrices. It first checks if multiplication is possible based on the dimensions of the matrices. Then it performs the multiplication and displays the result.

    14. Linked List Operations

    This program demonstrates basic operations on a singly linked list, including insertion and display.

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Node {
        int data;
        struct Node* next;
    };
    
    void insert(struct Node** head_ref, int new_data) {
        struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
        new_node->data = new_data;
        new_node->next = (*head_ref);
        (*head_ref) = new_node;
    }
    
    void printList(struct Node* n) {
        while (n != NULL) {
            printf("%d -> ", n->data);
            n = n->next;
        }
        printf("NULL\n");
    }
    
    int main() {
        struct Node* head = NULL;
    
        insert(&head, 1);
        insert(&head, 2);
        insert(&head, 3);
        insert(&head, 4);
    
        printf("Linked list: ");
        printList(head);
    
        return 0;
    }

    Explanation:

    • This program creates a linked list, inserts nodes into it, and prints the list. It shows basic linked list operations: insertion and traversal.

    This example shows how to perform a binary search on a sorted array.

    #include <stdio.h>
    
    int binarySearch(int arr[], int size, int target) {
        int low = 0, high = size - 1, mid;
    
        while (low <= high) {
            mid = (low + high) / 2;
    
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
    
    int main() {
        int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
        int size = sizeof(arr) / sizeof(arr[0]);
        int target, result;
    
        printf("Enter the number to search: ");
        scanf("%d", &target);
    
        result = binarySearch(arr, size, target);
    
        if (result != -1) {
            printf("Element found at index %d", result);
        } else {
            printf("Element not found");
        }
    
        return 0;
    }

    Explanation:

    • This program performs a binary search on a sorted array. It repeatedly divides the search interval in half to find the target element.

    16. Simple File Handling

    This program demonstrates basic file handling operations: writing to and reading from a file.

    #include <stdio.h>
    
    int main() {
        FILE *file;
        char data[100];
    
        // Writing to a file
        file = fopen("example.txt", "w");
        if (file == NULL) {
            printf("Error opening file!");
            return 1;
        }
        fprintf(file, "Hello, File Handling in C!");
        fclose(file);
    
        // Reading from a file
        file = fopen("example.txt", "r");
        if (file == NULL) {
            printf("Error opening file!");
            return 1;
        }
        fgets(data, 100, file);
        fclose(file);
    
        printf("File content: %s", data);
    
        return 0;
    }

    Explanation:

    • This program writes a string to a file and then reads it back. It usesfopen to open files, fprintf to write data, fgets to read data, and fclose to close the file.

    17. Prime Number Checker

    This program checks if a given number is a prime number.

    #include <stdio.h>
    #include <stdbool.h>
    
    bool isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) return false;
        }
        return true;
    }
    
    int main() {
        int num;
    
        printf("Enter a number: ");
        scanf("%d", &num);
    
        if (isPrime(num)) {
            printf("%d is a prime number.", num);
        } else {
            printf("%d is not a prime number.", num);
        }
    
        return 0;
    }

    Explanation:

    • This program checks if a number is prime by dividing it by all numbers from 2 up to half of itself. If it is divisible by any of these numbers, it’s not a prime number.

    18. Find the Largest Element in an Array

    This program finds the largest element in a user-input array.

    #include <stdio.h>
    
    int main() {
        int n, i;
        int arr[100], largest;
    
        printf("Enter number of elements: ");
        scanf("%d", &n);
    
        printf("Enter %d integers: ", n);
        for (i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }
    
        largest = arr[0];
        for (i = 1; i < n; i++) {
            if (arr[i] > largest) {
                largest = arr[i];
            }
        }
    
        printf("Largest element is %d", largest);
    
        return 0;
    }

    Explanation:

    • This program finds the largest number in an array by iterating through all elements and keeping track of the largest number found.

    19. Number Conversion (Decimal to Binary)

    This program converts a decimal number to its binary equivalent.

    #include <stdio.h>
    
    void decimalToBinary(int n) {
        if (n == 0) {
            printf("0");
            return;
        }
    
        int binary[32], i = 0;
    
        while (n > 0) {
            binary[i] = n % 2;
            n = n / 2;
            i++;
        }
    
        printf("Binary equivalent: ");
        for (int j = i - 1; j >= 0; j--) {
            printf("%d", binary[j]);
        }
    }
    
    int main() {
        int num;
    
        printf("Enter a decimal number: ");
        scanf("%d", &num);
    
        decimalToBinary(num);
    
        return 0;
    }

    Explanation:

    • This program converts a decimal number to binary by repeatedly dividing the number by 2 and storing the remainders. It then prints these remainders in reverse order to show the binary representation.

    20. Simple Interest Calculator

    This program calculates simple interest based on user inputs.

    #include <stdio.h>
    
    int main() {
        float principal, rate, time, interest;
    
        printf("Enter principal amount: ");
        scanf("%f", &principal);
        printf("Enter rate of interest: ");
        scanf("%f", &rate);
        printf("Enter time period (in years): ");
        scanf("%f", &time);
    
        interest = (principal * rate * time) / 100;
    
        printf("Simple Interest: %.2f", interest);
    
        return 0;
    }

    Explanation:

    • This program calculates simple interest using the formula Interest = (Principal×Rate×Time)/100.

    21. Temperature Conversion (Fahrenheit to Celsius)

    This program converts temperature from Fahrenheit to Celsius.

    #include <stdio.h>
    
    int main() {
        float fahrenheit, celsius;
    
        printf("Enter temperature in Fahrenheit: ");
        scanf("%f", &fahrenheit);
    
        celsius = (fahrenheit - 32) * 5 / 9;
    
        printf("Temperature in Celsius: %.2f", celsius);
    
        return 0;
    }

    Explanation:

    • This program converts Fahrenheit to Celsius using the formula Celsius = (Fahrenheit−32)×5/9.

    Conclusion

    These C programming examples cover a wide range of concepts from basic to more advanced topics. By working through these examples, you can gain a deeper understanding of C programming and enhance your problem-solving skills. Experiment with these codes, make modifications, and see how the changes affect the output. This hands-on practice will solidify your understanding and make you more proficient in C programming.

    Feel free to revisit these examples anytime you need a refresher or want to test your understanding.

    That’s a wrap!

    Thank you for taking the time to read this article! I hope you found it informative and enjoyable. If you did, please consider sharing it with your friends and followers. Your support helps me continue creating content like this.

    Stay updated with our latest content by signing up for our email newsletter! Be the first to know about new articles and exciting updates directly in your inbox. Don't miss out—subscribe today!

    If you'd like to support my work directly, you can buy me a coffee . Your generosity is greatly appreciated and helps me keep bringing you high-quality articles.

    Thanks!
    Faraz 😊

    End of the article

    Subscribe to my Newsletter

    Get the latest posts delivered right to your inbox


    Latest Post