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

typedef struct {
    int *list;
    short count;
} Factors;

void xferFactors( Factors *fctrs, int *flist, int flix )
{
    int ix, ij;
    int newSize = fctrs->count + flix;
    if (newSize > flix)  {
        fctrs->list = realloc( fctrs->list, newSize * sizeof(int));
    }
    else {
        fctrs->list = malloc(  newSize * sizeof(int));
    }
    for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) {
        fctrs->list[ix] = flist[ij];
    }
    fctrs->count = newSize;
}

Factors *factor( int num, Factors *fctrs)
{
    int flist[301], flix;
    int dvsr;
    flix = 0;
    fctrs->count = 0;
    free(fctrs->list);
    fctrs->list = NULL;
    for (dvsr=1; dvsr*dvsr < num; dvsr++) {
        if (num % dvsr != 0) continue;
        if ( flix == 300) {
            xferFactors( fctrs, flist, flix );
            flix = 0;
        }
        flist[flix++] = dvsr;
        flist[flix++] = num/dvsr;
    }
    if (dvsr*dvsr == num)
        flist[flix++] = dvsr;
    if (flix > 0)
        xferFactors( fctrs, flist, flix );

    return fctrs;
}

int main(int argc, char*argv[])
{
    int nums2factor[] = { 2059, 223092870, 3135, 45 };
    Factors ftors = { NULL, 0};
    char sep;
    int i,j;

    for (i=0; i<4; i++) {
        factor( nums2factor[i], &ftors );
        printf("\nfactors of %d are:\n  ", nums2factor[i]);
        sep = ' ';
        for (j=0; j<ftors.count; j++) {
            printf("%c %d", sep, ftors.list[j]);
            sep = ',';
        }
        printf("\n");
    }
    return 0;
}

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

/* 65536 = 2^16, so we can factor all 32 bit ints */
char bits[65536];

typedef unsigned long ulong;
ulong primes[7000], n_primes;

typedef struct { ulong p, e; } prime_factor; /* prime, exponent */

void sieve()
{
	int i, j;
	memset(bits, 1, 65536);
	bits[0] = bits[1] = 0;
	for (i = 0; i < 256; i++)
		if (bits[i])
			for (j = i * i; j < 65536; j += i)
				bits[j] = 0;

	/* collect primes into a list. slightly faster this way if dealing with large numbers */
	for (i = j = 0; i < 65536; i++)
		if (bits[i]) primes[j++] = i;

	n_primes = j;
}

int get_prime_factors(ulong n, prime_factor *lst)
{
	ulong i, e, p;
	int len = 0;

	for (i = 0; i < n_primes; i++) {
		p = primes[i];
		if (p * p > n) break;
		for (e = 0; !(n % p); n /= p, e++);
		if (e) {
			lst[len].p = p;
			lst[len++].e = e;
		}
	}

	return n == 1 ? len : (lst[len].p = n, lst[len].e = 1, ++len);
}

int ulong_cmp(const void *a, const void *b)
{
	return *(const ulong*)a < *(const ulong*)b ? -1 : *(const ulong*)a > *(const ulong*)b;
}

int get_factors(ulong n, ulong *lst)
{
	int n_f, len, len2, i, j, k, p;
	prime_factor f[100];

	n_f = get_prime_factors(n, f);

	len2 = len = lst[0] = 1;
	/* L = (1); L = (L, L * p**(1 .. e)) forall((p, e)) */
	for (i = 0; i < n_f; i++, len2 = len)
		for (j = 0, p = f[i].p; j < f[i].e; j++, p *= f[i].p)
			for (k = 0; k < len2; k++)
				lst[len++] = lst[k] * p;

	qsort(lst, len, sizeof(ulong), ulong_cmp);
	return len;
}

int main()
{
	ulong fac[10000];
	int len, i, j;
	ulong nums[] = {3, 120, 1024, 2UL*2*2*2*3*3*3*5*5*7*11*13*17*19 };

	sieve();

	for (i = 0; i < 4; i++) {
		len = get_factors(nums[i], fac);
		printf("%lu:", nums[i]);
		for (j = 0; j < len; j++)
			printf(" %lu", fac[j]);
		printf("\n");
	}

	return 0;
}

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


#include <stdio.h>

const char *str =
	"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
"
	"are$delineated$by$a$single$'dollar'$character,$write$a$program
"
	"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
"
	"column$are$separated$by$at$least$one$space.
"
	"Further,$allow$for$each$word$in$a$column$to$be$either$left$
"
	"justified,$right$justified,$or$center$justified$within$its$column.";

void align(const char *in, char alignment)
{
	int col, i, l, r;
	int w[1024] = {0};
	const char *s;

	for (s = in, i = col = 0; s[i]; s += i + 1) {
		for (i = 0; s[i] && s[i] != '$' && s[i] != '
'; i++);

		if (i > w[col]) w[col] = i;

		if (col++ >= 1024) abort(); /* artificial limit */

		if (s[i] == '
') col = 0;
		if (!s[i]) break;
	}

	for (s = in, i = col = 0; s[i]; s += i + 1) {
		for (i = 0; s[i] && s[i] != '$' && s[i] != '
'; i++);

		switch(alignment) {
		case 'l':	r = w[col] - i; break;
		case 'c':	r = (w[col] - i)/2; break;
		case 'r':	r = 0; break;
		}
		l = w[col++] - i - r + 1;

		while (l--) putchar(' ');
		printf("%.*s", i, s);
		while (r--) putchar(' ');

		if (s[i] != '$') {
			putchar('
');
			col = 0;
		}
		if (!s[i]) break;
	}
}

int main(void)
{
	puts("
----  right ----"); align(str, 'r');
	puts("
----  left  ----"); align(str, 'l');
	puts("
---- center ----"); align(str, 'c');
	return 0;
}

The code reads a text file where each line's fields are separated by a dollar character. It then aligns each column by ensuring at least one space between words in each column. The code also allows for words in a column to be left, right, or center justified. The minimum space between columns is computed from the text and not hard-coded. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.


generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, displaying three visible faces. The cuboid can be either static or rotationally projected. The code correctly executes, but only the characters '.' and ':' appear on the cuboid.


#include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);

Establishes a connection to an Active Directory or Lightweight Directory Access Protocol server using OpenLDAP.


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

static char rot13_table[UCHAR_MAX + 1];

static void init_rot13_table(void) {
	static const unsigned char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	static const unsigned char lower[] = "abcdefghijklmnopqrstuvwxyz";

	for (int ch = '\0'; ch <= UCHAR_MAX; ch++) {
		rot13_table[ch] = ch;
	}
	for (const unsigned char *p = upper; p[13] != '\0'; p++) {
		rot13_table[p[0]] = p[13];
		rot13_table[p[13]] = p[0];
	}
	for (const unsigned char *p = lower; p[13] != '\0'; p++) {
		rot13_table[p[0]] = p[13];
		rot13_table[p[13]] = p[0];
	}
}

static void rot13_file(FILE *fp)
{
	int ch;
	while ((ch = fgetc(fp)) != EOF) {
		fputc(rot13_table[ch], stdout);
	}
}

int main(int argc, char *argv[])
{
	init_rot13_table();

	if (argc > 1) {
		for (int i = 1; i < argc; i++) {
			FILE *fp = fopen(argv[i], "r");
			if (fp == NULL) {
				perror(argv[i]);
				return EXIT_FAILURE;
			}
			rot13_file(fp);
			fclose(fp);
		}
	} else {
		rot13_file(stdin);
	}
	return EXIT_SUCCESS;
}

implement a rot-13 encoding function that can be optionally wrapped in a utility program. The function replaces every letter of the ASCII alphabet with the letter 13 characters away, preserving case and passing non-alphabetic characters without alteration. It can handle all character sets, even if the letters are not in a contiguous range.


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

typedef struct twoStringsStruct {
    char * key, *value;
} sTwoStrings;

int ord( char v )
{
    static char *dgts = "012345679";
    char *cp;
    for (cp=dgts; v != *cp; cp++);
    return (cp-dgts);
}

int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2)
{
    char *p1 = s1->key;
    char *p2 = s2->key;
    char *mrk1, *mrk2;
    while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;}
    if (isdigit(*p1) && isdigit(*p2)) {
        long v1, v2;
        if ((*p1 == '0') ||(*p2 == '0')) {
            while (p1 > s1->key) {
                p1--; p2--;
                if (*p1 != '0') break;
            }
            if (!isdigit(*p1)) {
                p1++; p2++;
            }
        }
        mrk1 = p1; mrk2 = p2;
        v1 = 0;
        while(isdigit(*p1)) {
            v1 = 10*v1+ord(*p1);
            p1++;
        }
        v2 = 0;
        while(isdigit(*p2)) {
            v2 = 10*v2+ord(*p2);
            p2++;
        }
        if (v1 == v2)
           return(p2-mrk2)-(p1-mrk1);
        return v1 - v2;
    }
    if (tolower(*p1) != tolower(*p2))
       return (tolower(*p1) - tolower(*p2));
    for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++);
    return (*p1 -*p2);
}

int maxstrlen( char *a, char *b)
{
	int la = strlen(a);
	int lb = strlen(b);
	return (la>lb)? la : lb;
}

int main()
{
    sTwoStrings toBsorted[] = {
        { "Beta11a", "many" },
        { "alpha1", "This" },
        { "Betamax", "sorted." },
        { "beta3", "order" },
        { "beta11a", "strings" },
        { "beta001", "is" },
        { "beta11", "which" },
        { "beta041", "be" },
        { "beta05", "in" },
        { "beta1", "the" },
        { "beta40", "should" },
    };
#define ASIZE (sizeof(toBsorted)/sizeof(sTwoStrings))
    int k, maxlens[ASIZE];
    char format[12];
    sTwoStrings *cp;

    qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs);

    for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) {
        maxlens[k] = maxstrlen(cp->key, cp->value);
        sprintf(format," %%-%ds", maxlens[k]);
        printf(format, toBsorted[k].value);
	}
    printf("\n");
    for (k=0; k < ASIZE; k++) {
        sprintf(format," %%-%ds", maxlens[k]);
        printf(format, toBsorted[k].key);
	}
    printf("\n");

  return 0;
}

   This      is   the order     in  which    many strings should      be sorted.
 alpha1 beta001 beta1 beta3 beta05 beta11 Beta11a beta11a beta40 beta041 Betamax

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator and the qsort function from the standard library.


demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


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

typedef struct {
    int size;
    void **keys;
    void **values;
} hash_t;

hash_t *hash_new (int size) {
    hash_t *h = calloc(1, sizeof (hash_t));
    h->keys = calloc(size, sizeof (void *));
    h->values = calloc(size, sizeof (void *));
    h->size = size;
    return h;
}

int hash_index (hash_t *h, void *key) {
    int i = (int) key % h->size;
    while (h->keys[i] && h->keys[i] != key)
        i = (i + 1) % h->size;
    return i;
}

void hash_insert (hash_t *h, void *key, void *value) {
    int i = hash_index(h, key);
    h->keys[i] = key;
    h->values[i] = value;
}

void *hash_lookup (hash_t *h, void *key) {
    int i = hash_index(h, key);
    return h->values[i];
}

int main () {
    hash_t *h = hash_new(15);
    hash_insert(h, "hello", "world");
    hash_insert(h, "a", "b");
    printf("hello => %s
", hash_lookup(h, "hello"));
    printf("herp => %s
", hash_lookup(h, "herp"));
    printf("a => %s
", hash_lookup(h, "a"));
    return 0;
}

create an associative array, also referred to as a dictionary, map, or hash.


#include <stdio.h>

/* always assuming int is at least 32 bits */
int rand();
int rseed = 0;

inline void srand(int x)
{
	rseed = x;
}

#ifndef MS_RAND
#define RAND_MAX ((1U << 31) - 1)

inline int rand()
{
	return rseed = (rseed * 1103515245 + 12345) & RAND_MAX;
}

#else /* MS rand */

#define RAND_MAX_32 ((1U << 31) - 1)
#define RAND_MAX ((1U << 15) - 1)

inline int rand()
{
	return (rseed = (rseed * 214013 + 2531011) & RAND_MAX_32) >> 16;
}

#endif/* MS_RAND */

int main()
{
	int i;
	printf("rand max is %d\n", RAND_MAX);

	for (i = 0; i < 100; i++)
		printf("%d\n", rand());

	return 0;
}

The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The generators use the linear congruential generator formula, with different constants for each version. The code ensures that each generator produces the same sequence of integers as the original when given the same seed. The BSD version generates numbers in the range of 0 to 2147483647, while the Microsoft version generates numbers in the range of 0 to 32767. The code also allows for easy reproduction of a sequence of numbers from the same seed.


void insert_append (struct link *anchor, struct link *newlink) {
  newlink->next = anchor->next;
  anchor->next = newlink;
}

struct link *a, *b, *c;
a = malloc(sizeof(link));
b = malloc(sizeof(link));
c = malloc(sizeof(link));
a->data = 1;
b->data = 2;
c->data = 3;

 insert_append (a, b);

 insert_append (a, c);

 free (a);
 free (b);
 free (c);

The code defines a method to insert an element into a singly-linked list after a given element. It specifically inserts element C after element A in a list with elements A and B. The code also includes checks for valid values and memory management after the operation is completed.


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

void halve(int *x) { *x >>= 1; }
void doublit(int *x)  { *x <<= 1; }
bool iseven(const int x) { return (x & 1) ==  0; }

int ethiopian(int plier,
	      int plicand, const bool tutor)
{
  int result=0;

  if (tutor)
    printf("ethiopian multiplication of %d by %d\n", plier, plicand);

  while(plier >= 1) {
    if ( iseven(plier) ) {
      if (tutor) printf("%4d %6d struck\n", plier, plicand);
    } else {
      if (tutor) printf("%4d %6d kept\n", plier, plicand);
      result += plicand;
    }
    halve(&plier); doublit(&plicand);
  }
  return result;
}

int main()
{
  printf("%d\n", ethiopian(17, 34, true));
  return 0;
}

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


#include <stdio.h>

typedef struct {int val, op, left, right;} Node;

Node nodes[10000];
int iNodes;

int b;
float eval(Node x){
    if (x.op != -1){
        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
        switch(x.op){
            case 0: return l+r;
            case 1: return l-r;
            case 2: return r-l;
            case 3: return l*r;
            case 4: return r?l/r:(b=1,0);
            case 5: return l?r/l:(b=1,0);
        }
    }
    else return x.val*1.;
}

void show(Node x){
    if (x.op != -1){
        printf("(");
        switch(x.op){
            case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break;
            case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break;
            case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break;
            case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break;
            case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break;
            case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break;
        }
        printf(")");
    }
    else printf("%d", x.val);
}

int float_fix(float x){ return x < 0.00001 && x > -0.00001; }

void solutions(int a[], int n, float t, int s){
    if (s == n){
        b = 0;
        float e = eval(nodes[0]);

        if (!b && float_fix(e-t)){
            show(nodes[0]);
            printf("\n");
        }
    }
    else{
        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};

        for (int op = 0; op < 6; op++){
            int k = iNodes-1;
            for (int i = 0; i < k; i++){
                nodes[iNodes++] = nodes[i];
                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};
                solutions(a, n, t, s+1);
                nodes[i] = nodes[--iNodes];
            }
        }

        iNodes--;
    }
};

int main(){
    // define problem

    int a[4] = {8, 3, 8, 3};
    float t = 24;

    // print all solutions

    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};
    iNodes = 1;

    solutions(a, sizeof(a)/sizeof(int), t, 1);

    return 0;
}

The code takes four digits as input, either from the user or generated randomly, and calculates arithmetic expressions based on the rules of the 24 game. It displays examples of solutions produced. The code uses a brute-force approach with a specific time complexity and recursion depth. It can be adjusted to work with more than four numbers, different goals, and additional operations. If no solutions are found, it prints nothing.


int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i)
        result *= i;
    return result;
}

