Art of C Programming

Code Examples

Hello World Example

This example prints "Hello, World!" to the console. It's a basic program that demonstrates the standard way to output text in C.

#include <stdio.h>

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

Ranges of char, short, int, and long

This function prints the minimum and maximum values for the built-in types: char, short, int, and long, using constants from the <limits.h> library.

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

void print_ranges() {
    printf("char: %d to %d\n", CHAR_MIN, CHAR_MAX);
    printf("short: %d to %d\n", SHRT_MIN, SHRT_MAX);
    printf("int: %d to %d\n", INT_MIN, INT_MAX);
    printf("long: %ld to %ld\n", LONG_MIN, LONG_MAX);
}

int main() {
    print_ranges();
    return 0;
}

Function getline using && and ||

This example demonstrates how to use the <stdio.h> library and the && and || operators to check if input was received and its length.

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

int main() {
    char str[100];
    if (fgets(str, sizeof(str), stdin) && strlen(str) > 0) {
        printf("Input received: %s", str);
    } else {
        printf("No input received.\n");
    }
    return 0;
}

Function htoi (hexadecimal to integer)

This function converts a hexadecimal string (starting with 0x or 0X) to its integer equivalent.

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

int htoi(char s[]) {
    int n = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        char c = tolower(s[i]);
        n *= 16;
        if (c >= '0' && c <= '9') {
            n += c - '0';
        } else if (c >= 'a' && c <= 'f') {
            n += c - 'a' + 10;
        }
    }
    return n;
}

int main() {
    printf("%d\n", htoi("0x1A3"));
    return 0;
}

Function squeeze(s1, s2)

This function removes characters from s1 that appear in s2, modifying the string s1 in place.

#include <stdio.h>

void squeeze(char s1[], char s2[]) {
    int i, j, k;
    for (i = j = 0; s1[i] != '\0'; i++) {
        for (k = 0; s2[k] != '\0' && s1[i] != s2[k]; k++);
        if (s2[k] == '\0') {
            s1[j++] = s1[i];
        }
    }
    s1[j] = '\0';
}

int main() {
    char str1[] = "hello";
    char str2[] = "aeiou";
    squeeze(str1, str2);
    printf("%s\n", str1);
    return 0;
}

Function any(s1, s2)

This function returns the position of the first occurrence of any character from s2 in s1, or -1 if no match is found.

#include <stdio.h>

int any(char s1[], char s2[]) {
    for (int i = 0; s1[i] != '\0'; i++) {
        for (int j = 0; s2[j] != '\0'; j++) {
            if (s1[i] == s2[j]) {
                return i;
            }
        }
    }
    return -1;
}

int main() {
    char str1[] = "hello";
    char str2[] = "aeiou";
    printf("First match at position: %d\n", any(str1, str2));
    return 0;
}