int factorialSafe(int n) {
    int result = 1;
    if(n<0)
        return -1;
    for (int i = 1; i <= n; ++i)
        result *= i;
    return result;
}

int factorial(int n) {
    return n == 0 ? 1 : n * factorial(n - 1);
}

int factorialSafe(int n) {
    return n<0 ? -1 : n == 0 ? 1 : n * factorialSafe(n - 1);
}

Tail
int fac_aux(int n, int acc) {
    return n < 1 ? acc : fac_aux(n - 1, acc * n);
}

int fac_auxSafe(int n, int acc) {
    return n<0 ? -1 : n < 1 ? acc : fac_aux(n - 1, acc * n);
}

int factorial(int n) {
    return fac_aux(n, 1);
}

#include <stdio.h>

#define l11l 0xFFFF
#define ll1 for
#define ll111 if
#define l1l1 unsigned
#define l111 struct
#define lll11 short
#define ll11l long
#define ll1ll putchar
#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1;
#define l1ll1 *lllll++=l1ll%10000;l1ll/=10000;
#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\
lllll=(l1=l1->lll1l)->lll;ll=1-1;
#define llll 1000

                                                     l111 llll1 {
                                                     l111 llll1 *
      lll1l,*ll1l1        ;l1l1                      lll11 lll [
      llll];};main      (){l111 llll1                *ll11,*l1l,*
      l1, *ll1l, *    malloc ( ) ; l1l1              ll11l l1ll ;
      ll11l l11,ll  ,l;l1l1 lll11 *lll1,*            lllll; ll1(l
      =1-1 ;l< 14; ll1ll("\t\"8)>l\"9!.)>vl"         [l]^'L'),++l
      );scanf("%d",&l);l1l1l(l1l) l1l1l(ll11         ) (l1=l1l)->
      lll[l1l->lll[1-1]     =1]=l11l;ll1(l11         =1+1;l11<=l;
      ++l11){l1=ll11;         lll1 = (ll1l=(         ll11=l1l))->
      lll; lllll =(            l1l=l1)->lll;         ll=(l1ll=1-1
      );ll1(;ll1l->             lll1l||l11l!=        *lll1;){l1ll
      +=l11**lll1++             ;l1ll1 ll111         (++ll>llll){
      l1lll lll1=(              ll1l =ll1l->         lll1l)->lll;
      }}ll1(;l1ll;              ){l1ll1 ll111        (++ll>=llll)
      { l1lll} } *              lllll=l11l;}
      ll1(l=(ll=1-              1);(l<llll)&&
      (l1->lll[ l]              !=l11l);++l);        ll1 (;l1;l1=
      l1->ll1l1,l=              llll){ll1(--l        ;l>=1-1;--l,
      ++ll)printf(              (ll)?((ll%19)        ?"%04d":(ll=
      19,"\n%04d")              ):"%4d",l1->         lll[l] ) ; }
                                                     ll1ll(10); }

The code implements a function to calculate the factorial of a given number. The function can be either iterative or recursive. It optionally handles negative input values by returning -1. The maximum factorial it can calculate is 429539.


Library: ncurses
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>

#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18

int yp=LINE_BEGIN, xp=0;

char number[5];
char guess[5];

#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
  va_list args;
  char buf[MAX_STR];

  va_start(args, fmt);
  vsprintf(buf, fmt, args);
  move(y, x);
  clrtoeol();
  addstr(buf);
  va_end(args);
}

void ask_for_a_number()
{
  int i=0;
  char symbols[] = "123456789";

  move(5,0); clrtoeol();
  addstr("Enter four digits: ");
  while(i<4) {
    int c = getch();
    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
      addch(c);
      symbols[c-'1'] = 0;
      guess[i++] = c;
    }
  }
}

void choose_the_number()
{
  int i=0, j;
  char symbols[] = "123456789";

  while(i<4) {
    j = rand() % 9;
    if ( symbols[j] != 0 ) {
      number[i++] = symbols[j];
      symbols[j] = 0;
    }
  }
}

bool take_it_or_not()
{
  int i;
  int cows=0, bulls=0;

  for(i=0; i < 4; i++) {
    if ( number[i] == guess[i] ) {
      bulls++;
    } else if ( strchr(number, guess[i]) != NULL ) {
      cows++;
    }
  }
  move(yp, xp);
  addstr(guess); addch(' ');
  if ( bulls == 4 ) { yp++; return true; }
  if ( (cows==0) && (bulls==0) ) addch('-');
  while( cows-- > 0 ) addstr("O");
  while( bulls-- > 0 ) addstr("X");
  yp++;
  if ( yp > LAST_LINE ) {
    yp = LINE_BEGIN;
    xp += 10;
  }
  return false;
}

bool ask_play_again()
{
  int i;

  while(yp-- >= LINE_BEGIN) {
    move(yp, 0); clrtoeol();
  }
  yp = LINE_BEGIN; xp = 0;

  move(21,0); clrtoeol();
  addstr("Do you want to play again? [y/n]");
  while(true) {
    int a = getch();
    switch(a) {
    case 'y':
    case 'Y':
      return true;
    case 'n':
    case 'N':
      return false;
    }
  }
}

int main()
{
  bool bingo, again;
  int tries = 0;

  initscr(); cbreak(); noecho();
  clear();

  number[4] = guess[4] = 0;

  mvaddstr(0,0, "I choose a number made of 4 digits (from 1 to 9) without repetitions\n"
                "You enter a number of 4 digits, and I say you how many of them are\n"
                "in my secret number but in wrong position (cows or O), and how many\n"
                "are in the right position (bulls or X)");
  do {
    move(20,0); clrtoeol(); move(21, 0); clrtoeol();
    srand(time(NULL));
    choose_the_number();
    do {
      ask_for_a_number();
      bingo = take_it_or_not();
      tries++;
    } while(!bingo && (tries < MAX_NUM_TRIES));
    if ( bingo )
      mvaddstrf(20, 0, "You guessed %s correctly in %d attempts!", number, tries);
    else
      mvaddstrf(20,0, "Sorry, you had only %d tries...; the number was %s",
		MAX_NUM_TRIES, number);
    again = ask_play_again();
    tries = 0;
  } while(again);
  nocbreak(); echo(); endwin();
  return EXIT_SUCCESS;
}

The code generates a random four-digit number with unique digits from 1 to 9. It then prompts the user to guess this number, rejecting any malformed guesses. The code calculates and prints a score for each guess, with "bulls" representing correct digits in the correct position and "cows" representing correct digits in the wrong position. The game ends when the user correctly guesses the number.


#include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

double drand()   /* uniform distribution, (0..1] */
{
  return (rand()+1.0)/(RAND_MAX+1.0);
}
double random_normal()  /* normal distribution, centered on 0, std dev 1 */
{
  return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}
int main()
{
  int i;
  double rands[1000];
  for (i=0; i<1000; i++)
    rands[i] = 1.0 + 0.5*random_normal();
  return 0;
}

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.


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

int dot_product(int *, int *, size_t);

int
main(void)
{
        int a[3] = {1, 3, -5};
        int b[3] = {4, -2, -1};

        printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));

        return EXIT_SUCCESS;
}

int
dot_product(int *a, int *b, size_t n)
{
        int sum = 0;
        size_t i;

        for (i = 0; i < n; i++) {
                sum += a[i] * b[i];
        }

        return sum;
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


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

char *get_line(FILE* fp)
{
	int len = 0, got = 0, c;
	char *buf = 0;

	while ((c = fgetc(fp)) != EOF) {
		if (got + 1 >= len) {
			len *= 2;
			if (len < 4) len = 4;
			buf = realloc(buf, len);
		}
		buf[got++] = c;
		if (c == '\n') break;
	}
	if (c == EOF && !got) return 0;

	buf[got++] = '\0';
	return buf;
}

int main()
{
	char *s;
	while ((s = get_line(stdin))) {
		printf("%s",s);
		free(s);
	}
	return 0;
}

read data from a text stream either word-by-word or line-by-line until no more data is available. It reads an arbitrarily long line each time and returns a null-terminated string. The caller is responsible for freeing the string.


#include <libxml/parser.h>
#include <libxml/tree.h>

int main()
{
  xmlDoc *doc = xmlNewDoc("1.0");
  xmlNode *root = xmlNewNode(NULL, BAD_CAST "root");
  xmlDocSetRootElement(doc, root);

  xmlNode *node = xmlNewNode(NULL, BAD_CAST "element");
  xmlAddChild(node, xmlNewText(BAD_CAST "some text here"));
  xmlAddChild(root, node);

  xmlSaveFile("myfile.xml", doc);

  xmlFreeDoc(doc);
  xmlCleanupParser();
}

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;
   Stack{
       Store ( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
       Store ( XML, Parser( "root", "",XML, NORMAL_TAG) );
   } Stack_off;

   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;

   Free secure XML, body;
End

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;

   Get_fn_let( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
   Get_fn_let( XML, Parser( "root", "",XML, NORMAL_TAG) );

   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;

   Free secure XML, body;
End

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;
   Stack{
       Store ( XML, Parser( "root", "",
                    Parser( "element", "","Some text here", NORMAL_TAG),
                    NORMAL_TAG) );
   } Stack_off;

   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;

   Free secure XML, body;
End

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String body;
   Stack{
       Store ( body, Multi_copy( body,"<?xml version=\"1.0\" ?>",
                                 Parser( "root", "", Parser( "element", "","Some text here",
                                 NORMAL_TAG), NORMAL_TAG),
                                 NULL) );
   }

   Print "%s\n", body;

   Free secure body;
End

Create a simple DOM and serialize it to XML format. The XML output includes a root element containing a single element with some text. The code also includes different versions with varying memory allocations.


It shows system time as "Www Mmm dd hh:mm:ss yyyy", where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.#include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
  time_t my_time = time(NULL);
  printf("%s", ctime(&my_time));
  return 0;
}

the system time, which can be used for debugging, network information, random number seeds, or program performance. The time can be outputted using a system command or a built-in language function. The time units are also specified.


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

int sedol_weights[] = {1, 3, 1, 7, 3, 9};
const char *reject = "AEIOUaeiou";

int sedol_checksum(const char *sedol6)
{
  int len = strlen(sedol6);
  int sum = 0, i;

  if ( len == 7 ) {
    fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6);
    return sedol6[6] & 0x7f;
  }
  if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {
    fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6);
    return -1;
  }
  for(i=0; i < 6; i++) {
    if ( isdigit(sedol6[i]) ) {
      sum += (sedol6[i]-'0')*sedol_weights[i];
    } else if ( isalpha(sedol6[i]) ) {
      sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];
    } else {
      fprintf(stderr, "SEDOL with not alphanumeric digit\n");
      return -1;
    }
  }
  return (10 - (sum%10))%10 + '0';
}

#define MAXLINELEN 10
int main()
{
  char line[MAXLINELEN];
  int sr, len;
  while( fgets(line, MAXLINELEN, stdin) != NULL ) {
    len = strlen(line);
    if ( line[len-1] == '\n' ) line[len-1]='\0';
    sr = sedol_checksum(line);
    if ( sr > 0 )
      printf("%s%c\n", line, sr);
  }
  return 0;
}

7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the respective SEDOL. It also validates the input to ensure it is correctly formed according to the SEDOL string rules. The SEDOLs are read from standard input, one per line, and must meet specific encoding specifications. The code then outputs the original SEDOLs with the appended checksum digit.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

const char *shades = ".:!*oe&#%@";

double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
        v[0] /= len; v[1] /= len; v[2] /= len;
}

double dot(double *x, double *y)
{
        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
        return d < 0 ? -d : 0;
}

void draw_sphere(double R, double k, double ambient)
{
        int i, j, intensity;
        double b;
        double vec[3], x, y;
        for (i = floor(-R); i <= ceil(R); i++) {
                x = i + .5;
                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
                        y = j / 2. + .5;
                        if (x * x + y * y <= R * R) {
                                vec[0] = x;
                                vec[1] = y;
                                vec[2] = sqrt(R * R - x * x - y * y);
                                normalize(vec);
                                b = pow(dot(light, vec), k) + ambient;
                                intensity = (1 - b) * (sizeof(shades) - 1);
                                if (intensity < 0) intensity = 0;
                                if (intensity >= sizeof(shades) - 1)
                                        intensity = sizeof(shades) - 2;
                                putchar(shades[intensity]);
                        } else
                                putchar(' ');
                }
                putchar('\n');
        }
}

int main()
{
        normalize(light);
        draw_sphere(20, 4, .1);
        draw_sphere(10, 2, .4);

        return 0;
}

represent a sphere either graphically or in ASCII art, with the option for static or rotational projection. The lighting calculation used for shading is basic.


#include <stdio.h>

char* addSuffix(int num, char* buf, size_t len)
{
    char *suffixes[4] = { "th", "st", "nd", "rd" };
    int i;

    switch (num % 10)
    {
        case 1 : i = (num % 100 == 11) ? 0 : 1;
	         break;
        case 2 : i = (num % 100 == 12) ? 0 : 2;
                 break;
        case 3 : i = (num % 100 == 13) ? 0 : 3;
                 break;
        default: i = 0;
    };

    snprintf(buf, len, "%d%s", num, suffixes[i]);
    return buf;
}

int main(void)
{
    int i;

    printf("Set [0,25]:\n");
    for (i = 0; i < 26; i++)
    {
        char s[5];
        printf("%s ", addSuffix(i, s, 5));
    }
    putchar('\n');

    printf("Set [250,265]:\n");
    for (i = 250; i < 266; i++)
    {
        char s[6];
        printf("%s ", addSuffix(i, s, 6));
    }
    putchar('\n');

    printf("Set [1000,1025]:\n");
    for (i = 1000; i < 1026; i++)
    {
        char s[7];
        printf("%s ", addSuffix(i, s, 7));
    }
    putchar('\n');

    return 0;
}

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

static int digits(const int x) {
    if (x / 10 == 0) return 1;
    return 1 + digits(x / 10);
}

static char * get_ordinal(const int i) {
    const int string_size = digits(i) + 3;
    char * o_number = malloc(string_size);
    char * ordinal;
    if(i % 100 >= 11 && i % 100 <= 13) ordinal = "th";
    else ordinal = i/10==1?"th":i%10==1?"st":i%10==2?"nd":i%10==3?"rd":"th";
    sprintf_s(o_number, string_size, "%d%s", i, ordinal);
    return o_number;
}

static void print_range(const int begin, const int end) {
    printf("Set [%d,%d]:\n", begin, end);
    for (int i = begin; i <= end; i++) {
        char * o_number = get_ordinal(i);
        printf("%s ", o_number);
        free(o_number);
    }
    printf("\n");
}

int main(void) {
    print_range(0, 25);
    print_range(250, 265);
    print_range(1000, 1025);
}

The code implements a function that accepts a non-negative integer as input and returns a string representation of the number with its ordinal suffix. The function is tested with integer ranges 0..25, 250..265, and 1000..1025. The use of apostrophes in the output is optional.


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

  /* removes all chars from string */
char *strip_chars(const char *string, const char *chars)
{
  char * newstr = malloc(strlen(string) + 1);
  int counter = 0;

  for ( ; *string; string++) {
    if (!strchr(chars, *string)) {
      newstr[ counter ] = *string;
      ++ counter;
    }
  }

  newstr[counter] = 0;
  return newstr;
}

int main(void)
{
  char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
  printf("%s\n", new);

  free(new);
  return 0;
}

Result:
Sh ws  soul strppr. Sh took my hrt!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strip(const char * str, const char *pat)
{
	/*  char replacement is typically done with lookup tables if
	 *  the replacement set can be large: it turns O(m n) into
	 *  O(m + n).
	 *  If same replacement pattern is going to be applied to many
	 *  strings, it's better to build a table beforehand and reuse it.
	 *  If charset is big like unicode, table needs to be implemented
	 *  more efficiently, say using bit field or hash table -- it
	 *  all depends on the application.
	 */
	int i = 0, tbl[128] = {0};
	while (*pat != '\0') tbl[(int)*(pat++)] = 1;

	char *ret = malloc(strlen(str) + 1);
	do {
		if (!tbl[(int)*str])
			ret[i++] = *str;
	} while (*(str++) != '\0');

	/*  assuming realloc is efficient and succeeds; if not, we could
	 *  do a two-pass, count first, alloc and strip second
	 */
	return realloc(ret, i);
}

int main()
{
	char * x = strip("She was a soul stripper. She took my heart!", "aei");
	printf(x);
	free(x);

	return 0;
}
Output same as above.

"Function to remove specific characters from a given string"


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

struct replace_info {
    int n;
    char *text;
};

int compare(const void *a, const void *b)
{
    struct replace_info *x = (struct replace_info *) a;
    struct replace_info *y = (struct replace_info *) b;
    return x->n - y->n;
}

void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
    int i, it;
    int found_word;

    for (i = 1; i < max; ++i) {
        found_word = 0;

        /* Assume sorted order of values in the info array */
        for (it = 0; it < info_length; ++it) {
            if (0 == i % info[it].n) {
                printf("%s", info[it].text);
                found_word = 1;
            }
        }

        if (0 == found_word)
            printf("%d", i);

        printf("\n");
    }
}

int main(void)
{
    struct replace_info info[3] = {
        {5, "Buzz"},
        {7, "Baxx"},
        {3, "Fizz"}
    };

    /* Sort information array */
    qsort(info, 3, sizeof(struct replace_info), compare);

    /* Print output for generic FizzBuzz */
    generic_fizz_buzz(20, info, 3);
    return 0;
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


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

int main()
{
    char str[100]="my String";
    char *cstr="Changed ";
    char *dup;
    sprintf(str,"%s%s",cstr,(dup=strdup(str)));
    free(dup);
    printf("%s\n",str);
    return 0;
}

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


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

/* x, y: coordinates of current point; dx, dy: direction of movement.
 * Think turtle graphics.  They are divided by scale, so as to keep
 * very small coords/increments without losing precission. clen is
 * the path length travelled, which should equal to scale at the end
 * of the curve.
 */
long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;

/* for every depth increase, rotate 45 degrees and scale up by sqrt(2)
 * Note how coords can still be represented by integers.
 */
void sc_up()
{
	long long tmp = dx - dy; dy = dx + dy; dx = tmp;
	scale *= 2; x *= 2; y *= 2;
}

/* Hue changes from 0 to 360 degrees over entire length of path; Value
 * oscillates along the path to give some contrast between segments
 * close to each other spatially.  RGB derived from HSV gets *added*
 * to each pixel reached; they'll be dealt with later.
 */
void h_rgb(long long x, long long y)
{
	rgb *p = &pix[y][x];

#	define SAT 1
	double h = 6.0 * clen / scale;
	double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
	double c = SAT * VAL;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	switch((int)h) {
	case 0: p->r += c; p->g += X; return;
	case 1:	p->r += X; p->g += c; return;
	case 2: p->g += c; p->b += X; return;
	case 3: p->g += X; p->b += c; return;
	case 4: p->r += X; p->b += c; return;
	default:
		p->r += c; p->b += X;
	}
}

/* string rewriting.  No need to keep the string itself, just execute
 * its instruction recursively.
 */
void iter_string(const char * str, int d)
{
	long tmp;
#	define LEFT  tmp = -dy; dy = dx; dx = tmp
#	define RIGHT tmp = dy; dy = -dx; dx = tmp
	while (*str != '\0') {
		switch(*(str++)) {
		case 'X':	if (d) iter_string("X+YF+", d - 1); continue;
		case 'Y':	if (d) iter_string("-FX-Y", d - 1); continue;
		case '+':	RIGHT; continue;
		case '-':	LEFT;  continue;
		case 'F':
                        /* draw: increment path length; add color; move. Here
                         * is why the code does not allow user to choose arbitrary
                         * image size: if it's not a power of two, aliasing will
                         * occur and grid-like bright or dark lines will result
                         * when normalized later.  It can be gotten rid of, but that
                         * involves computing multiplicative order and would be a huge
                         * bore.
                         */
				clen ++;
				h_rgb(x/scale, y/scale);
				x += dx; y += dy;
				continue;
		}
	}
}

void dragon(long leng, int depth)
{
	long i, d = leng / 3 + 1;
	long h = leng + 3, w = leng + d * 3 / 2 + 2;

	/* allocate pixel buffer */
	rgb *buf = malloc(sizeof(rgb) * w * h);
	pix = malloc(sizeof(rgb *) * h);
	for (i = 0; i < h; i++)
		pix[i] = buf + w * i;
	memset(buf, 0, sizeof(rgb) * w * h);

        /* init coords; scale up to desired; exec string */
	x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
	for (i = 0; i < depth; i++) sc_up();
	iter_string("FX", depth);

	/* write color PNM file */
	unsigned char *fpix = malloc(w * h * 3);
	double maxv = 0, *dbuf = (double*)buf;

        /* find highest value among pixels; normalize image according
         * to it.  Highest value would be at points most travelled, so
         * this ends up giving curve edge a nice fade -- it's more apparaent
         * if we increase iteration depth by one or two.
         */
	for (i = 3 * w * h - 1; i >= 0; i--)
		if (dbuf[i] > maxv) maxv = dbuf[i];
	for (i = 3 * h * w - 1; i >= 0; i--)
		fpix[i] = 255 * dbuf[i] / maxv;

	printf("P6\n%ld %ld\n255\n", w, h);
	fflush(stdout); /* printf and fwrite may treat buffer differently */
	fwrite(fpix, h * w * 3, 1, stdout);
}

int main(int c, char ** v)
{
	int size, depth;

	depth  = (c > 1) ? atoi(v[1]) : 10;
	size = 1 << depth;

	fprintf(stderr, "size: %d depth: %d\n", size, depth);
	dragon(size, depth * 2);

	return 0;
}

The code generates a dragon curve fractal, a mathematical shape that is self-replicating. It uses various algorithms to create the fractal, such as recursive methods, successive approximation, and iterative methods. The code also allows for the curve to be displayed directly or written to an image file. It can calculate absolute direction and coordinates for each point, and can also test if a given point or segment is on the curve. Additionally, the code can be run with a specified depth to control the complexity of the fractal.


#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(void)
{
    int n;
    int g;
    char c;

    srand(time(NULL));
    n = 1 + (rand() % 10);

    puts("I'm thinking of a number between 1 and 10.");
    puts("Try to guess it:");

    while (1) {
        if (scanf("%d", &g) != 1) {
		/* ignore one char, in case user gave a non-number */
		scanf("%c", &c);
		continue;
	}

        if (g == n) {
	    puts("Correct!");
	    return 0;
	}
        puts("That's not my number. Try another guess:");
    }
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


#include <stdlib.h>

#define N 26

int main() {
    unsigned char lower[N];

    for (size_t i = 0; i < N; i++) {
        lower[i] = i + 'a';
    }

    return EXIT_SUCCESS;
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


#define _CRT_SECURE_NO_WARNINGS    // turn off panic warnings
#define _CRT_NONSTDC_NO_DEPRECATE   // enable old-gold POSIX names in MSVS

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

char* bin2str(unsigned value, char* buffer)
{
    // This algorithm is not the fastest one, but is relativelly simple.
    //
    // A faster algorithm would be conversion octets to strings by a lookup table.
    // There is only 2**8 == 256 octets, therefore we would need only 2048 bytes
    // for the lookup table. Conversion of a 64-bit integers would need 8 lookups
    // instead 64 and/or/shifts of bits etc. Even more... lookups may be implemented
    // with XLAT or similar CPU instruction... and AVX/SSE gives chance for SIMD.

    const unsigned N_DIGITS = sizeof(unsigned) * 8;
    unsigned mask = 1 << (N_DIGITS - 1);
    char* ptr = buffer;

    for (int i = 0; i < N_DIGITS; i++)
    {
        *ptr++ = '0' + !!(value & mask);
        mask >>= 1;
    }
    *ptr = '\0';

    // Remove leading zeros.
    //
    for (ptr = buffer; *ptr == '0'; ptr++)
        ;

    return ptr;
}

char* bin2strNaive(unsigned value, char* buffer)
{
    // This variation of the solution doesn't use bits shifting etc.

    unsigned n, m, p;

    n = 0;
    p = 1;  // p = 2 ** n
    while (p <= value / 2)
    {
        n = n + 1;
        p = p * 2;
    }

    m = 0;
    while (n > 0)
    {
        buffer[m] = '0' + value / p;
        value = value % p;
        m = m + 1;
        n = n - 1;
        p = p / 2;
    }

    buffer[m + 1] = '\0';
    return buffer;
}

int main(int argc, char* argv[])
{
    const unsigned NUMBERS[] = { 5, 50, 9000 };

    const int RADIX = 2;
    char buffer[(sizeof(unsigned)*8 + 1)];

    // Function itoa is an POSIX function, but it is not in C standard library.
    // There is no big surprise that Microsoft deprecate itoa because POSIX is
    // "Portable Operating System Interface for UNIX". Thus it is not a good
    // idea to use _itoa instead itoa: we lost compatibility with POSIX;
    // we gain nothing in MS Windows (itoa-without-underscore is not better
    // than _itoa-with-underscore). The same holds for kbhit() and _kbhit() etc.
    //
    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        itoa(value, buffer, RADIX);
        printf("itoa:          %u decimal = %s binary\n", value, buffer);
    }

    // Yeep, we can use a homemade bin2str function. Notice that C is very very
    // efficient (as "hi level assembler") when bit manipulation is needed.
    //
    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        printf("bin2str:       %u decimal = %s binary\n", value, bin2str(value, buffer));
    }

    // Another implementation - see above.
    //
    for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++)
    {
        unsigned value = NUMBERS[i];
        printf("bin2strNaive:  %u decimal = %s binary\n", value, bin2strNaive(value, buffer));
    }

    return EXIT_SUCCESS;
}

"Generates and displays a sequence of binary digits for a given non-negative integer. The output is a string of binary digits, without any leading zeros, whitespace, radix, or sign markers. The conversion can be achieved using built-in radix functions or a user-defined function."


#include<graphics.h>

int main()
{
	initwindow(320,240,"Red Pixel");

	putpixel(100,100,RED);

	getch();

	return 0;
}

Creates a 320x240 window using the WinBGIm library and draws a red pixel at position (100, 100).


Library: libconfini

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

#define rosetta_uint8_t unsigned char

#define FALSE 0
#define TRUE 1

#define CONFIGS_TO_READ 5
#define INI_ARRAY_DELIMITER ','

/* Assume that the config file represent a struct containing all the parameters to load */
struct configs {
	char *fullname;
	char *favouritefruit;
	rosetta_uint8_t needspeeling;
	rosetta_uint8_t seedsremoved;
	char **otherfamily;
	size_t otherfamily_len;
	size_t _configs_left_;
};

static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {

	/* Allocate a new array of strings and populate it from the stringified source */
	*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);
	char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;
	if (!dest) { return NULL; }
	memcpy(dest + *arrlen, src, buffsize);
	char * iter = (char *) (dest + *arrlen);
	for (size_t idx = 0; idx < *arrlen; idx++) {
		dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);
		ini_string_parse(dest[idx], ini_format);
	}
	return dest;

}

static int configs_member_handler (IniDispatch *this, void *v_confs) {

	struct configs *confs = (struct configs *) v_confs;

	if (this->type != INI_KEY) {

		return 0;

	}

	if (ini_string_match_si("FULLNAME", this->data, this->format)) {

		if (confs->fullname) { return 0; }
		this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */
		confs->fullname = strndup(this->value, this->v_len);
		confs->_configs_left_--;

	} else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) {

		if (confs->favouritefruit) { return 0; }
		this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */
		confs->favouritefruit = strndup(this->value, this->v_len);
		confs->_configs_left_--;

	} else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) {

		if (~confs->needspeeling & 0x80) { return 0; }
		confs->needspeeling = ini_get_bool(this->value, TRUE);
		confs->_configs_left_--;

	} else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) {

		if (~confs->seedsremoved & 0x80) { return 0; }
		confs->seedsremoved = ini_get_bool(this->value, TRUE);
		confs->_configs_left_--;

	} else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) {

		if (confs->otherfamily) { return 0; }
		this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); /* Save memory (not strictly needed) */
		confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);
		confs->_configs_left_--;

	}

	/* Optimization: stop reading the INI file when we have all we need */
	return !confs->_configs_left_;

}

static int populate_configs (struct configs * confs) {

	/* Define the format of the configuration file */
	IniFormat config_format = {
		.delimiter_symbol = INI_ANY_SPACE,
		.case_sensitive = FALSE,
		.semicolon_marker = INI_IGNORE,
		.hash_marker = INI_IGNORE,
		.multiline_nodes = INI_NO_MULTILINE,
		.section_paths = INI_NO_SECTIONS,
		.no_single_quotes = FALSE,
		.no_double_quotes = FALSE,
		.no_spaces_in_names = TRUE,
		.implicit_is_not_empty = TRUE,
		.do_not_collapse_values = FALSE,
		.preserve_empty_quotes = FALSE,
		.disabled_after_space = TRUE,
		.disabled_can_be_implicit = FALSE
	};

	*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };

	if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {

		fprintf(stderr, "Sorry, something went wrong :-(\n");
		return 1;

	}

	confs->needspeeling &= 0x7F;
	confs->seedsremoved &= 0x7F;

	return 0;

}

int main () {

	struct configs confs;

	ini_global_set_implicit_value("YES", 0);

	if (populate_configs(&confs)) {

		return 1;

	}

	/* Print the configurations parsed */

	printf(

		"Full name: %s\n"
		"Favorite fruit: %s\n"
		"Need spelling: %s\n"
		"Seeds removed: %s\n",

		confs.fullname,
		confs.favouritefruit,
		confs.needspeeling ? "True" : "False",
		confs.seedsremoved ? "True" : "False"

	);

	for (size_t idx = 0; idx < confs.otherfamily_len; idx++) {

		printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]);

	}

	/* Free the allocated memory */

	#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }

	FREE_NON_NULL(confs.fullname);
	FREE_NON_NULL(confs.favouritefruit);
	FREE_NON_NULL(confs.otherfamily);

	return 0;

}

The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration entries: 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved'. It also handles multiple parameters for a configuration option, storing them in an array under 'otherfamily'. The configuration option names are not case sensitive, but the data is case sensitive. An optional equals sign can be used to separate data from the option name.


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define R 6371
#define TO_RAD (3.1415926536 / 180)
double dist(double th1, double ph1, double th2, double ph2)
{
	double dx, dy, dz;
	ph1 -= ph2;
	ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;

	dz = sin(th1) - sin(th2);
	dx = cos(ph1) * cos(th1) - cos(th2);
	dy = sin(ph1) * cos(th1);
	return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;
}

int main()
{
	double d = dist(36.12, -86.67, 33.94, -118.4);
	/* Americans don't know kilometers */
	printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344);

	return 0;
}

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


Library: libcurl
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int
main(void)
{
        CURL *curl;
        char buffer[CURL_ERROR_SIZE];

        if ((curl = curl_easy_init()) != NULL) {
                curl_easy_setopt(curl, CURLOPT_URL, "http://www.rosettacode.org/");
                curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
                if (curl_easy_perform(curl) != CURLE_OK) {
                        fprintf(stderr, "%s\n", buffer);
                        return EXIT_FAILURE;
                }
                curl_easy_cleanup(curl);
        }
        return EXIT_SUCCESS;
}

Print the content of a specified URL to the console using HTTP request.


The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


#include <stdio.h>

// m-th on the reversed kill list; m = 0 is final survivor
int jos(int n, int k, int m) {
	int a;
	for (a = m + 1; a <= n; a++)
		m = (m + k) % a;
	return m;
}

typedef unsigned long long xint;

// same as jos(), useful if n is large and k is not
xint jos_large(xint n, xint k, xint m) {
	if (k <= 1) return n - m - 1;

	xint a = m;
	while (a < n) {
		xint q = (a - m + k - 2) / (k - 1);

		if (a + q > n)	q = n - a;
		else if (!q)	q = 1;

		m = (m + q * k) % (a += q);
	}

	return m;
}

int main(void) {
	xint n, k, i;

	n = 41;
	k = 3;
	printf("n = %llu, k = %llu, final survivor: %d\n", n, k, jos(n, k, 0));

	n = 9876543210987654321ULL;
	k = 12031;
	printf("n = %llu, k = %llu, three survivors:", n, k);

	for (i = 3; i--; )
		printf(" %llu", jos_large(n, k, i));
	putchar('\n');

	return 0;
}

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


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

char * string_repeat( int n, const char * s ) {
  size_t slen = strlen(s);
  char * dest = malloc(n*slen+1);

  int i; char * p;
  for ( i=0, p = dest; i < n; ++i, p += slen ) {
    memcpy(p, s, slen);
  }
  *p = '\0';
  return dest;
}

int main() {
  char * result = string_repeat(5, "ha");
  puts(result);
  free(result);
  return 0;
}

...
char *string_repeat(const char *str, int n)
{
   char *pa, *pb;
   size_t slen = strlen(str);
   char *dest = malloc(n*slen+1);

   pa = dest + (n-1)*slen;
   strcpy(pa, str);
   pb = --pa + slen;
   while (pa>=dest) *pa-- = *pb--;
   return dest;
}

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

char * char_repeat( int n, char c ) {
  char * dest = malloc(n+1);
  memset(dest, c, n);
  dest[n] = '\0';
  return dest;
}

int main() {
  char * result = char_repeat(5, '*');
  puts(result);
  free(result);
  return 0;
}

"Code functionality: Repeats a given string or character a specified number of times. For example, repeating 'ha' 5 times results in 'hahahahaha'. If using GLib, the function g_strnfill can be used to repeat a single character efficiently."


Works with: POSIX

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>

int main()
{
   regex_t preg;
   regmatch_t substmatch[1];
   const char *tp = "string$";
   const char *t1 = "this is a matching string";
   const char *t2 = "this is not a matching string!";
   const char *ss = "istyfied";

   regcomp(&preg, "string$", REG_EXTENDED);
   printf("'%s' %smatched with '%s'\n", t1,
                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
   printf("'%s' %smatched with '%s'\n", t2,
                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
   regfree(&preg);
   /* change "a[a-z]+" into "istifyed"?*/
   regcomp(&preg, "a[a-z]+", REG_EXTENDED);
   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
   {
      //fprintf(stderr, "%d, %d\n", substmatch[0].rm_so, substmatch[0].rm_eo);
      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
                        (strlen(t1) - substmatch[0].rm_eo) + 2);
      memcpy(ns, t1, substmatch[0].rm_so+1);
      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
                strlen(&t1[substmatch[0].rm_eo]));
      ns[ substmatch[0].rm_so + strlen(ss) +
          strlen(&t1[substmatch[0].rm_eo]) ] = 0;
      printf("mod string: '%s'\n", ns);
      free(ns);
   } else {
      printf("the string '%s' is the same: no matching!\n", t1);
   }
   regfree(&preg);

   return 0;
}

Library: GLib
#include <stdio.h>
#include <glib.h>

void print_regex_match(const GRegex* regex, const char* string) {
    GMatchInfo* match_info;
    gboolean match = g_regex_match(regex, string, 0, &match_info);
    printf("  string = '%s': %s\n", string, match ? "yes" : "no");
    g_match_info_free(match_info);
}

void regex_match_demo() {
    const char* pattern = "^[a-z]+$";
    GError* error = NULL;
    GRegex* regex = g_regex_new(pattern, 0, 0, &error);
    if (regex == NULL) {
        fprintf(stderr, "%s\n", error->message);
        g_error_free(error);
        return;
    }
    printf("Does the string match the pattern '%s'?\n", pattern);
    print_regex_match(regex, "test");
    print_regex_match(regex, "Test");
    g_regex_unref(regex);
}

void regex_replace_demo() {
    const char* pattern = "[0-9]";
    const char* input = "Test2";
    const char* replace = "X";
    GError* error = NULL;
    GRegex* regex = g_regex_new(pattern, 0, 0, &error);
    if (regex == NULL) {
        fprintf(stderr, "%s\n", error->message);
        g_error_free(error);
        return;
    }
    char* result = g_regex_replace_literal(regex, input, -1,
                                           0, replace, 0, &error);
    if (result == NULL) {
        fprintf(stderr, "%s\n", error->message);
        g_error_free(error);
    } else {
        printf("Replace pattern '%s' in string '%s' by '%s': '%s'\n",
               pattern, input, replace, result);
        g_free(result);
    }
    g_regex_unref(regex);
}

int main() {
    regex_match_demo();
    regex_replace_demo();
    return 0;
}

implement the functionality to match a string against a regular expression and substitute part of a string using a regular expression. The POSIX defined function is used for regex matching and the substitution is manually coded. The code complexity is reduced by converting it into a function. GLib's Perl-compatible regular expression functionality is also utilized to simplify the task.


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

int main(int argc, char *argv[])
{
  int a, b;
  if (argc < 3) exit(1);
  b = atoi(argv[--argc]);
  if (b == 0) exit(2);
  a = atoi(argv[--argc]);
  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); /* truncates towards 0 (in C99) */
  printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
  return 0;
}

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


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

int match(const char *s, const char *p, int overlap)
{
        int c = 0, l = strlen(p);

        while (*s != '\0') {
                if (strncmp(s++, p, l)) continue;
                if (!overlap) s += l - 1;
                c++;
        }
        return c;
}

int main()
{
        printf("%d\n", match("the three truths", "th", 0));
        printf("overlap:%d\n", match("abababababa", "aba", 1));
        printf("not:    %d\n", match("abababababa", "aba", 0));
        return 0;
}

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

// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const char *str, const char *sub)
{
    int length = strlen(sub);
    if (length == 0) return 0;
    int count = 0;
    for (str = strstr(str, sub); str; str = strstr(str + length, sub))
        ++count;
    return count;
}

int main()
{
    printf("%d\n", countSubstring("the three truths", "th"));
    printf("%d\n", countSubstring("ababababab", "abab"));
    printf("%d\n", countSubstring("abaabba*bbaba*bbab", "a*b"));

    return 0;
}

"Output: The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments - the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left."


#include <stdio.h>

void move(int n, int from, int via, int to)
{
  if (n > 1) {
    move(n - 1, from, to, via);
    printf("Move disk from pole %d to pole %d\n", from, to);
    move(n - 1, via, from, to);
  } else {
    printf("Move disk from pole %d to pole %d\n", from, to);
  }
}
int main()
{
  move(4, 1,2,3);
  return 0;
}

Animate it for fun:#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct { int *x, n; } tower;
tower *new_tower(int cap)
{
	tower *t = calloc(1, sizeof(tower) + sizeof(int) * cap);
	t->x = (int*)(t + 1);
	return t;
}

tower *t[3];
int height;

void text(int y, int i, int d, const char *s)
{
	printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d);
	while (d--) printf("%s", s);
}

void add_disk(int i, int d)
{
	t[i]->x[t[i]->n++] = d;
	text(t[i]->n, i, d, "==");

	usleep(100000);
	fflush(stdout);
}

int remove_disk(int i)
{
	int d = t[i]->x[--t[i]->n];
	text(t[i]->n + 1, i, d, "  ");
	return d;
}

void move(int n, int from, int to, int via)
{
	if (!n) return;

	move(n - 1, from, via, to);
	add_disk(to, remove_disk(from));
	move(n - 1, via, to, from);
}

int main(int c, char *v[])
{
	puts("\033[H\033[J");

	if (c <= 1 || (height = atoi(v[1])) <= 0)
		height = 8;
	for (c = 0; c < 3; c++)	 t[c] = new_tower(height);
	for (c = height; c; c--) add_disk(0, c);

	move(height, 0, 2, 1);

	text(1, 0, 1, "\n");
	return 0;
}

"Implement a recursive solution to solve the Towers of Hanoi problem."


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

/* We go to some effort to handle overflow situations */

static unsigned long gcd_ui(unsigned long x, unsigned long y) {
  unsigned long t;
  if (y < x) { t = x; x = y; y = t; }
  while (y > 0) {
    t = y;  y = x % y;  x = t;  /* y1 <- x0 % y0 ; x1 <- y0 */
  }
  return x;
}

unsigned long binomial(unsigned long n, unsigned long k) {
  unsigned long d, g, r = 1;
  if (k == 0) return 1;
  if (k == 1) return n;
  if (k >= n) return (k == n);
  if (k > n/2) k = n-k;
  for (d = 1; d <= k; d++) {
    if (r >= ULONG_MAX/n) {  /* Possible overflow */
      unsigned long nr, dr;  /* reduced numerator / denominator */
      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;
      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;
      if (r >= ULONG_MAX/nr) return 0;  /* Unavoidable overflow */
      r *= nr;
      r /= dr;
      n--;
    } else {
      r *= n--;
      r /= d;
    }
  }
  return r;
}

int main() {
    printf("%lu\n", binomial(5, 3));
    printf("%lu\n", binomial(40, 19));
    printf("%lu\n", binomial(67, 31));
    return 0;
}

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.


implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


typedef unsigned char luminance;
typedef luminance pixel1[1];
typedef struct {
   unsigned int width;
   unsigned int height;
   luminance *buf;
} grayimage_t;
typedef grayimage_t *grayimage;

grayimage alloc_grayimg(unsigned int, unsigned int);
grayimage tograyscale(image);
image tocolor(grayimage);

grayimage alloc_grayimg(unsigned int width, unsigned int height)
{
     grayimage img;
     img = malloc(sizeof(grayimage_t));
     img->buf = malloc(width*height*sizeof(pixel1));
     img->width = width;
     img->height = height;
     return img;
}

grayimage tograyscale(image img)
{
   unsigned int x, y;
   grayimage timg;
   double rc, gc, bc, l;
   unsigned int ofs;

   timg = alloc_grayimg(img->width, img->height);

   for(x=0; x < img->width; x++)
   {
      for(y=0; y < img->height; y++)
      {
        ofs = (y * img->width) + x;
        rc = (double) img->buf[ofs][0];
        gc = (double) img->buf[ofs][1];
        bc = (double) img->buf[ofs][2];
        l = 0.2126*rc + 0.7152*gc + 0.0722*bc;
        timg->buf[ofs][0] = (luminance) (l+0.5);
      }
   }
   return timg;
}

image tocolor(grayimage img)
{
   unsigned int x, y;
   image timg;
   luminance l;
   unsigned int ofs;

   timg = alloc_img(img->width, img->height);

   for(x=0; x < img->width; x++)
   {
      for(y=0; y < img->height; y++)
      {
        ofs = (y * img->width) + x;
        l = img->buf[ofs][0];
        timg->buf[ofs][0] = l;
        timg->buf[ofs][1] = l;
        timg->buf[ofs][2] = l;
      }
   }
   return timg;
}

tocolor and tograyscale do not free the previous image, so it must be freed normally calling free_img. With a cast we can use the same function also for grayscale images, or we can define something like
#define free_grayimg(IMG) free_img((image)(IMG))

Luminance is rounded. Since the C implementation is based on unsigned char (256 possible values per components), L can be at most 255.0 and rounding gives 255, as we expect. Changing the color_component type would only change 256, 255.0 and 255 values here written in something else, the code would work the same.

- Defines a data storage type for grayscale images.
- Implements two operations for converting a color image to a grayscale image and vice versa.
- Uses the CIE recommended formula for calculating luminance of a color.
- Ensures that rounding errors in floating-point arithmetic do not cause run-time problems or distort results when storing calculated luminance as an unsigned integer.
- Provides a definition/interface for a grayscale image similar to alloc_img.
- Converts a color image to a grayscale image and back.


Library: GTK

#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>

const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;

GtkLabel *label;

void change_dir(GtkLayout *o, gpointer d)
{
  direction = -direction;
}

gchar *rotateby(const gchar *t, gint q, gint l)
{
  gint i, cl = l, j;
  gchar *r = malloc(l+1);
  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
    r[j] = t[i];
  r[l] = 0;
  return r;
}

gboolean scroll_it(gpointer data)
{
  if ( direction > 0 )
    cx = (cx + 1) % slen;
  else
    cx = (cx + slen - 1 ) % slen;
  gchar *scrolled = rotateby(hello, cx, slen);
  gtk_label_set_text(label, scrolled);
  free(scrolled);
  return TRUE;
}

int main(int argc, char **argv)
{
  GtkWidget *win;
  GtkButton *button;
  PangoFontDescription *pd;

  gtk_init(&argc, &argv);
  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
  g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);

  label = (GtkLabel *)gtk_label_new(hello);

  // since we shift a whole character per time, it's better to use
  // a monospace font, so that the shifting seems done at the same pace
  pd = pango_font_description_new();
  pango_font_description_set_family(pd, "monospace");
  gtk_widget_modify_font(GTK_WIDGET(label), pd);

  button = (GtkButton *)gtk_button_new();
  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));

  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
  g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);

  slen = strlen(hello);

  g_timeout_add(125, scroll_it, NULL);

  gtk_widget_show_all(GTK_WIDGET(win));
  gtk_main();
  return 0;
}

The code creates a GUI window displaying the string "Hello World!" and implements an animation effect that gives the illusion of the text rotating to the right by periodically moving the last letter to the beginning of the string. The direction of rotation reverses when the user clicks on the text. The code utilizes the GTK and Pango libraries.


int val = 0;
do{
   val++;
   printf("%d\n",val);
}while(val % 6 != 0);

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Works with: ANSI C
Works with: GCC version 3.3.3
#include <string.h>

int main(void)
{
  const char *string = "Hello, world!";
  size_t length = strlen(string);

  return 0;
}

int main(void)
{
  const char *string = "Hello, world!";
  size_t length = 0;

  const char *p = string;
  while (*p++ != '\0') length++;

  return 0;
}

#include <stdlib.h>

int main(void)
{
  char s[] = "Hello, world!";
  size_t length = sizeof s - 1;

  return 0;
}

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

int main(void)
{
   wchar_t *s = L"\x304A\x306F\x3088\x3046"; /* Japanese hiragana ohayou */
   size_t length;

   length = wcslen(s);
   printf("Length in characters = %d\n", length);
   printf("Length in bytes      = %d\n", sizeof(s) * sizeof(wchar_t));

   return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

int main()
{
	setlocale(LC_CTYPE, "");
	char moose[] = "møøse";
	printf("bytes: %d\n", sizeof(moose) - 1);
	printf("chars: %d\n", (int)mbstowcs(0, moose, 0));

	return 0;
}
outputbytes: 7
chars: 5

determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The character count is based on individual Unicode code points, not user-visible graphemes or code units. The code also handles non-BMP code points correctly. If possible, the code also provides the string length in graphemes. The example strings used include "møøse" and "𝔘𝔫𝔦𝔠𝔬𝔡𝔢". The code assumes the environment locale is UTF-8.


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

#define RANDOM_PATH "/dev/urandom"

int main(void)
{
        unsigned char buf[4];
        unsigned long v;
        FILE *fin;

        if ((fin = fopen(RANDOM_PATH, "r")) == NULL) {
                fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH);
                return EXIT_FAILURE;
        }
        if (fread(buf, 1, sizeof buf, fin) != sizeof buf) {
                fprintf(stderr, "%s: not enough bytes (expected %u)\n",
                        RANDOM_PATH, (unsigned) sizeof buf);
                return EXIT_FAILURE;
        }
        fclose(fin);
        v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL;
        printf("%lu\n", v);
        return 0;
}

#include <inttypes.h> /* PRIu32 */
#include <stdlib.h> /* arc4random */
#include <stdio.h>  /* printf */

int
main()
{
  printf("%" PRIu32 "\n", arc4random());
  return 0;
}

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

#include <openssl/err.h>
#include <openssl/rand.h>

int
main()
{
  uint32_t v;

  if (RAND_bytes((unsigned char *)&v, sizeof v) == 0) {
    ERR_print_errors_fp(stderr);
    return 1;
  }
  printf("%" PRIu32 "\n", v);
  return 0;
}

Works with: MinGW
#include <stdio.h>  /* printf */
#include <windows.h>
#include <wincrypt.h> /* CryptAcquireContext, CryptGenRandom */

int
main()
{
  HCRYPTPROV p;
  ULONG i;

  if (CryptAcquireContext(&p, NULL, NULL,
      PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {
    fputs("CryptAcquireContext failed.\n", stderr);
    return 1;
  }
  if (CryptGenRandom(p, sizeof i, (BYTE *)&i) == FALSE) {
    fputs("CryptGenRandom failed.\n", stderr);
    return 1;
  }
  printf("%lu\n", i);
  CryptReleaseContext(p, 0);
  return 0;
}

Works with: GCC
#include <stdio.h>
#include <stdlib.h>

/*
   (C) 2020 J.G.A. Debaere, all rights reserved 2020/10/29

    Put into Public Domain for individuals only

    Tested with NIST, Diehard, Diehard 3.31

    gcc -lm ./jpsrand_f.c -o ./jpsrand_f.o

    dieharder -a -f /tmp/tmp.bin

	I consider it TRNG,

	using Time, Hardddisk and Memory as the hardware component

	No warranty of any kind, "AS IS"

	Last time I tested  ( 2021/07/07 ) with dieharder:

	rgb_bitdist		|   8|    100000|     100|0.99716738|   WEAK
	rgb_lagged_sum	|   3|   1000000|     100|0.99661184|   WEAK

	Out of 114 tests, rest PASSED

        Obviously, it changes per run :)

*/

unsigned int  jps_rand()
{
    /* (C) 2020 J.G.A. Debaere, all rights reserved */

    #include   <dirent.h>

    #include <sys/time.h>

    struct timeval current_time ;

    DIR *folder ;

    struct dirent *en ;

    folder = opendir ( "." ) ;

    while ( ( folder ) && ( en = readdir ( folder ) ) != NULL )

        asm ( "nop" ) ;

    closedir ( folder ) ;

    gettimeofday( &current_time, NULL ) ;

    unsigned int t = ( current_time.tv_sec * current_time.tv_usec / 17.17 ) ;

    return t ;
}

int main()
{
    FILE * f1;

    f1 = fopen("/tmp/tmp.bin", "wb");

    unsigned int t = ( unsigned int ) jps_rand() ;

    for ( unsigned int k = 0;  k < 40000000 ; k++ )
    {
        t = jps_rand () ;

        fwrite ( &t, sizeof( unsigned int ),  1, f1 ) ;
    }

    fflush(f1);

    fclose(f1);

    return 0;
}

   Random

demonstrate how to generate a random 32-bit number using system's built-in mechanisms such as /dev/urandom in Unix, arc4random() in BSD systems, or OpenSSL's default generator. The code is compatible with systems that have /dev/urandom like GNU/Linux, and uses entropy from a kernel device or the Entropy Gathering Daemon.


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

int main( int argc, char ** argv ){
  const char * str_a = "knight";
  const char * str_b = "socks";
  const char * str_c = "brooms";

  char * new_a = malloc( strlen( str_a ) - 1 );
  char * new_b = malloc( strlen( str_b ) - 1 );
  char * new_c = malloc( strlen( str_c ) - 2 );

  strcpy( new_a, str_a + 1 );
  strncpy( new_b, str_b, strlen( str_b ) - 1 );
  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );

  printf( "%s\n%s\n%s\n", new_a, new_b, new_c );

  free( new_a );
  free( new_b );
  free( new_c );

  return 0;
}

night
sock
room

The code demonstrates how to remove the first and last characters from a string. It shows how to get a string with the first character removed, a string with the last character removed, and a string with both the first and last characters removed. The code works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not 8-bit or 16-bit code units. It doesn't support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP. The code uses only ANSI C for text manipulation.


Library: POSIX
#include <fcntl.h>	/* fcntl, open */
#include <stdlib.h>	/* atexit, getenv, malloc */
#include <stdio.h>	/* fputs, printf, puts, snprintf */
#include <string.h>	/* memcpy */
#include <unistd.h>	/* sleep, unlink */

/* Filename for only_one_instance() lock. */
#define INSTANCE_LOCK "rosetta-code-lock"

void
fail(const char *message)
{
	perror(message);
	exit(1);
}

/* Path to only_one_instance() lock. */
static char *ooi_path;

void
ooi_unlink(void)
{
	unlink(ooi_path);
}

/* Exit if another instance of this program is running. */
void
only_one_instance(void)
{
	struct flock fl;
	size_t dirlen;
	int fd;
	char *dir;

	/*
	 * Place the lock in the home directory of this user;
	 * therefore we only check for other instances by the same
	 * user (and the user can trick us by changing HOME).
	 */
	dir = getenv("HOME");
	if (dir == NULL || dir[0] != '/') {
		fputs("Bad home directory.\n", stderr);
		exit(1);
	}
	dirlen = strlen(dir);

	ooi_path = malloc(dirlen + sizeof("/" INSTANCE_LOCK));
	if (ooi_path == NULL)
		fail("malloc");
	memcpy(ooi_path, dir, dirlen);
	memcpy(ooi_path + dirlen, "/" INSTANCE_LOCK,
	    sizeof("/" INSTANCE_LOCK));  /* copies '\0' */

	fd = open(ooi_path, O_RDWR | O_CREAT, 0600);
	if (fd < 0)
		fail(ooi_path);

	fl.l_start = 0;
	fl.l_len = 0;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	if (fcntl(fd, F_SETLK, &fl) < 0) {
		fputs("Another instance of this program is running.\n",
		    stderr);
		exit(1);
	}

	/*
	 * Run unlink(ooi_path) when the program exits. The program
	 * always releases locks when it exits.
	 */
	atexit(ooi_unlink);
}

/*
 * Demo for Rosetta Code.
 * http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
 */
int
main()
{
	int i;

	only_one_instance();

	/* Play for 10 seconds. */
	for(i = 10; i > 0; i--) {
		printf("%d...%s", i, i % 5 == 1 ? "\n" : " ");
		fflush(stdout);
		sleep(1);
	}
	puts("Fin!");
	return 0;
}

Library: POSIX
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* unistd for sleep */

void sigint_handler(int sig)
{
   fprintf(stderr, "Caught signal %d.\n", sig);
   unlink("/tmp/MyUniqueName");
   /* exit() is not safe in a signal handler, use _exit() */
   _exit(1);
}

int main()
{
   struct sigaction act;
   int myfd;

   myfd = open("/tmp/MyUniqueName", O_CREAT|O_EXCL);
   if ( myfd < 0 )
   {
      fprintf(stderr, "I am already running!\n");
      exit(1);
   }
   act.sa_handler = sigint_handler;
   sigemptyset(&act.sa_mask);
   act.sa_flags = 0;
   sigaction(SIGINT, &act, NULL);
   /* here the real code of the app*/
   sleep(20);
   /* end of the app */
   unlink("/tmp/MyUniqueName"); close(myfd);
   return 0;
}

The code checks if only one instance of an application is running. It uses a write lock on the ~/rosetta-code-lock file to ensure only one instance can set the lock. If the lock setting fails, it assumes another instance is running and exits. The lock is cleared upon program termination. If the program is terminated via an interrupt or signal, the lock file persists but the lock is cleared. The code also handles scenarios where the file system doesn't support file locking. It also creates a file with O_CREAT|O_EXCL and if the file exists, it assumes another instance is running. The code makes sure to unlink the file upon termination. It also handles signal interruptions and ensures the file is deleted unless the program is terminated with SIGKILL. The code uses a regular file with open() and unlink(), and an older version used a semaphore with sem_open() and sem_unlink().


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

int main()
{
	printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
	return 0;
}

Dimensions of the screen are (w x h) : 1536 x 864 pixels

calculate the maximum height and width of a window that can fit within the physical display area of the screen without scrolling, considering window decorations and menubars. The code also accounts for multiple monitors and tiling window managers. Tested on Windows 8.1.


are designed to solve a partially filled 9x9 Sudoku grid and display the results in a human-readable format. The solution is based on the Algorithmics of Sudoku and is suitable for size 3 puzzles. For larger puzzles, a more complex version of the code is required.


#include <stdlib.h>
#include <string.h>

int rrand(int m)
{
  return (int)((double)m * ( rand() / (RAND_MAX+1.0) ));
}

#define BYTE(X) ((unsigned char *)(X))
void shuffle(void *obj, size_t nmemb, size_t size)
{
  void *temp = malloc(size);
  size_t n = nmemb;
  while ( n > 1 ) {
    size_t k = rrand(n--);
    memcpy(temp, BYTE(obj) + n*size, size);
    memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);
    memcpy(BYTE(obj) + k*size, temp, size);
  }
  free(temp);
}

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

/* define a shuffle function. e.g. decl_shuffle(double).
 * advantage: compiler is free to optimize the swap operation without
 *            indirection with pointers, which could be much faster.
 * disadvantage: each datatype needs a separate instance of the function.
 *            for a small funciton like this, it's not very big a deal.
 */
#define decl_shuffle(type)				\
void shuffle_##type(type *list, size_t len) {		\
	int j;						\
	type tmp;					\
	while(len) {					\
		j = irand(len);				\
		if (j != len - 1) {			\
			tmp = list[j];			\
			list[j] = list[len - 1];	\
			list[len - 1] = tmp;		\
		}					\
		len--;					\
	}						\
}							\

/* random integer from 0 to n-1 */
int irand(int n)
{
	int r, rand_max = RAND_MAX - (RAND_MAX % n);
	/* reroll until r falls in a range that can be evenly
	 * distributed in n bins.  Unless n is comparable to
	 * to RAND_MAX, it's not *that* important really. */
	while ((r = rand()) >= rand_max);
	return r / (rand_max / n);
}

/* declare and define int type shuffle function from macro */
decl_shuffle(int);

int main()
{
	int i, x[20];

	for (i = 0; i < 20; i++) x[i] = i;
	for (printf("before:"), i = 0; i < 20 || !printf("\n"); i++)
		printf(" %d", x[i]);

	shuffle_int(x, 20);

	for (printf("after: "), i = 0; i < 20 || !printf("\n"); i++)
		printf(" %d", x[i]);
	return 0;
}

Implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm which randomly shuffles the elements of an array. The algorithm modifies the input array in-place, but can be adjusted to return a new array if necessary. It can also be adjusted to iterate from left to right. The function handles integer arrays and potentially arrays of any type. Test cases are provided for validation.


The code takes a year as input and outputs the dates of the last Fridays of each month for that given year. It doesn't support the Julian calendar.


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

int main(int argc, char *argv[]) {
  (void) printf("Goodbye, World!");    /* No automatic newline */
  return EXIT_SUCCESS;
}

"Display the string 'Goodbye, World!' without a trailing newline in C language, considering that the language doesn't automatically insert a newline unless embedded and the last line of a text stream may or may not require a new-line based on the implementation."


Library: GTK
#include <gtk/gtk.h>

void ok_hit(GtkButton *o, GtkWidget **w)
{
  GtkMessageDialog *msg;

  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);

  msg = (GtkMessageDialog *)
    gtk_message_dialog_new(NULL,
			   GTK_DIALOG_MODAL,
			   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,
			   GTK_BUTTONS_OK,
			   "You wrote '%s' and selected the number %d%s",
			   c, (gint)v,
			   (v==75000) ? "" : " which is wrong (75000 expected)!");
  gtk_widget_show_all(GTK_WIDGET(msg));
  (void)gtk_dialog_run(GTK_DIALOG(msg));
  gtk_widget_destroy(GTK_WIDGET(msg));
  if ( v==75000 ) gtk_main_quit();
}

int main(int argc, char **argv)
{
  GtkWindow *win;
  GtkEntry *entry;
  GtkSpinButton *spin;
  GtkButton *okbutton;
  GtkLabel *entry_l, *spin_l;
  GtkHBox *hbox[2];
  GtkVBox *vbox;
  GtkWidget *widgs[2];

  gtk_init(&argc, &argv);

  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(win, "Insert values");

  entry_l = (GtkLabel *)gtk_label_new("Insert a string");
  spin_l =  (GtkLabel *)gtk_label_new("Insert 75000");

  entry = (GtkEntry *)gtk_entry_new();
  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);

  widgs[0] = GTK_WIDGET(entry);
  widgs[1] = GTK_WIDGET(spin);

  okbutton = (GtkButton *)gtk_button_new_with_label("Ok");

  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);

  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);

  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));
  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));

  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));

  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));

  g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
  g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs);

  gtk_widget_show_all(GTK_WIDGET(win));
  gtk_main();

  return 0;
}

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


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

#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
#define decrypt_rot(x, y) rot((26-x), y)

void rot(int c, char *str)
{
	int l = strlen(str);

        const char*  alpha_low  = "abcdefghijklmnopqrstuvwxyz";

        const char*  alpha_high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

       char subst;  /* substitution character */
       int idx;    /* index */

         int i; /* loop var */

	for (i = 0; i < l; i++)  /* for each letter in string */
	{
		if( 0 == isalpha(str[i]) )  continue; /* not alphabet character */

                idx = (int) (tolower(str[i]) - 'a') + c) % 26; /* compute index */

		if( isupper(str[i]) )
                    subst = alpha_high[idx];
                else
                    subst = alpha_low[idx];

               str[i] = subst;

	}
}

int main(int argc, char** argv)
{
	char str[] = "This is a top secret text message!";

	printf("Original: %s\n", str);
	caesar(str);
	printf("Encrypted: %s\n", str);
	decaesar(str);
	printf("Decrypted: %s\n", str);

	return 0;
}

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


#include <stdio.h>

int gcd(int m, int n)
{
        int tmp;
        while(m) { tmp = m; m = n % m; n = tmp; }
        return n;
}

int lcm(int m, int n)
{
        return m / gcd(m, n) * n;
}

int main()
{
        printf("lcm(35, 21) = %d\n", lcm(21,35));
        return 0;
}

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


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

int cusipCheck(char str[10]){
	int sum=0,i,v;

	for(i=0;i<8;i++){
		if(str[i]>='0'&&str[i]<='9')
			v = str[i]-'0';
		else if(str[i]>='A'&&str[i]<='Z')
			v = (str[i] - 'A' + 10);
		else if(str[i]=='*')
			v = 36;
		else if(str[i]=='@')
			v = 37;
		else if(str[i]=='#')
			v = 38;
		if(i%2!=0)
			v*=2;

		sum += ((int)(v/10) + v%10);
	}
	return ((10 - (sum%10))%10);
}

int main(int argC,char* argV[])
{
	char cusipStr[10];

	int i,numLines;

	if(argC==1)
		printf("Usage : %s <full path of CUSIP Data file>",argV[0]);

	else{
		FILE* fp = fopen(argV[1],"r");

		fscanf(fp,"%d",&numLines);

		printf("CUSIP       Verdict\n");
		printf("-------------------");

		for(i=0;i<numLines;i++){

			fscanf(fp,"%s",cusipStr);

			printf("\n%s : %s",cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?"Valid":"Invalid");
		}

		fclose(fp);
	}
	return 0;
}

6
037833100
17275R102
38259P508
594918104
68389X106
68389X105

C:\rosettaCode>cusipCheck.exe cusipData.txt
CUSIP       Verdict
-------------------
037833100 : Valid
17275R102 : Valid
38259P508 : Valid
594918104 : Valid
68389X106 : Invalid
68389X105 : Valid

The code reads CUSIP strings from a file, verifies the correctness of the last digit (check digit) of each CUSIP code, and prints the results to the console. The CUSIP code is a nine-character alphanumeric code that identifies a North American financial security. The verification process involves a specific algorithm that takes into account the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. If invoked incorrectly, usage instructions are printed.


#include <stdio.h>
#include <stddef.h> /* for size_t */
#include <limits.h> /* for CHAR_BIT */

int main() {
    int one = 1;

    /*
     * Best bet: size_t typically is exactly one word.
     */
    printf("word size = %d bits\n", (int)(CHAR_BIT * sizeof(size_t)));

    /*
     * Check if the least significant bit is located
     * in the lowest-address byte.
     */
    if (*(char *)&one)
        printf("little endian\n");
    else
        printf("big endian\n");
    return 0;
}

#include <stdio.h>
#include <arpa/inet.h>

int main()
{
  if (htonl(1) == 1)
    printf("big endian\n");
  else
    printf("little endian\n");
}

"Outputs the word size and endianness of the host machine, and tests the endianness on POSIX-compatible systems using network order."


This example is incorrect.  Please fix the code and remove this message.Details: Compiles without error but "Segmentation fault" when run. Tested on Cygwin, SuSE Linux and Arch Linux (Manjaro)

This example is in need of improvement:
This solution uses an external program wget for networking, but it could use Library: libcurl (see Web scraping#C) for example. Also this solution scrapes Special:Categories &limit 5000 which will break if the HTML style changes or the number of languages exceeds 5000. It could use the MediWiki API to get the language names and pages in a single call, in blocks of 500 until complete with no upper limit. See the Awk example. If you make an API-based version please retain the web-scrapping version in its own sub-section (following the lead of TCL on this page).

Ghetto parser#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char * lang_url = "http://www.rosettacode.org/w/api.php?action=query&"
		"list=categorymembers&cmtitle=Category:Programming_Languages&"
		"cmlimit=500&format=json";
const char * cat_url = "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000";

#define BLOCK 1024
char *get_page(const char *url)
{
	char cmd[1024];
	char *ptr, *buf;
	int bytes_read = 1, len = 0;
	sprintf(cmd, "wget -q \"%s\" -O -", url);
	FILE *fp = popen(cmd, "r");
	if (!fp) return 0;
	for (ptr = buf = 0; bytes_read > 0; ) {
		buf = realloc(buf, 1 + (len += BLOCK));
		if (!ptr) ptr = buf;
		bytes_read = fread(ptr, 1, BLOCK, fp);
		if (bytes_read <= 0) break;
		ptr += bytes_read;
	}
	*++ptr = '\0';
	return buf;
}

char ** get_langs(char *buf, int *l)
{
	char **arr = 0;
	for (*l = 0; (buf = strstr(buf, "Category:")) && (buf += 9); ++*l)
		for (	(*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;
			*buf != '"' || (*buf++ = 0);
			buf++);

	return arr;
}

typedef struct { const char *name; int count; } cnt_t;
cnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)
{
	char str[1024], *found;
	cnt_t *list = 0;
	int i, llen = 0;
	for (i = 0; i < len; i++) {
		sprintf(str, "/wiki/Category:%s", langs[i]);
		if (!(found = strstr(buf, str))) continue;
		buf = found + strlen(str);

		if (!(found = strstr(buf, "</a> ("))) continue;
		list = realloc(list, sizeof(cnt_t) * ++llen);
		list[llen - 1].name = langs[i];
		list[llen - 1].count = strtol(found + 6, 0, 10);
	}
	*ret_len = llen;
	return list;
}

int _scmp(const void *a, const void *b)
{
	int x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;
	return x < y ? -1 : x > y;
}

int main()
{
	int len, clen;
	char ** langs = get_langs(get_page(lang_url), &len);
	cnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);
	qsort(cats, clen, sizeof(cnt_t), _scmp);
	while (--clen >= 0)
		printf("%4d %s\n", cats[clen].count, cats[clen].name);

	return 0;
}

The code ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It scrapes data from the web or uses the API method to access the data. The code can filter incorrect results and cross-check against the MostLinkedCategories or a complete list of programming languages. It compiles using cJSON and gcc, and outputs the top 'n' languages, with a default of 10.


#include <stdio.h>
...

const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
   printf("%s\n", list[ix]);
}

#include <stdio.h>
#include <stdlib.h>
/* foreach macro for using a string as a collection of char */
#define foreach( ptrvar , strvar ) char* ptrvar; for( ptrvar=strvar ; (*ptrvar) != '\0' ; *ptrvar++)

int main(int argc,char* argv[]){
char* s1="abcdefg";
char* s2="123456789";
foreach( p1 , s1 ) {
 printf("loop 1 %c\n",*p1);
}
foreach( p2 , s2 ){
 printf("loop 2 %c\n",*p2);
}
exit(0);
return(0);
}

#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[]){
/* foreach macro viewing an array of int values as a collection of int values */
#define foreach( intpvar , intary ) int* intpvar; for( intpvar=intary; intpvar < (intary+(sizeof(intary)/sizeof(intary[0]))) ; intpvar++)
int a1[]={ 1 , 1 , 2 , 3 , 5 , 8 };
int a2[]={ 3 , 1 , 4 , 1, 5, 9 };
foreach( p1 , a1 ) {
 printf("loop 1 %d\n",*p1);
}
foreach( p2 , a2 ){
 printf("loop 2 %d\n",*p2);
}
exit(0);
return(0);
}

Note: idxtype can be removed and typeof(col[0]) can be used in it's place with GCC
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[]){
#define foreach( idxtype , idxpvar , col , colsiz ) idxtype* idxpvar; for( idxpvar=col ; idxpvar < (col+(colsiz)) ; idxpvar++)
#define arraylen( ary ) ( sizeof(ary)/sizeof(ary[0]) )
char* c1="collection";
int c2[]={ 3 , 1 , 4 , 1, 5, 9 };
double* c3;
int c3len=4;
c3=(double*)calloc(c3len,sizeof(double));
c3[0]=1.2;c3[1]=3.4;c3[2]=5.6;c3[3]=7.8;
foreach( char,p1   , c1, strlen(c1) ) {
 printf("loop 1 : %c\n",*p1);
}
foreach( int,p2    , c2, arraylen(c2) ){
 printf("loop 2 : %d\n",*p2);
}
foreach( double,p3 , c3, c3len ){
 printf("loop 3 : %3.1lf\n",*p3);
}
exit(0);
return(0);
}

demonstrate how to iterate through a collection in C using a loop, as it doesn't have a native 'for each' statement or 'container' type. The codes show how to print each element of a C string (collection of char), an int array (collection of int), and a general string or array (collection size known at run-time).


Works with: ANSI C
Library: POSIX

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

int main(void)
{
	char *a[5];
	const char *s="Hello,How,Are,You,Today";
	int n=0, nn;

	char *ds=strdup(s);

	a[n]=strtok(ds, ",");
	while(a[n] && n<4) a[++n]=strtok(NULL, ",");

	for(nn=0; nn<=n; ++nn) printf("%s.", a[nn]);
	putchar('\n');

	free(ds);

	return 0;
}

#include<stdio.h>

typedef void (*callbackfunc)(const char *);

void doprint(const char *s) {
	printf("%s.", s);
}

void tokenize(char *s, char delim, callbackfunc cb) {
	char *olds = s;
	char olddelim = delim;
	while(olddelim && *s) {
		while(*s && (delim != *s)) s++;
		*s ^= olddelim = *s; // olddelim = *s; *s = 0;
		cb(olds);
		*s++ ^= olddelim; // *s = olddelim; s++;
		olds = s;
	}
}

int main(void)
{
        char array[] = "Hello,How,Are,You,Today";
	tokenize(array, ',', doprint);
	return 0;
}

"Tokenizes a string by separating it into an array based on comma delimiters, then displays the words to the user separated by periods. The strtok() function is used for tokenization, which modifies the original string, hence a copy of the string is made using strdup(). Alternatively, the task can be accomplished by temporarily modifying the separator character without using additional memory, but this requires the input string to be writable."


int
gcd_iter(int u, int v) {
  if (u < 0) u = -u;
  if (v < 0) v = -v;
  if (v) while ((u %= v) && (v %= u));
  return (u + v);
}

int gcd(int u, int v) {
return (v != 0)?gcd(v, u%v):u;
}

int gcd_bin(int u, int v) {
  int t, k;

  u = u < 0 ? -u : u; /* abs(u) */
  v = v < 0 ? -v : v;
  if (u < v) {
    t = u;
    u = v;
    v = t;
  }
  if (v == 0)
    return u;

  k = 1;
  while ((u & 1) == 0 && (v & 1) == 0) { /* u, v - even */
    u >>= 1; v >>= 1;
    k <<= 1;
  }

  t = (u & 1) ? -v : u;
  while (t) {
    while ((t & 1) == 0)
      t >>= 1;

    if (t > 0)
      u = t;
    else
      v = -t;

    t = u - v;
  }
  return u * k;
}

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.