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

typedef struct { double x, y; } vec_t, *vec;

inline double dot(vec a, vec b)
{
	return a->x * b->x + a->y * b->y;
}

inline double cross(vec a, vec b)
{
	return a->x * b->y - a->y * b->x;
}

inline vec vsub(vec a, vec b, vec res)
{
	res->x = a->x - b->x;
	res->y = a->y - b->y;
	return res;
}

/* tells if vec c lies on the left side of directed edge a->b
 * 1 if left, -1 if right, 0 if colinear
 */
int left_of(vec a, vec b, vec c)
{
	vec_t tmp1, tmp2;
	double x;
	vsub(b, a, &tmp1);
	vsub(c, b, &tmp2);
	x = cross(&tmp1, &tmp2);
	return x < 0 ? -1 : x > 0;
}

int line_sect(vec x0, vec x1, vec y0, vec y1, vec res)
{
	vec_t dx, dy, d;
	vsub(x1, x0, &dx);
	vsub(y1, y0, &dy);
	vsub(x0, y0, &d);
	/* x0 + a dx = y0 + b dy ->
	   x0 X dx = y0 X dx + b dy X dx ->
	   b = (x0 - y0) X dx / (dy X dx) */
	double dyx = cross(&dy, &dx);
	if (!dyx) return 0;
	dyx = cross(&d, &dx) / dyx;
	if (dyx <= 0 || dyx >= 1) return 0;

	res->x = y0->x + dyx * dy.x;
	res->y = y0->y + dyx * dy.y;
	return 1;
}

/* === polygon stuff === */
typedef struct { int len, alloc; vec v; } poly_t, *poly;

poly poly_new()
{
	return (poly)calloc(1, sizeof(poly_t));
}

void poly_free(poly p)
{
	free(p->v);
	free(p);
}

void poly_append(poly p, vec v)
{
	if (p->len >= p->alloc) {
		p->alloc *= 2;
		if (!p->alloc) p->alloc = 4;
		p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
	}
	p->v[p->len++] = *v;
}

/* this works only if all of the following are true:
 *   1. poly has no colinear edges;
 *   2. poly has no duplicate vertices;
 *   3. poly has at least three vertices;
 *   4. poly is convex (implying 3).
*/
int poly_winding(poly p)
{
	return left_of(p->v, p->v + 1, p->v + 2);
}

void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)
{
	int i, side0, side1;
	vec_t tmp;
	vec v0 = sub->v + sub->len - 1, v1;
	res->len = 0;

	side0 = left_of(x0, x1, v0);
	if (side0 != -left) poly_append(res, v0);

	for (i = 0; i < sub->len; i++) {
		v1 = sub->v + i;
		side1 = left_of(x0, x1, v1);
		if (side0 + side1 == 0 && side0)
			/* last point and current straddle the edge */
			if (line_sect(x0, x1, v0, v1, &tmp))
				poly_append(res, &tmp);
		if (i == sub->len - 1) break;
		if (side1 != -left) poly_append(res, v1);
		v0 = v1;
		side0 = side1;
	}
}

poly poly_clip(poly sub, poly clip)
{
	int i;
	poly p1 = poly_new(), p2 = poly_new(), tmp;

	int dir = poly_winding(clip);
	poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);
	for (i = 0; i < clip->len - 1; i++) {
		tmp = p2; p2 = p1; p1 = tmp;
		if(p1->len == 0) {
			p2->len = 0;
			break;
		}
		poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);
	}

	poly_free(p1);
	return p2;
}

int main()
{
	int i;
	vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};
	//vec_t c[] = {{100,300}, {300,300}, {300,100}, {100,100}};
	vec_t s[] = {	{50,150}, {200,50}, {350,150},
			{350,300},{250,300},{200,250},
			{150,350},{100,250},{100,200}};
#define clen (sizeof(c)/sizeof(vec_t))
#define slen (sizeof(s)/sizeof(vec_t))
	poly_t clipper = {clen, 0, c};
	poly_t subject = {slen, 0, s};

	poly res = poly_clip(&subject, &clipper);

	for (i = 0; i < res->len; i++)
		printf("%g %g\n", res->v[i].x, res->v[i].y);

	/* long and arduous EPS printout */
	FILE * eps = fopen("test.eps", "w");
	fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n"
		"/l {lineto} def /m{moveto} def /s{setrgbcolor} def"
		"/c {closepath} def /gs {fill grestore stroke} def\n");
	fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y);
	for (i = 1; i < clen; i++)
		fprintf(eps, "%g %g l ", c[i].x, c[i].y);
	fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n");

	fprintf(eps, "%g %g m ", s[0].x, s[0].y);
	for (i = 1; i < slen; i++)
		fprintf(eps, "%g %g l ", s[i].x, s[i].y);
	fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n");

	fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ",
		res->v[0].x, res->v[0].y);
	for (i = 1; i < res->len; i++)
		fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y);
	fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n");

	fprintf(eps, "%%%%EOF");
	fclose(eps);
	printf("test.eps written\n");

	return 0;
}

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as input, clips the polygon by the rectangle, and outputs the sequence of points defining the resulting clipped polygon. Additionally, it provides an option to visually display all three polygons on a graphical surface, with each polygon in a different color. The code also includes utility routines for storage and writes the test results to a 'test.eps' file in the current directory.


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

typedef struct{
	int score;
	char name[100];
}entry;

void ordinalRanking(entry* list,int len){

	int i;

	printf("\n\nOrdinal Ranking\n---------------");

	for(i=0;i<len;i++)
		printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
}

void standardRanking(entry* list,int len){

	int i,j=1;

	printf("\n\nStandard Ranking\n----------------");

	for(i=0;i<len;i++){
		printf("\n%d\t%d\t%s",j,list[i].score,list[i].name);
		if(list[i+1].score<list[i].score)
			j = i+2;
	}
}

void denseRanking(entry* list,int len){

	int i,j=1;

	printf("\n\nDense Ranking\n-------------");

	for(i=0;i<len;i++){
		printf("\n%d\t%d\t%s",j,list[i].score,list[i].name);
		if(list[i+1].score<list[i].score)
			j++;
	}
}

void modifiedRanking(entry* list,int len){

	int i,j,count;

	printf("\n\nModified Ranking\n----------------");

	for(i=0;i<len-1;i++){
		if(list[i].score!=list[i+1].score){
			printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
			count = 1;
			for(j=i+1;list[j].score==list[j+1].score && j<len-1;j++)
				count ++;
			for(j=0;j<count-1;j++)
				printf("\n%d\t%d\t%s",i+count+1,list[i+j+1].score,list[i+j+1].name);
			i += (count-1);
		}
	}
	printf("\n%d\t%d\t%s",len,list[len-1].score,list[len-1].name);
}

void fractionalRanking(entry* list,int len){

	int i,j,count;
	float sum = 0;

	printf("\n\nFractional Ranking\n------------------");

	for(i=0;i<len;i++){
		if(i==len-1 || list[i].score!=list[i+1].score)
			printf("\n%.1f\t%d\t%s",(float)(i+1),list[i].score,list[i].name);
		else if(list[i].score==list[i+1].score){
			sum = i;
			count = 1;
			for(j=i;list[j].score==list[j+1].score;j++){
				sum += (j+1);
				count ++;
			}
			for(j=0;j<count;j++)
				printf("\n%.1f\t%d\t%s",sum/count + 1,list[i+j].score,list[i+j].name);
			i += (count-1);
		}
	}
}

void processFile(char* fileName){
	FILE* fp = fopen(fileName,"r");
	entry* list;
	int i,num;

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

	list = (entry*)malloc(num*sizeof(entry));

	for(i=0;i<num;i++)
		fscanf(fp,"%d%s",&list[i].score,list[i].name);

	fclose(fp);

	ordinalRanking(list,num);
	standardRanking(list,num);
	denseRanking(list,num);
	modifiedRanking(list,num);
	fractionalRanking(list,num);
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		printf("Usage %s <score list file>");
	else
		processFile(argV[1]);
	return 0;
}

7
44 Solomon
42 Jason
42 Errol
41 Garry
41 Bernard
41 Barry
39 Stephen

C:\rosettaCode>ranking.exe rankData.txt

Ordinal Ranking
---------------
1       44      Solomon
2       42      Jason
3       42      Errol
4       41      Garry
5       41      Bernard
6       41      Barry
7       39      Stephen

Standard Ranking
----------------
1       44      Solomon
2       42      Jason
2       42      Errol
4       41      Garry
4       41      Bernard
4       41      Barry
7       39      Stephen

Dense Ranking
-------------
1       44      Solomon
2       42      Jason
2       42      Errol
3       41      Garry
3       41      Bernard
3       41      Barry
4       39      Stephen

Modified Ranking
----------------
1       44      Solomon
3       42      Jason
3       42      Errol
6       41      Garry
6       41      Bernard
6       41      Barry
7       39      Stephen

Fractional Ranking
------------------
1.0     44      Solomon
2.5     42      Jason
2.5     42      Errol
5.0     41      Garry
5.0     41      Bernard
5.0     41      Barry
7.0     39      Stephen

"Code implements various ranking methods (Standard, Modified, Dense, Ordinal, Fractional) for competitors in a competition. It takes competition scores from an input file, assigns ranks based on each method, and outputs the rankings. It also handles incorrect invocation by displaying usage instructions."


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

int main() {
  double pi = 4 * atan(1);
  /*Pi / 4 is 45 degrees. All answers should be the same.*/
  double radians = pi / 4;
  double degrees = 45.0;
  double temp;
  /*sine*/
  printf("%f %f\n", sin(radians), sin(degrees * pi / 180));
  /*cosine*/
  printf("%f %f\n", cos(radians), cos(degrees * pi / 180));
  /*tangent*/
  printf("%f %f\n", tan(radians), tan(degrees * pi / 180));
  /*arcsine*/
  temp = asin(sin(radians));
  printf("%f %f\n", temp, temp * 180 / pi);
  /*arccosine*/
  temp = acos(cos(radians));
  printf("%f %f\n", temp, temp * 180 / pi);
  /*arctangent*/
  temp = atan(tan(radians));
  printf("%f %f\n", temp, temp * 180 / pi);

  return 0;
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.


Library: POSIX

#include <stdio.h>
#include <stdlib.h>	// for exit()
#include <signal.h>
#include <time.h>	// for clock()
#include <unistd.h>	// for POSIX usleep()

volatile sig_atomic_t gotint = 0;

void handleSigint() {
    /*
     * Signal safety: It is not safe to call clock(), printf(),
     * or exit() inside a signal handler. Instead, we set a flag.
     */
    gotint = 1;
}

int main() {
    clock_t startTime = clock();
    signal(SIGINT, handleSigint);
    int i=0;
    for (;;) {
        if (gotint)
            break;
        usleep(500000);
        if (gotint)
            break;
	printf("%d\n", ++i);
    }
    clock_t endTime = clock();
    double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
    printf("Program has run for %5.3f seconds\n", td);
    return 0;
}

The code outputs an integer every half second. When a SIGINT or SIGQUIT signal is received, typically from the user typing ctrl-C or ctrl-\, the program stops outputting integers, displays the total runtime in seconds, and then terminates. To achieve the half-second delay, the POSIX usleep() function is used instead of the standard C's sleep() function. Signal handlers are implemented to ensure the program behaves predictably upon receiving a signal.


Handling strings of arbitrary sizes:#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*  Constraints: input is in the form of (\+|-)?[0-9]+
 *  and without leading zero (0 itself can be as "0" or "+0", but not "-0");
 *  input pointer is realloc'able and may change;
 *  if input has leading + sign, return may or may not keep it.
 *  The constranits conform to sprintf("%+d") and this function's own output.
 */
char * incr(char *s)
{
	int i, begin, tail, len;
	int neg = (*s == '-');
	char tgt = neg ? '0' : '9';

	/* special case: "-1" */
	if (!strcmp(s, "-1")) {
		s[0] = '0', s[1] = '\0';
		return s;
	}

	len = strlen(s);
	begin = (*s == '-' || *s == '+') ? 1 : 0;

	/* find out how many digits need to be changed */
	for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);

	if (tail < begin && !neg) {
		/* special case: all 9s, string will grow */
		if (!begin) s = realloc(s, len + 2);
		s[0] = '1';
		for (i = 1; i <= len - begin; i++) s[i] = '0';
		s[len + 1] = '\0';
	} else if (tail == begin && neg && s[1] == '1') {
		/* special case: -1000..., so string will shrink */
		for (i = 1; i < len - begin; i++) s[i] = '9';
		s[len - 1] = '\0';
	} else { /* normal case; change tail to all 0 or 9, change prev digit by 1*/
		for (i = len - 1; i > tail; i--)
			s[i] = neg ? '9' : '0';
		s[tail] += neg ? -1 : 1;
	}

	return s;
}

void string_test(const char *s)
{
	char *ret = malloc(strlen(s));
	strcpy(ret, s);

	printf("text: %s\n", ret);
	printf("  ->: %s\n", ret = incr(ret));
	free(ret);
}

int main()
{
	string_test("+0");
	string_test("-1");
	string_test("-41");
	string_test("+41");
	string_test("999");
	string_test("+999");
	string_test("109999999999999999999999999999999999999999");
	string_test("-100000000000000000000000000000000000000000000");

	return 0;
}


#include <stdio.h>

int common_len(const char *const *names, int n, char sep)
{
	int i, pos;
	for (pos = 0; ; pos++) {
		for (i = 0; i < n; i++) {
			if (names[i][pos] != '\0' &&
					names[i][pos] == names[0][pos])
				continue;

			/* backtrack */
			while (pos > 0 && names[0][--pos] != sep);
			return pos;
		}
	}

	return 0;
}

int main()
{
	const char *names[] = {
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
	};
	int len = common_len(names, sizeof(names) / sizeof(const char*), '/');

	if (!len) printf("No common path\n");
	else      printf("Common path: %.*s\n", len, names[0]);

	return 0;
}
output:Common path: /home/user1/tmp

The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.


Interactive and without hardcoded inputs[edit]
#include<stdlib.h>
#include<stdio.h>
#include<time.h>

void sattoloCycle(void** arr,int count){
	int i,j;
	void* temp;

	if(count<2)
		return;
	for(i=count-1;i>=1;i--){
		j = rand()%i;
		temp = arr[j];
		arr[j] = arr[i];
		arr[i] = temp;
	}
}

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

	if(argC==1)
		printf("Usage : %s <array elements separated by a space each>",argV[0]);
	else{
                srand((unsigned)time(NULL));
		sattoloCycle((void*)(argV + 1),argC-1);

		for(i=1;i<argC;i++)
			printf("%s ",argV[i]);
	}
	return 0;
}

C:\rosettaCode>sattoloCycle.exe ""

C:\rosettaCode>sattoloCycle.exe 10
10
C:\rosettaCode>sattoloCycle.exe 10 20
20 10
C:\rosettaCode>sattoloCycle.exe 10 20 30
30 10 20
C:\rosettaCode>sattoloCycle.exe 11 12 13 14 15 16 17 18 19 20 21 22
16 17 11 12 13 20 22 14 15 21 18 19
C:\rosettaCode>sattoloCycle.exe s a t t o l o C y c l e
l o s a t c e t o l C y
C:\rosettaCode>sattoloCycle.exe 1 2.3 4.2 1 3 e r q t 2 1 oo 2.1 eds
1 2.1 2.3 q r eds 1 e 3 t 1 2 oo 4.2
C:\rosettaCode>sattoloCycle.exe totally mixed up random string ( 1 2.3 2 ) which will get even more { a 2 q.1 } mixed up.
mixed q.1 a 1 up ) 2 even { will ( } 2 more totally random get which string up. 2.3 mixed

Non Interactive and with hardcoded inputs[edit]

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

void sattoloCycle(void** arr,int count){
	int i,j;
	void* temp;

	if(count<2)
		return;
	for(i=count-1;i>=1;i--){
		j = rand()%i;
		temp = arr[j];
		arr[j] = arr[i];
		arr[i] = temp;
	}
}

int main()
{
	int i;

	int a[] = {};
	int b[] = {10};
	int c[] = {10, 20};
	int d[] = {10, 20, 30};
	int e[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};

	srand((unsigned)time(NULL));
	sattoloCycle((void*)a,0);

	printf("\nShuffled a = ");
	for(i=0;i<0;i++)
		printf("%d ",a[i]);

	sattoloCycle((void*)b,1);

	printf("\nShuffled b = ");
	for(i=0;i<1;i++)
		printf("%d ",b[i]);

	sattoloCycle((void*)c,2);

	printf("\nShuffled c = ");
	for(i=0;i<2;i++)
		printf("%d ",c[i]);

	sattoloCycle((void*)d,3);

	printf("\nShuffled d = ");
	for(i=0;i<3;i++)
		printf("%d ",d[i]);

	sattoloCycle((void*)e,12);

	printf("\nShuffled e = ");
	for(i=0;i<12;i++)
		printf("%d ",e[i]);

	return 0;
}

Shuffled a =
Shuffled b = 10
Shuffled c = 20 10
Shuffled d = 20 30 10
Shuffled e = 13 18 14 20 17 15 21 19 16 12 22 11

implement the Sattolo cycle algorithm that shuffles an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place or returns a new array based on the programming language's convenience. The function can handle any type of array.


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

size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
    return fwrite(ptr,size,nmeb,stream);
}

size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
    return fread(ptr,size,nmeb,stream);
}

void callSOAP(char* URL, char * inFile, char * outFile) {

    FILE * rfp = fopen(inFile, "r");
    if(!rfp)
        perror("Read File Open:");

    FILE * wfp = fopen(outFile, "w+");
    if(!wfp)
        perror("Write File Open:");

    struct curl_slist *header = NULL;
		header = curl_slist_append (header, "Content-Type:text/xml");
		header = curl_slist_append (header, "SOAPAction: rsc");
		header = curl_slist_append (header, "Transfer-Encoding: chunked");
		header = curl_slist_append (header, "Expect:");
    CURL *curl;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, URL);
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
        curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
        curl_easy_perform(curl);

        curl_easy_cleanup(curl);
    }
}

int main(int argC,char* argV[])
{
	if(argC!=4)
		printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
	else
		callSOAP(argV[1],argV[2],argV[3]);
	return 0;
}

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dom="http://example.com/soap/wsdl">
   <soapenv:Header/>
   <soapenv:Body>
      <dom:soapFunc soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
   </soapenv:Body>
</soapenv:Envelope>

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dom="http://example.com/soap/wsdl">
   <soapenv:Header/>
   <soapenv:Body>
      <dom:anotherSoapFunc soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
   </soapenv:Body>
</soapenv:Envelope>

The code creates a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() defined at http://example.com/soap/wsdl. It requires the construction of input XML files for these functions and may need libraries like xerces if written in C. Note that the code may be flagged incorrect due to pending task clarification.


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

typedef struct floatList {
    float *list;
    int   size;
} *FloatList;

int floatcmp( const void *a, const void *b) {
    if (*(const float *)a < *(const float *)b) return -1;
    else return *(const float *)a > *(const float *)b;
}

float median( FloatList fl )
{
    qsort( fl->list, fl->size, sizeof(float), floatcmp);
    return 0.5 * ( fl->list[fl->size/2] + fl->list[(fl->size-1)/2]);
}

int main()
{
    static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 };
    static struct floatList flist1 = { floats1, sizeof(floats1)/sizeof(float) };

    static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 };
    static struct floatList flist2 = { floats2, sizeof(floats2)/sizeof(float) };

    printf("flist1 median is %7.2f\n", median(&flist1)); /* 4.85 */
    printf("flist2 median is %7.2f\n", median(&flist2)); /* 4.60 */
    return 0;
}

Quickselect algorithm[edit]

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

#define MAX_ELEMENTS 1000000

/* Return the k-th smallest item in array x of length len */
double quick_select(int k, double *x, int len)
{
   inline void swap(int a, int b)
   {
      double t = x[a];
      x[a] = x[b], x[b] = t;
   }

   int left = 0, right = len - 1;
   int pos, i;
   double pivot;

   while (left < right)
   {
      pivot = x[k];
      swap(k, right);
      for (i = pos = left; i < right; i++)
      {
         if (x[i] < pivot)
         {
            swap(i, pos);
            pos++;
         }
      }
      swap(right, pos);
      if (pos == k) break;
      if (pos < k) left = pos + 1;
      else right = pos - 1;
   }
   return x[k];
}

int main(void)
{
   int i, length;
   double *x, median;

   /* Initialize random length double array with random doubles */
   srandom(time(0));
   length = random() % MAX_ELEMENTS;
   x = malloc(sizeof(double) * length);
   for (i = 0; i < length; i++)
   {
      // shifted by RAND_MAX for negative values
      // divide by a random number for floating point
      x[i] = (double)(random() - RAND_MAX / 2) / (random() + 1); // + 1 to not divide by 0
   }

   if (length % 2 == 0) // Even number of elements, median is average of middle two
   {
      median = (quick_select(length / 2, x, length) + quick_select(length / 2 - 1, x, length / 2)) / 2;
   }
   else // select middle element
   {
      median = quick_select(length / 2, x, length);
   }

   /* Sanity testing of median */
   int less = 0, more = 0, eq = 0;
   for (i = 0; i < length; i++)
   {
      if (x[i] < median) less ++;
      else if (x[i] > median) more ++;
      else eq ++;
   }
   printf("length: %d\nmedian: %lf\n<: %d\n>: %d\n=: %d\n", length, median, less, more, eq);

   free(x);
   return 0;
}

length: 992021
median: 0.000473
<: 496010
>: 496010
=: 1

find the median value of a vector of floating-point numbers. It handles the case of an even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time efficiency. The code also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation.


The code prints integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. This is a solution to the FizzBuzz problem, demonstrating basic programming comprehension. The code is optimized for low signal-to-noise and is presented in various forms including one-line, pretty printing, and obfuscated versions.


PPM non interactive[edit]

 /*
 c program:
 --------------------------------
  1. draws Mandelbrot set for Fc(z)=z*z +c
  using Mandelbrot algorithm ( boolean escape time )
 -------------------------------
 2. technique of creating ppm file is  based on the code of Claudio Rocchini
 http://en.wikipedia.org/wiki/Image:Color_complex_plot.jpg
 create 24 bit color graphic file ,  portable pixmap file = PPM
 see http://en.wikipedia.org/wiki/Portable_pixmap
 to see the file use external application ( graphic viewer)
  */
 #include <stdio.h>
 #include <math.h>
 int main()
 {
          /* screen ( integer) coordinate */
        int iX,iY;
        const int iXmax = 800;
        const int iYmax = 800;
        /* world ( double) coordinate = parameter plane*/
        double Cx,Cy;
        const double CxMin=-2.5;
        const double CxMax=1.5;
        const double CyMin=-2.0;
        const double CyMax=2.0;
        /* */
        double PixelWidth=(CxMax-CxMin)/iXmax;
        double PixelHeight=(CyMax-CyMin)/iYmax;
        /* color component ( R or G or B) is coded from 0 to 255 */
        /* it is 24 bit color RGB file */
        const int MaxColorComponentValue=255;
        FILE * fp;
        char *filename="new1.ppm";
        char *comment="# ";/* comment should start with # */
        static unsigned char color[3];
        /* Z=Zx+Zy*i  ;   Z0 = 0 */
        double Zx, Zy;
        double Zx2, Zy2; /* Zx2=Zx*Zx;  Zy2=Zy*Zy  */
        /*  */
        int Iteration;
        const int IterationMax=200;
        /* bail-out value , radius of circle ;  */
        const double EscapeRadius=2;
        double ER2=EscapeRadius*EscapeRadius;
        /*create new file,give it a name and open it in binary mode  */
        fp= fopen(filename,"wb"); /* b -  binary mode */
        /*write ASCII header to the file*/
        fprintf(fp,"P6\n %s\n %d\n %d\n %d\n",comment,iXmax,iYmax,MaxColorComponentValue);
        /* compute and write image data bytes to the file*/
        for(iY=0;iY<iYmax;iY++)
        {
             Cy=CyMin + iY*PixelHeight;
             if (fabs(Cy)< PixelHeight/2) Cy=0.0; /* Main antenna */
             for(iX=0;iX<iXmax;iX++)
             {
                        Cx=CxMin + iX*PixelWidth;
                        /* initial value of orbit = critical point Z= 0 */
                        Zx=0.0;
                        Zy=0.0;
                        Zx2=Zx*Zx;
                        Zy2=Zy*Zy;
                        /* */
                        for (Iteration=0;Iteration<IterationMax && ((Zx2+Zy2)<ER2);Iteration++)
                        {
                            Zy=2*Zx*Zy + Cy;
                            Zx=Zx2-Zy2 +Cx;
                            Zx2=Zx*Zx;
                            Zy2=Zy*Zy;
                        };
                        /* compute  pixel color (24 bit = 3 bytes) */
                        if (Iteration==IterationMax)
                        { /*  interior of Mandelbrot set = black */
                           color[0]=0;
                           color[1]=0;
                           color[2]=0;
                        }
                     else
                        { /* exterior of Mandelbrot set = white */
                             color[0]=255; /* Red*/
                             color[1]=255;  /* Green */
                             color[2]=255;/* Blue */
                        };
                        /*write color to the file*/
                        fwrite(color,1,3,fp);
                }
        }
        fclose(fp);
        return 0;
 }

PPM Interactive[edit]

OpenBSD users, install freeglut package, and compile with make mandelbrot CPPFLAGS='-I/usr/local/include `pkg-config glu --cflags`' LDLIBS='-L/usr/local/lib -lglut `pkg-config glu --libs` -lm'
Library: GLUT

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

void set_texture();

typedef struct {unsigned char r, g, b;} rgb_t;
rgb_t **tex = 0;
int gwin;
GLuint texture;
int width, height;
int tex_w, tex_h;
double scale = 1./256;
double cx = -.6, cy = 0;
int color_rotate = 0;
int saturation = 1;
int invert = 0;
int max_iter = 256;

void render()
{
	double	x = (double)width /tex_w,
		y = (double)height/tex_h;

	glClear(GL_COLOR_BUFFER_BIT);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

	glBindTexture(GL_TEXTURE_2D, texture);

	glBegin(GL_QUADS);

	glTexCoord2f(0, 0); glVertex2i(0, 0);
	glTexCoord2f(x, 0); glVertex2i(width, 0);
	glTexCoord2f(x, y); glVertex2i(width, height);
	glTexCoord2f(0, y); glVertex2i(0, height);

	glEnd();

	glFlush();
	glFinish();
}

int dump = 1;
void screen_dump()
{
	char fn[100];
	int i;
	sprintf(fn, "screen%03d.ppm", dump++);
	FILE *fp = fopen(fn, "w");
	fprintf(fp, "P6\n%d %d\n255\n", width, height);
	for (i = height - 1; i >= 0; i--)
		fwrite(tex[i], 1, width * 3, fp);
	fclose(fp);
	printf("%s written\n", fn);
}

void keypress(unsigned char key, int x, int y)
{
	switch(key) {
	case 'q':	glFinish();
			glutDestroyWindow(gwin);
			return;
	case 27:	scale = 1./256; cx = -.6; cy = 0; break;

	case 'r':	color_rotate = (color_rotate + 1) % 6;
			break;

	case '>': case '.':
			max_iter += 128;
			if (max_iter > 1 << 15) max_iter = 1 << 15;
			printf("max iter: %d\n", max_iter);
			break;

	case '<': case ',':
			max_iter -= 128;
			if (max_iter < 128) max_iter = 128;
			printf("max iter: %d\n", max_iter);
			break;

	case 'c':	saturation = 1 - saturation;
			break;

	case 's':	screen_dump(); return;
	case 'z':	max_iter = 4096; break;
	case 'x':	max_iter = 128; break;
	case ' ':	invert = !invert;
	}
	set_texture();
}

void hsv_to_rgb(int hue, int min, int max, rgb_t *p)
{
	if (min == max) max = min + 1;
	if (invert) hue = max - (hue - min);
	if (!saturation) {
		p->r = p->g = p->b = 255 * (max - hue) / (max - min);
		return;
	}
	double h = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6);
#	define VAL 255
	double c = VAL * saturation;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	p->r = p->g = p->b = 0;

	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;
	}
}

void calc_mandel()
{
	int i, j, iter, min, max;
	rgb_t *px;
	double x, y, zx, zy, zx2, zy2;
	min = max_iter; max = 0;
	for (i = 0; i < height; i++) {
		px = tex[i];
		y = (i - height/2) * scale + cy;
		for (j = 0; j  < width; j++, px++) {
			x = (j - width/2) * scale + cx;
			iter = 0;

			zx = hypot(x - .25, y);
			if (x < zx - 2 * zx * zx + .25) iter = max_iter;
			if ((x + 1)*(x + 1) + y * y < 1/16) iter = max_iter;

			zx = zy = zx2 = zy2 = 0;
			for (; iter < max_iter && zx2 + zy2 < 4; iter++) {
				zy = 2 * zx * zy + y;
				zx = zx2 - zy2 + x;
				zx2 = zx * zx;
				zy2 = zy * zy;
			}
			if (iter < min) min = iter;
			if (iter > max) max = iter;
			*(unsigned short *)px = iter;
		}
	}

	for (i = 0; i < height; i++)
		for (j = 0, px = tex[i]; j  < width; j++, px++)
			hsv_to_rgb(*(unsigned short*)px, min, max, px);
}

void alloc_tex()
{
	int i, ow = tex_w, oh = tex_h;

	for (tex_w = 1; tex_w < width;  tex_w <<= 1);
	for (tex_h = 1; tex_h < height; tex_h <<= 1);

	if (tex_h != oh || tex_w != ow)
		tex = realloc(tex, tex_h * tex_w * 3 + tex_h * sizeof(rgb_t*));

	for (tex[0] = (rgb_t *)(tex + tex_h), i = 1; i < tex_h; i++)
		tex[i] = tex[i - 1] + tex_w;
}

void set_texture()
{
	alloc_tex();
	calc_mandel();

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h,
		0, GL_RGB, GL_UNSIGNED_BYTE, tex[0]);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	render();
}

void mouseclick(int button, int state, int x, int y)
{
	if (state != GLUT_UP) return;

	cx += (x - width / 2) * scale;
	cy -= (y - height/ 2) * scale;

	switch(button) {
	case GLUT_LEFT_BUTTON: /* zoom in */
		if (scale > fabs(x) * 1e-16 && scale > fabs(y) * 1e-16)
			scale /= 2;
		break;
	case GLUT_RIGHT_BUTTON: /* zoom out */
		scale *= 2;
		break;
	/* any other button recenters */
	}
	set_texture();
}

void resize(int w, int h)
{
	printf("resize %d %d\n", w, h);
	width = w;
	height = h;

	glViewport(0, 0, w, h);
	glOrtho(0, w, 0, h, -1, 1);

	set_texture();
}

void init_gfx(int *c, char **v)
{
	glutInit(c, v);
	glutInitDisplayMode(GLUT_RGB);
	glutInitWindowSize(640, 480);

	gwin = glutCreateWindow("Mandelbrot");
	glutDisplayFunc(render);

	glutKeyboardFunc(keypress);
	glutMouseFunc(mouseclick);
	glutReshapeFunc(resize);
	glGenTextures(1, &texture);
	set_texture();
}

int main(int c, char **v)
{
	init_gfx(&c, v);
	printf("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t"
		"<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n");

	glutMainLoop();
	return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

void set_texture();

unsigned char *tex;
int gwin;
GLuint texture;
int width, height;
int old_width, old_height;
double scale = 1. / 256;
double cx = -.6, cy = 0;
int color_rotate = 0;
int saturation = 1;
int invert = 0;
int max_iter = 256;

void render()
{
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    glBindTexture(GL_TEXTURE_2D, texture);

    glBegin(GL_QUADS);

    glTexCoord2d(0, 0);
    glVertex2i(0, 0);
    glTexCoord2d(1, 0);
    glVertex2i(width, 0);
    glTexCoord2d(1, 1);
    glVertex2i(width, height);
    glTexCoord2d(0, 1);
    glVertex2i(0, height);

    glEnd();

    glFlush();
    glFinish();
}

int dump = 1;
void screen_dump()
{
    char fn[100];
    sprintf(fn, "screen%03d.ppm", dump++);
    FILE *fp = fopen(fn, "w");
    fprintf(fp, "P6\n%d %d\n255\n", width, height);
    for (int i = height - 1; i >= 0; i -= 1) {
        for (int j = 0; j < width; j += 1) {
            fwrite(&tex[((i * width) + j) * 4], 1, 3, fp);
        }
    }
    fclose(fp);
    printf("%s written\n", fn);
}

void keypress(unsigned char key,[[maybe_unused]]
              int x,[[maybe_unused]]
              int y)
{
    switch (key) {
    case 'q':
        glFinish();
        glutDestroyWindow(gwin);
        break;

    case 27:
        scale = 1. / 256;
        cx = -.6;
        cy = 0;
        set_texture();
        break;

    case 'r':
        color_rotate = (color_rotate + 1) % 6;
        set_texture();
        break;

    case '>':
    case '.':
        max_iter += 128;
        if (max_iter > 1 << 15)
            max_iter = 1 << 15;
        printf("max iter: %d\n", max_iter);
        set_texture();
        break;

    case '<':
    case ',':
        max_iter -= 128;
        if (max_iter < 128)
            max_iter = 128;
        printf("max iter: %d\n", max_iter);
        set_texture();
        break;

    case 'c':
        saturation = 1 - saturation;
        set_texture();
        break;

    case 's':
        screen_dump();
        break;

    case 'z':
        max_iter = 4096;
        set_texture();
        break;

    case 'x':
        max_iter = 128;
        set_texture();
        break;

    case ' ':
        invert = !invert;
        set_texture();
        break;

    default:
        set_texture();
        break;
    }
}

#define VAL 255

void hsv_to_rgba(int hue, int min, int max, unsigned char *px)
{
    unsigned char r;
    unsigned char g;
    unsigned char b;

    if (min == max)
        max = min + 1;
    if (invert)
        hue = max - (hue - min);
    if (!saturation) {
        r = 255 * (max - hue) / (max - min);
        g = r;
        b = r;
    } else {
        double h =
            fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6);
        double c = VAL * saturation;
        double X = c * (1 - fabs(fmod(h, 2) - 1));

        r = 0;
        g = 0;
        b = 0;

        switch ((int) h) {
        case 0:
            r = c;
            g = X;
            break;
        case 1:
            r = X;
            g = c;
            break;
        case 2:
            g = c;
            b = X;
            break;
        case 3:
            g = X;
            b = c;
            break;
        case 4:
            r = X;
            b = c;
            break;
        default:
            r = c;
            b = X;
            break;
        }
    }

    /* Using an alpha channel neatly solves the problem of aligning
     * rows on 4-byte boundaries (at the expense of memory, of
     * course). */
    px[0] = r;
    px[1] = g;
    px[2] = b;
    px[3] = 255;                /* Alpha channel. */
}

void calc_mandel()
{
    int i, j, iter, min, max;
    double x, y, zx, zy, zx2, zy2;
    unsigned short *hsv = malloc(width * height * sizeof(unsigned short));

    min = max_iter;
    max = 0;
    for (i = 0; i < height; i++) {
        y = (i - height / 2) * scale + cy;
        for (j = 0; j < width; j++) {
            x = (j - width / 2) * scale + cx;
            iter = 0;

            zx = hypot(x - .25, y);
            if (x < zx - 2 * zx * zx + .25)
                iter = max_iter;
            if ((x + 1) * (x + 1) + y * y < 1 / 16)
                iter = max_iter;

            zx = 0;
            zy = 0;
            zx2 = 0;
            zy2 = 0;
            while (iter < max_iter && zx2 + zy2 < 4) {
                zy = 2 * zx * zy + y;
                zx = zx2 - zy2 + x;
                zx2 = zx * zx;
                zy2 = zy * zy;
                iter += 1;
            }
            if (iter < min)
                min = iter;
            if (iter > max)
                max = iter;
            hsv[(i * width) + j] = iter;
        }
    }

    for (i = 0; i < height; i += 1) {
        for (j = 0; j < width; j += 1) {
            unsigned char *px = tex + (((i * width) + j) * 4);
            hsv_to_rgba(hsv[(i * width) + j], min, max, px);
        }
    }

    free(hsv);
}

void alloc_tex()
{
    if (tex == NULL || width != old_width || height != old_height) {
        free(tex);
        tex = malloc(height * width * 4 * sizeof(unsigned char));
        memset(tex, 0, height * width * 4 * sizeof(unsigned char));
        old_width = width;
        old_height = height;
    }
}

void set_texture()
{
    alloc_tex();
    calc_mandel();

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
                 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    render();
}

void mouseclick(int button, int state, int x, int y)
{
    if (state != GLUT_UP)
        return;

    cx += (x - width / 2) * scale;
    cy -= (y - height / 2) * scale;

    switch (button) {
    case GLUT_LEFT_BUTTON:     /* zoom in */
        if (scale > fabs((double) x) * 1e-16
            && scale > fabs((double) y) * 1e-16)
            scale /= 2;
        break;
    case GLUT_RIGHT_BUTTON:    /* zoom out */
        scale *= 2;
        break;
        /* any other button recenters */
    }
    set_texture();
}

void resize(int w, int h)
{
    printf("resize %d %d\n", w, h);

    width = w;
    height = h;

    glViewport(0, 0, w, h);
    glOrtho(0, w, 0, h, -1, 1);

    set_texture();
}

void init_gfx(int *c, char **v)
{
    glutInit(c, v);
    glutInitDisplayMode(GLUT_RGBA);
    glutInitWindowSize(640, 480);

    gwin = glutCreateWindow("Mandelbrot");
    glutDisplayFunc(render);

    glutKeyboardFunc(keypress);
    glutMouseFunc(mouseclick);
    glutReshapeFunc(resize);
    glGenTextures(1, &texture);
    set_texture();
}

int main(int c, char **v)
{
    tex = NULL;

    init_gfx(&c, v);
    printf
        ("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t"
         "<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n");

    glutMainLoop();
    return 0;
}

// local variables:
// mode: C
// c-file-style: "k&r"
// c-basic-offset: 4
// end:

generate and draw the Mandelbrot set using various algorithms and functions. The program creates a ppm file directly and features an infinitely zoomable OpenGL program with adjustable colors, max iteration, black and white, screen dump, etc. It is compatible with architectures that allow unaligned pointers and has been tested on x86-64. Despite potential compile warnings, the output will still be produced.


/* using pointer arithmetic (because we can, I guess) */
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;

for (p = arg; p!=end; ++p) {
   sum += *p;
   prod *= *p;
}

Calculate the sum and product of all integers in an array.


#include <stdio.h>

int is_leap_year(unsigned year)
{
    return !(year & (year % 100 ? 3 : 15));
}

int main(void)
{
    const unsigned test_case[] = {
        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100
    };
    const unsigned n = sizeof test_case / sizeof test_case[0];

    for (unsigned i = 0; i != n; ++i) {
        unsigned year = test_case[i];
        printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not ");
    }
    return 0;
}

"Determines if a specified year is a leap year in the Gregorian calendar."


implement the MD5 Message Digest Algorithm directly without using any built-in or external hashing libraries. The key functionality is to produce a correct message digest for an input string. The implementation also handles bit manipulation, unsigned integers, and works with little-endian data. The code includes verification strings and hashes from RFC 1321 for testing purposes. Note that MD5 has been broken and should not be used in applications requiring security.


#include<stdio.h>

int main()
{
	int police,sanitation,fire;

	printf("Police     Sanitation         Fire\n");
	printf("----------------------------------");

	for(police=2;police<=6;police+=2){
		for(sanitation=1;sanitation<=7;sanitation++){
			for(fire=1;fire<=7;fire++){
				if(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){
					printf("\n%d\t\t%d\t\t%d",police,sanitation,fire);
				}
			}
		}
	}

	return 0;
}

Police     Sanitation         Fire
----------------------------------
2               3               7
2               4               6
2               6               4
2               7               3
4               1               7
4               2               6
4               3               5
4               5               3
4               6               2
4               7               1
6               1               5
6               2               4
6               4               2
6               5               1

"Generate all valid combinations of unique numbers between 1 and 7 (inclusive) for three departments - police, sanitation, and fire, such that the sum of these numbers is 12 and the police department number is even."


#include <stdlib.h>	/* exit(), free() */
#include <stdio.h>	/* fputs(), perror(), printf() */
#include <string.h>

int
main()
{
	size_t len;
	char src[] = "Hello";
	char dst1[80], dst2[80];
	char *dst3, *ref;

	/*
	 * Option 1. Use strcpy() from <string.h>.
	 *
	 * DANGER! strcpy() can overflow the destination buffer.
	 * strcpy() is only safe if the source string is shorter than
	 * the destination buffer. We know that "Hello" (6 characters
	 * with the final '\0') easily fits in dst1 (80 characters).
	 */
	strcpy(dst1, src);

	/*
	 * Option 2. Use strlen() and memcpy() from <string.h>, to copy
	 * strlen(src) + 1 bytes including the final '\0'.
	 */
	len = strlen(src);
	if (len >= sizeof dst2) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}
	memcpy(dst2, src, len + 1);

	/*
	 * Option 3. Use strdup() from <string.h>, to allocate a copy.
	 */
	dst3 = strdup(src);
	if (dst3 == NULL) {
		/* Failed to allocate memory! */
		perror("strdup");
		exit(1);
	}

	/* Create another reference to the source string. */
	ref = src;

	/* Modify the source string, not its copies. */
	memset(src, '-', 5);

	printf(" src: %s\n", src);   /*  src: ----- */
	printf("dst1: %s\n", dst1);  /* dst1: Hello */
	printf("dst2: %s\n", dst2);  /* dst2: Hello */
	printf("dst3: %s\n", dst3);  /* dst3: Hello */
	printf(" ref: %s\n", ref);   /*  ref: ----- */

	/* Free memory from strdup(). */
	free(dst3);

	return 0;
}

Library: BSD libc[edit]
#include <stdlib.h>	/* exit() */
#include <stdio.h>	/* fputs(), printf() */
#include <string.h>

int
main()
{
	char src[] = "Hello";
	char dst[80];

	/* Use strlcpy() from <string.h>. */
	if (strlcpy(dst, src, sizeof dst) >= sizeof dst) {
		fputs("The buffer is too small!\n", stderr);
		exit(1);
	}

	memset(src, '-', 5);
	printf("src: %s\n", src);  /* src: ----- */
	printf("dst: %s\n", dst);  /* dst: Hello */

	return 0;
}

Library: Gadget[edit]

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String v, w = "this message is a message";

   Let( v, "Hello world!");
   Print "v = %s\nw = %s\n\n", v,w;

   Get_fn_let( v, Upper(w) );

   Print "v = %s\nw = %s\n\n", v,w;

   Stack{
       Store ( v, Str_tran_last( Upper(w), "MESSAGE", "PROOF" ) );
   }Stack_off;

   Print "v = %s\nw = %s\n\n", v,w;

   Free secure v, w;

End

"Implements a function to copy a string's content, differentiating between copying the content and creating an additional reference to the string, using the Gadget library."


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

/* let us declare our functions; indeed here we need
   really only M declaration, so that F can "see" it
   and the compiler won't complain with a warning */
int F(const int n);
int M(const int n);

int F(const int n)
{
  return (n == 0) ? 1 : n - M(F(n - 1));
}

int M(const int n)
{
  return (n == 0) ? 0 : n - F(M(n - 1));
}

int main(void)
{
  int i;
  for (i = 0; i < 20; i++)
    printf("%2d ", F(i));
  printf("\n");
  for (i = 0; i < 20; i++)
    printf("%2d ", M(i));
  printf("\n");
  return EXIT_SUCCESS;
}

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. The functions are declared explicitly to ensure proper usage.


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

int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));

   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }

   return 0;
}

a
e
f
h
b
d
g
a
b
f
a
i
b
d
d
g
j
a
f
e
a
e
g
e
i
d
j
a
f
e
a

demonstrate how to select a random element from a list.


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

inline int ishex(int x)
{
	return	(x >= '0' && x <= '9')	||
		(x >= 'a' && x <= 'f')	||
		(x >= 'A' && x <= 'F');
}

int decode(const char *s, char *dec)
{
	char *o;
	const char *end = s + strlen(s);
	int c;

	for (o = dec; s <= end; o++) {
		c = *s++;
		if (c == '+') c = ' ';
		else if (c == '%' && (	!ishex(*s++)	||
					!ishex(*s++)	||
					!sscanf(s - 2, "%2x", &c)))
			return -1;

		if (dec) *o = c;
	}

	return o - dec;
}

int main()
{
	const char *url = "http%3A%2F%2ffoo+bar%2fabcd";
	char out[strlen(url) + 1];

	printf("length: %d\n", decode(url, 0));
	puts(decode(url, out) < 0 ? "bad string" : out);

	return 0;
}

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


#include <stdio.h>

int bsearch (int *a, int n, int x) {
    int i = 0, j = n - 1;
    while (i <= j) {
        int k = i + ((j - i) / 2);
        if (a[k] == x) {
            return k;
        }
        else if (a[k] < x) {
            i = k + 1;
        }
        else {
            j = k - 1;
        }
    }
    return -1;
}

int bsearch_r (int *a, int x, int i, int j) {
    if (j < i) {
        return -1;
    }
    int k = i + ((j - i) / 2);
    if (a[k] == x) {
        return k;
    }
    else if (a[k] < x) {
        return bsearch_r(a, x, k + 1, j);
    }
    else {
        return bsearch_r(a, x, i, k - 1);
    }
}

int main () {
    int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
    int n = sizeof a / sizeof a[0];
    int x = 2;
    int i = bsearch(a, n, x);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    x = 5;
    i = bsearch_r(a, x, 0, n - 1);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    return 0;
}

The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a "secret value" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.


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

int main(int argc, char* argv[])
{
  int i;
  (void) printf("This program is named %s.\n", argv[0]);
  for (i = 1; i < argc; ++i)
    (void) printf("the argument #%d is %s\n", i, argv[i]);
  return EXIT_SUCCESS;
}

The code retrieves the list of command-line arguments provided to the program and prints them. It also takes into account the program name as an argument. The argument count and argument strings are conventionally named as argc and argv respectively. The code is also capable of handling systems that use Unicode or other multibyte character sets by using a type of _wchar* and multi-byte-character-set-aware versions of printf.


Library: GLUT
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>

#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;

double elappsed() {
	struct timeval now;
	gettimeofday(&now, 0);
	int ret = (now.tv_sec - tv.tv_sec) * 1000000
		+ now.tv_usec - tv.tv_usec;
	tv = now;
	return ret / 1.e6;
}

void resize(int w, int h)
{
	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glOrtho(0, w, h, 0, -1, 1);
}

void render()
{
	double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
	resize(640, 320);
 	glClear(GL_COLOR_BUFFER_BIT);

	glBegin(GL_LINES);
	glVertex2d(320, 0);
	glVertex2d(x, y);
	glEnd();
	glFlush();

	double us = elappsed();
	alpha += (omega + us * accl / 2) * us;
	omega += accl * us;

	/* don't let precision error go out of hand */
	if (length * g * (1 - cos(alpha)) >= E) {
		alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
		omega = 0;
	}
	accl = -g / length * sin(alpha);
}

void init_gfx(int *c, char **v)
{
	glutInit(c, v);
	glutInitDisplayMode(GLUT_RGB);
	glutInitWindowSize(640, 320);
	glutIdleFunc(render);
	glutCreateWindow("Pendulum");
}

int main(int c, char **v)
{
	alpha = 4 * atan2(1, 1) / 2.1;
	E = length * g * (1 - cos(alpha));

	accl = -g / length * sin(alpha);
	omega = 0;

	gettimeofday(&tv, 0);
	init_gfx(&c, v);
	glutMainLoop();
	return 0;
}

create and animate a simple physical model of a gravity pendulum.


Library: YAJL
Works with: YAJL version 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>

static void print_callback (void *ctx, const char *str, size_t len)
{
  FILE *f = (FILE *) ctx;
  fwrite (str, 1, len, f);
}

static void check_status (yajl_gen_status status)
{
  if (status != yajl_gen_status_ok)
    {
      fprintf (stderr, "yajl_gen_status was %d\n", (int) status);
      exit (EXIT_FAILURE);
    }
}

static void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)
{
  size_t i;

  switch (val->type)
    {
    case yajl_t_string:
      check_status (yajl_gen_string (gen,
                                     (const unsigned char *) val->u.string,
                                     strlen (val->u.string)));
      break;
    case yajl_t_number:
      if (parse_numbers  &&  YAJL_IS_INTEGER (val))
        check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));
      else if (parse_numbers  &&  YAJL_IS_DOUBLE (val))
        check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));
      else
        check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),
                                       strlen (YAJL_GET_NUMBER (val))));
      break;
    case yajl_t_object:
      check_status (yajl_gen_map_open (gen));
      for (i = 0  ;  i < val->u.object.len  ;  i++)
        {
          check_status (yajl_gen_string (gen,
                                         (const unsigned char *) val->u.object.keys[i],
                                         strlen (val->u.object.keys[i])));
          serialize_value (gen, val->u.object.values[i], parse_numbers);
        }
      check_status (yajl_gen_map_close (gen));
      break;
    case yajl_t_array:
      check_status (yajl_gen_array_open (gen));
      for (i = 0  ;  i < val->u.array.len  ;  i++)
        serialize_value (gen, val->u.array.values[i], parse_numbers);
      check_status (yajl_gen_array_close (gen));
      break;
    case yajl_t_true:
      check_status (yajl_gen_bool (gen, 1));
      break;
    case yajl_t_false:
      check_status (yajl_gen_bool (gen, 0));
      break;
    case yajl_t_null:
      check_status (yajl_gen_null (gen));
      break;
    default:
      fprintf (stderr, "unexpectedly got type %d\n", (int) val->type);
      exit (EXIT_FAILURE);
    }
}

static void print_tree (FILE *f, yajl_val tree, int parse_numbers)
{
  yajl_gen gen;

  gen = yajl_gen_alloc (NULL);
  if (! gen)
    {
      fprintf (stderr, "yajl_gen_alloc failed\n");
      exit (EXIT_FAILURE);
    }

  if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1)  ||
      0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1)  ||
      0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))
    {
      fprintf (stderr, "yajl_gen_config failed\n");
      exit (EXIT_FAILURE);
    }

  serialize_value (gen, tree, parse_numbers);
  yajl_gen_free (gen);
}

int main (int argc, char **argv)
{
  char err_buf[200];
  const char *json =
    "{\"pi\": 3.14, \"large number\": 123456789123456789123456789, "
    "\"an array\": [-1, true, false, null, \"foo\"]}";
  yajl_val tree;

  tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));
  if (! tree)
    {
      fprintf (stderr, "parsing failed because: %s\n", err_buf);
      return EXIT_FAILURE;
    }

  printf ("Treating numbers as strings...\n");
  print_tree (stdout, tree, 0);
  printf ("Parsing numbers to long long or double...\n");
  print_tree (stdout, tree, 1);

  yajl_tree_free (tree);

  return EXIT_SUCCESS;
}

"Code loads a JSON string into a data structure, creates a new data structure and serializes it into JSON using objects and arrays. It also reads a JSON snippet into YAJL's tree format, walks the tree and prints it back out, handling numbers in both unparsed string form and converted to long long or double."


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

double pow_ (double x, int e) {
    int i;
    double r = 1;
    for (i = 0; i < e; i++) {
        r *= x;
    }
    return r;
}

double root (int n, double x) {
    double d, r = 1;
    if (!x) {
        return 0;
    }
    if (n < 1 || (x < 0 && !(n&1))) {
        return 0.0 / 0.0; /* NaN */
    }
    do {
        d = (x / pow_(r, n - 1) - r) / n;
        r += d;
    }
    while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10);
    return r;
}

int main () {
    int n = 15;
    double x = pow_(-3.14159, 15);
    printf("root(%d, %g) = %g\n", n, x, root(n, x));
    return 0;
}

implement the principal nth root of a positive real number A without using the math library.


#include<stdio.h>

void leonardo(int a,int b,int step,int num){

	int i,temp;

	printf("First 25 Leonardo numbers : \n");

	for(i=1;i<=num;i++){
		if(i==1)
			printf(" %d",a);
		else if(i==2)
			printf(" %d",b);
		else{
			printf(" %d",a+b+step);
			temp = a;
			a = b;
			b = temp+b+step;
		}
	}
}

int main()
{
	int a,b,step;

	printf("Enter first two Leonardo numbers and increment step : ");

	scanf("%d%d%d",&a,&b,&step);

	leonardo(a,b,step,25);

	return 0;
}

Enter first two Leonardo numbers and increment step : 1 1 1
First 25 Leonardo numbers :
 1 1 3 5 9 15 25 41 67 109 177 287 465 753 1219 1973 3193 5167 8361 13529 21891 35421 57313 92735 150049

Enter first two Leonardo numbers and increment step : 0 1 0
First 25 Leonardo numbers :
 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368

generate the first 25 Leonardo numbers starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. It also provides an option to generate the Fibonacci series by setting 0 and 1 for L(0) and L(1), and 0 for the add number. The implementation adheres to the task requirements of specifying the first two terms and the step increment.


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

jmp_buf ctx;
const char *msg;

enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };

typedef struct expr_t *expr, expr_t;
struct expr_t {
	int op, val, used;
	expr left, right;
};

#define N_DIGITS 4
expr_t digits[N_DIGITS];

void gen_digits()
{
	int i;
	for (i = 0; i < N_DIGITS; i++)
		digits[i].val = 1 + rand() % 9;
}

#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;

#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;

void reset()
{
	int i;
	msg = 0;
	pool_ptr = pos = 0;
	for (i = 0; i < POOL_SIZE; i++) {
		pool[i].op = OP_NONE;
		pool[i].left = pool[i].right = 0;
	}
	for (i = 0; i < N_DIGITS; i++)
		digits[i].used = 0;
}

/* longish jumpish back to input cycle */
void bail(const char *s)
{
	msg = s;
	longjmp(ctx, 1);
}

expr new_expr()
{
	if (pool_ptr < POOL_SIZE)
		return pool + pool_ptr++;
	return 0;
}

/* check next input char */
int next_tok()
{
	while (isspace(str[pos])) pos++;
	return str[pos];
}

/* move input pointer forward */
int take()
{
	if (str[pos] != '\0') return ++pos;
	return 0;
}

/* BNF(ish)
expr = term { ("+")|("-") term }
term = fact { ("*")|("/") expr }
fact =	number
	| '(' expr ')'
*/

expr get_fact();
expr get_term();
expr get_expr();

expr get_expr()
{
	int c;
	expr l, r, ret;
	if (!(ret = get_term())) bail("Expected term");
	while ((c = next_tok()) == '+' || c == '-') {
		if (!take()) bail("Unexpected end of input");
		if (!(r = get_term())) bail("Expected term");

		l = ret;
		ret = new_expr();
		ret->op = (c == '+') ? OP_ADD : OP_SUB;
		ret->left = l;
		ret->right = r;
	}
	return ret;
}

expr get_term()
{
	int c;
	expr l, r, ret;
	ret = get_fact();
	while((c = next_tok()) == '*' || c == '/') {
		if (!take()) bail("Unexpected end of input");

		r = get_fact();
		l = ret;
		ret = new_expr();
		ret->op = (c == '*') ? OP_MUL : OP_DIV;
		ret->left = l;
		ret->right = r;
	}
	return ret;
}

expr get_digit()
{
	int i, c = next_tok();
	expr ret;
	if (c >= '0' && c <= '9') {
		take();
		ret = new_expr();
		ret->op = OP_NUM;
		ret->val = c - '0';
		for (i = 0; i < N_DIGITS; i++)
			if (digits[i].val == ret->val && !digits[i].used) {
				digits[i].used = 1;
				return ret;
			}
		bail("Invalid digit");
	}
	return 0;
}

expr get_fact()
{
	int c;
	expr l = get_digit();
	if (l) return l;
	if ((c = next_tok()) == '(') {
		take();
		l = get_expr();
		if (next_tok() != ')') bail("Unbalanced parens");
		take();
		return l;
	}
	return 0;
}

expr parse()
{
	int i;
	expr ret = get_expr();
	if (next_tok() != '\0')
		bail("Trailing garbage");
	for (i = 0; i < N_DIGITS; i++)
		if (!digits[i].used)
			bail("Not all digits are used");
	return ret;
}

typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };

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

/* evaluate expression tree.  result in fraction form */
void eval_tree(expr e, frac res)
{
	frac_t l, r;
	int t;
	if (e->op == OP_NUM) {
		res->num = e->val;
		res->denom = 1;
		return;
	}

	eval_tree(e->left, &l);
	eval_tree(e->right, &r);

	switch(e->op) {
	case OP_ADD:
		res->num = l.num * r.denom + l.denom * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_SUB:
		res->num = l.num * r.denom - l.denom * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_MUL:
		res->num = l.num * r.num;
		res->denom = l.denom * r.denom;
		break;
	case OP_DIV:
		res->num = l.num * r.denom;
		res->denom = l.denom * r.num;
		break;
	}
	if ((t = gcd(res->denom, res->num))) {
		res->denom /= t;
		res->num /= t;
	}
}

void get_input()
{
	int i;
reinput:
	reset();
	printf("\nAvailable digits are:");
	for (i = 0; i < N_DIGITS; i++)
		printf(" %d", digits[i].val);
	printf(". Type an expression and I'll check it for you, or make new numbers.\n"
		"Your choice? [Expr/n/q] ");

	while (1) {
		for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
		fgets(str, MAX_INPUT, stdin);
		if (*str == '\0') goto reinput;
		if (str[MAX_INPUT - 1] != '\n')
			bail("string too long");

		for (i = 0; i < MAX_INPUT; i++)
			if (str[i] == '\n') str[i] = '\0';
		if (str[0] == 'q') {
			printf("Bye\n");
			exit(0);
		}
		if (str[0] == 'n') {
			gen_digits();
			goto reinput;
		}
		return;
	}
}

int main()
{
	frac_t f;
	srand(time(0));

	gen_digits();
	while(1) {
		get_input();
		setjmp(ctx); /* if parse error, jump back here with err msg set */
		if (msg) {
			/* after error jump; announce, reset, redo */
			printf("%s at '%.*s'\n", msg, pos, str);
			continue;
		}

		eval_tree(parse(), &f);

		if (f.denom == 0) bail("Divide by zero");
		if (f.denom == 1 && f.num == 24)
			printf("You got 24.  Very good.\n");
		else {
			if (f.denom == 1)
				printf("Eval to: %d, ", f.num);
			else
				printf("Eval to: %d/%d, ", f.num, f.denom);
			printf("no good.  Try again.\n");
		}
	}
	return 0;
}

The code is a game program that randomly selects and displays four digits (1-9). It prompts the player to create an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using addition, subtraction, multiplication, and division. The code checks and evaluates the player's input expression. It uses either floating point or rational arithmetic for division to maintain remainders. It allows brackets in infix expressions but does not allow forming multi-digit numbers from the given digits. The code does not generate the expression or check its feasibility. It may use any type of expression evaluator, including an RPN evaluator.


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

typedef struct stream_t stream_t, *stream;
struct stream_t {
	/* get function is supposed to return a byte value (0-255),
		or -1 to signify end of input */
	int (*get)(stream);
	/* put function does output, one byte at a time */
	int (*put)(stream, int);
};

/* next two structs inherit from stream_t */
typedef struct {
	int (*get)(stream);
	int (*put)(stream, int);
	char *string;
	int pos;
} string_stream;

typedef struct {
	int (*get)(stream);
	int (*put)(stream, int);
	FILE *fp;
} file_stream;

/* methods for above streams */
int sget(stream in)
{
	int c;
	string_stream* s = (string_stream*) in;
	c = (unsigned char)(s->string[s->pos]);
	if (c == '\0') return -1;
	s->pos++;
	return c;
}

int sput(stream out, int c)
{
	string_stream* s = (string_stream*) out;
	s->string[s->pos++] = (c == -1) ? '\0' : c;
	if (c == -1) s->pos = 0;
	return 0;
}

int file_put(stream out, int c)
{
	file_stream *f = (file_stream*) out;
	return fputc(c, f->fp);
}

/* helper function */
void output(stream out, unsigned char* buf, int len)
{
	int i;
	out->put(out, 128 + len);
	for (i = 0; i < len; i++)
		out->put(out, buf[i]);
}

/* Specification: encoded stream are unsigned bytes consisting of sequences.
 * First byte of each sequence is the length, followed by a number of bytes.
 * If length <=128, the next byte is to be repeated length times;
 * If length > 128, the next (length - 128) bytes are not repeated.
 * this is to improve efficiency for long non-repeating sequences.
 * This scheme can encode arbitrary byte values efficiently.
 * c.f. Adobe PDF spec RLE stream encoding (not exactly the same)
 */
void encode(stream in, stream out)
{
	unsigned char buf[256];
	int len = 0, repeat = 0, end = 0, c;
	int (*get)(stream) = in->get;
	int (*put)(stream, int) = out->put;

	while (!end) {
		end = ((c = get(in)) == -1);
		if (!end) {
			buf[len++] = c;
			if (len <= 1) continue;
		}

		if (repeat) {
			if (buf[len - 1] != buf[len - 2])
				repeat = 0;
			if (!repeat || len == 129 || end) {
				/* write out repeating bytes */
				put(out, end ? len : len - 1);
				put(out, buf[0]);
				buf[0] = buf[len - 1];
				len = 1;
			}
		} else {
			if (buf[len - 1] == buf[len - 2]) {
				repeat = 1;
				if (len > 2) {
					output(out, buf, len - 2);
					buf[0] = buf[1] = buf[len - 1];
					len = 2;
				}
				continue;
			}
			if (len == 128 || end) {
				output(out, buf, len);
				len = 0;
				repeat = 0;
			}
		}
	}
	put(out, -1);
}

void decode(stream in, stream out)
{
	int c, i, cnt;
	while (1) {
		c = in->get(in);
		if (c == -1) return;
		if (c > 128) {
			cnt = c - 128;
			for (i = 0; i < cnt; i++)
				out->put(out, in->get(in));
		} else {
			cnt = c;
			c = in->get(in);
			for (i = 0; i < cnt; i++)
				out->put(out, c);
		}
	}
}

int main()
{
	char buf[256];
	string_stream str_in = { sget, 0,
		"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", 0};
	string_stream str_out = { sget, sput, buf, 0 };
	file_stream file = { 0, file_put, stdout };

	/* encode from str_in to str_out */
	encode((stream)&str_in, (stream)&str_out);

	/* decode from str_out to file (stdout) */
	decode((stream)&str_out, (stream)&file);

	return 0;
}

implement a run-length encoding and decoding system. It compresses strings of uppercase characters by storing the length of consecutive identical characters. The system can recreate the original string from the compressed version. It also includes an encoder for handling byte streams of any length and value with efficiency, demonstrating object-oriented programming and polymorphism with structs.


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

char *sconcat(const char *s1, const char *s2)
{
  char *s0 = malloc(strlen(s1)+strlen(s2)+1);
  strcpy(s0, s1);
  strcat(s0, s2);
  return s0;
}

int main()
{
   const char *s = "hello";
   char *s2;

   printf("%s literal\n", s);
   /* or */
   printf("%s%s\n", s, " literal");

   s2 = sconcat(s, " literal");
   puts(s2);
   free(s2);
}

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


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

char rfc3986[256] = {0};
char html5[256] = {0};

/* caller responsible for memory */
void encode(const char *s, char *enc, char *tb)
{
	for (; *s; s++) {
		if (tb[*s]) sprintf(enc, "%c", tb[*s]);
		else        sprintf(enc, "%%%02X", *s);
		while (*++enc);
	}
}

int main()
{
	const char url[] = "http://foo bar/";
	char enc[(strlen(url) * 3) + 1];

	int i;
	for (i = 0; i < 256; i++) {
		rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'
			? i : 0;
		html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'
			? i : (i == ' ') ? '+' : 0;
	}

	encode(url, enc, rfc3986);
	puts(enc);

	return 0;
}

provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, "http://foo bar/" is encoded as "http%3A%2F%2Ffoo%20bar%2F".


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

#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int icompare(const void* p1, const void* p2) {
    const int* ip1 = p1;
    const int* ip2 = p2;
    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);
}

size_t unique(int* array, size_t len) {
    size_t out_index = 0;
    int prev;
    for (size_t i = 0; i < len; ++i) {
        if (i == 0 || prev != array[i])
            array[out_index++] = array[i];
        prev = array[i];
    }
    return out_index;
}

int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {
    size_t len = 0;
    for (size_t i = 0; i < count; ++i)
        len += lengths[i];
    int* array = xmalloc(len * sizeof(int));
    for (size_t i = 0, offset = 0; i < count; ++i) {
        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));
        offset += lengths[i];
    }
    qsort(array, len, sizeof(int), icompare);
    *size = unique(array, len);
    return array;
}

void print(const int* array, size_t len) {
    printf("[");
    for (size_t i = 0; i < len; ++i) {
        if (i > 0)
            printf(", ");
        printf("%d", array[i]);
    }
    printf("]\n");
}

int main() {
    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};
    const int b[] = {3, 5, 9, 8, 4};
    const int c[] = {1, 3, 7, 9};
    size_t len = 0;
    const int* arrays[] = {a, b, c};
    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};
    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);
    print(sorted, len);
    free(sorted);
    return 0;
}

generates a common sorted list with unique elements from multiple integer arrays.


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

struct item { double w, v; const char *name; } items[] = {
	{ 3.8, 36, "beef" },
	{ 5.4, 43, "pork" },
	{ 3.6, 90, "ham" },
	{ 2.4, 45, "greaves" },
	{ 4.0, 30, "flitch" },
	{ 2.5, 56, "brawn" },
	{ 3.7, 67, "welt" },
	{ 3.0, 95, "salami" },
	{ 5.9, 98, "sausage" },
};

int item_cmp(const void *aa, const void *bb)
{
	const struct item *a = aa, *b = bb;
	double ua = a->v / a->w, ub = b->v / b->w;
	return ua < ub ? -1 : ua > ub;
}

int main()
{
	struct item *it;
	double space = 15;

	qsort(items, 9, sizeof(struct item), item_cmp);
	for (it = items + 9; it---items && space > 0; space -= it->w)
		if (space >= it->w)
			printf("take all %s\n", it->name);
		else
			printf("take %gkg of %g kg of %s\n",
				space, it->w, it->name);

	return 0;
}
outputtake all salami
take all ham
take all brawn
take all greaves
take 3.5kg of 3.7 kg of welt

determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.


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

char *sortedWord(const char *word, char *wbuf)
{
    char *p1, *p2, *endwrd;
    char t;
    int swaps;

    strcpy(wbuf, word);
    endwrd = wbuf+strlen(wbuf);
    do {
       swaps = 0;
       p1 = wbuf; p2 = endwrd-1;
       while (p1<p2) {
          if (*p2 > *p1) {
             t = *p2; *p2 = *p1; *p1 = t;
             swaps = 1;
          }
          p1++; p2--;
       }
       p1 = wbuf; p2 = p1+1;
       while(p2 < endwrd) {
           if (*p2 > *p1) {
             t = *p2; *p2 = *p1; *p1 = t;
             swaps = 1;
           }
           p1++; p2++;
       }
    } while (swaps);
    return wbuf;
}

static
short cxmap[] = {
    0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,
    0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,
    0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,
    0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,
    0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,
    0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,
    0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,
    0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,
   };
#define CXMAP_SIZE (sizeof(cxmap)/sizeof(short))

int Str_Hash( const char *key, int ix_max )
{
   const char *cp;
   short mash;
   int  hash = 33501551;
   for (cp = key; *cp; cp++) {
      mash = cxmap[*cp % CXMAP_SIZE];
      hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));
      hash &= 0x3FFFFFFF;
      }
   return  hash % ix_max;
}

typedef struct sDictWord  *DictWord;
struct sDictWord {
    const char *word;
    DictWord next;
};

typedef struct sHashEntry *HashEntry;
struct sHashEntry {
    const char *key;
    HashEntry next;
    DictWord  words;
    HashEntry link;
    short wordCount;
};

#define HT_SIZE 8192

HashEntry hashTable[HT_SIZE];

HashEntry mostPerms = NULL;

int buildAnagrams( FILE *fin )
{
    char buffer[40];
    char bufr2[40];
    char *hkey;
    int hix;
    HashEntry he, *hep;
    DictWord  we;
    int  maxPC = 2;
    int numWords = 0;

    while ( fgets(buffer, 40, fin)) {
        for(hkey = buffer; *hkey && (*hkey!='\n'); hkey++);
        *hkey = 0;
        hkey = sortedWord(buffer, bufr2);
        hix = Str_Hash(hkey, HT_SIZE);
        he = hashTable[hix]; hep = &hashTable[hix];
        while( he && strcmp(he->key , hkey) ) {
            hep = &he->next;
            he = he->next;
        }
        if ( ! he ) {
            he = malloc(sizeof(struct sHashEntry));
            he->next = NULL;
            he->key = strdup(hkey);
            he->wordCount = 0;
            he->words = NULL;
            he->link = NULL;
            *hep = he;
        }
        we = malloc(sizeof(struct sDictWord));
        we->word = strdup(buffer);
        we->next = he->words;
        he->words = we;
        he->wordCount++;
        if ( maxPC < he->wordCount) {
            maxPC = he->wordCount;
            mostPerms = he;
            he->link = NULL;
        }
        else if (maxPC == he->wordCount) {
            he->link = mostPerms;
            mostPerms = he;
        }

        numWords++;
    }
    printf("%d words in dictionary max ana=%d\n", numWords, maxPC);
    return maxPC;
}

int main( )
{
    HashEntry he;
    DictWord  we;
    FILE *f1;

    f1 = fopen("unixdict.txt","r");
    buildAnagrams(f1);
    fclose(f1);

    f1 = fopen("anaout.txt","w");
//    f1 = stdout;

    for (he = mostPerms; he; he = he->link) {
        fprintf(f1,"%d:", he->wordCount);
        for(we = he->words; we; we = we->next) {
            fprintf(f1,"%s, ", we->word);
        }
        fprintf(f1, "\n");
    }

    fclose(f1);
    return 0;
}

Find the largest sets of anagrams using the word list from a given URL.


#include <stdio.h>

int main()
{
	int i, j, dim, d;
	int depth = 3;

	for (i = 0, dim = 1; i < depth; i++, dim *= 3);

	for (i = 0; i < dim; i++) {
		for (j = 0; j < dim; j++) {
			for (d = dim / 3; d; d /= 3)
				if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
					break;
			printf(d ? "  " : "##");
		}
		printf("\n");
	}

	return 0;
}

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

typedef struct sCarpet {
    int dim;      // dimension
    char *data;   // character data
    char **rows;  // pointers to data rows
} *Carpet;

/* Clones a tile into larger carpet, or blank if center */
void TileCarpet( Carpet d, int r, int c, Carpet tile )
{
    int y0 = tile->dim*r;
    int x0 = tile->dim*c;
    int k,m;

    if ((r==1) && (c==1)) {
        for(k=0; k < tile->dim; k++) {
           for (m=0; m < tile->dim; m++) {
               d->rows[y0+k][x0+m] = ' ';
           }
        }
    }
    else {
        for(k=0; k < tile->dim; k++) {
           for (m=0; m < tile->dim; m++) {
               d->rows[y0+k][x0+m] = tile->rows[k][m];
           }
        }
    }
}

/* define a 1x1 starting carpet */
static char s1[]= "#";
static char *r1[] = {s1};
static struct sCarpet single = { 1, s1, r1};

Carpet Sierpinski( int n )
{
   Carpet carpet;
   Carpet subCarpet;
   int row,col, rb;
   int spc_rqrd;

   subCarpet = (n > 1) ? Sierpinski(n-1) : &single;

   carpet = malloc(sizeof(struct sCarpet));
   carpet->dim = 3*subCarpet->dim;
   spc_rqrd = (2*subCarpet->dim) * (carpet->dim);
   carpet->data = malloc(spc_rqrd*sizeof(char));
   carpet->rows = malloc( carpet->dim*sizeof(char *));
   for (row=0; row<subCarpet->dim; row++) {
       carpet->rows[row] = carpet->data + row*carpet->dim;
       rb = row+subCarpet->dim;
       carpet->rows[rb] = carpet->data + rb*carpet->dim;
       rb = row+2*subCarpet->dim;
       carpet->rows[rb] = carpet->data + row*carpet->dim;
   }

    for (col=0; col < 3; col++) {
      /* 2 rows of tiles to copy - third group points to same data a first */
      for (row=0; row < 2; row++)
         TileCarpet( carpet, row, col, subCarpet );
    }
    if (subCarpet != &single ) {
       free(subCarpet->rows);
       free(subCarpet->data);
       free(subCarpet);
    }

    return carpet;
}

void CarpetPrint( FILE *fout, Carpet carp)
{
    char obuf[730];
    int row;
    for (row=0; row < carp->dim; row++) {
       strncpy(obuf, carp->rows[row], carp->dim);
       fprintf(fout, "%s\n", obuf);
    }
    fprintf(fout,"\n");
}

int main(int argc, char *argv[])
{
//    FILE *f = fopen("sierp.txt","w");
    CarpetPrint(stdout, Sierpinski(3));
//    fclose(f);
    return 0;
}

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

typedef struct _PartialGrid{
        char** base;
        int xbegin, xend, ybegin, yend; // yend strictly not used
} PartialGrid;

void sierpinski_hollow(PartialGrid G){
        int len = G.xend - G.xbegin+1;
        int unit = len/3;
        for(int i = G.xbegin+unit; i <G.xbegin+2*unit;i++){
        for(int j = G.ybegin+unit; j <G.ybegin+2*unit;j++){
                G.base[j][i] = ' ';
        }}
}

void sierpinski(PartialGrid G, int iterations){
        if(iterations==0)
                return;
        if((iterations)==1){
                sierpinski_hollow(G);
                sierpinski(G,0);
        }
        sierpinski_hollow(G);
        for(int i=0;i<3;i++){
                for(int j=0;j<3;j++){
                        int length = G.xend-G.xbegin+1;
                        int unit = length/3;
                        PartialGrid q = {G.base, G.xbegin + i*unit, G.xbegin+(i+1)*unit-1,
                                G.ybegin+j*unit, G.ybegin+(j+1)*unit-1};
                        sierpinski(q, iterations-1);
                }
        }
}

int intpow(int base, int expo){
        if(expo==0){
                return 1;
        }
        return base*intpow(base,expo-1);
}

int allocate_grid(char*** g, int n, const char sep){
        int size = intpow(3,n+1);
        *g = (char**)calloc(size, sizeof(char*));
        if(*g==NULL)
                return -1;

        for(int i = 0; i < size; ++i){
                (*g)[i] = (char*)calloc(size, sizeof(char));
                if((*g)[i] == NULL)
                        return -1;
                for(int j = 0; j < size; j++){
                        (*g)[i][j] = sep;
                }
        }

        return size;
}

void print_grid(char** b, int size){
        for(int i = 0; i < size; i++){
                printf("%s\n",b[i]);
        }
}

int main(){
        int n = 3;

        char** basegrid;
        int size = allocate_grid(&basegrid, n, '#');
        if(size == -1)
                return 1; //bad alloc
        PartialGrid b = {basegrid, 0, size-1, 0, size-1};
        sierpinski(b, n);
        print_grid(basegrid, size);
        free(basegrid);

        return 0;
}

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order. The carpet is constructed based on the placement of whitespace and non-whitespace characters. The pixel is blank if any matching pair of digits in base 3 coordinates of a point are (1, 1). The code also includes a recursive version of the task.


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

#define BYTES 256

struct huffcode {
  int nbits;
  int code;
};
typedef struct huffcode huffcode_t;

struct huffheap {
  int *h;
  int n, s, cs;
  long *f;
};
typedef struct huffheap heap_t;

/* heap handling funcs */
static heap_t *_heap_create(int s, long *f)
{
  heap_t *h;
  h = malloc(sizeof(heap_t));
  h->h = malloc(sizeof(int)*s);
  h->s = h->cs = s;
  h->n = 0;
  h->f = f;
  return h;
}

static void _heap_destroy(heap_t *heap)
{
  free(heap->h);
  free(heap);
}

#define swap_(I,J) do { int t_; t_ = a[(I)];	\
      a[(I)] = a[(J)]; a[(J)] = t_; } while(0)
static void _heap_sort(heap_t *heap)
{
  int i=1, j=2; /* gnome sort */
  int *a = heap->h;

  while(i < heap->n) { /* smaller values are kept at the end */
    if ( heap->f[a[i-1]] >= heap->f[a[i]] ) {
      i = j; j++;
    } else {
      swap_(i-1, i);
      i--;
      i = (i==0) ? j++ : i;
    }
  }
}
#undef swap_

static void _heap_add(heap_t *heap, int c)
{
  if ( (heap->n + 1) > heap->s ) {
    heap->h = realloc(heap->h, heap->s + heap->cs);
    heap->s += heap->cs;
  }
  heap->h[heap->n] = c;
  heap->n++;
  _heap_sort(heap);
}

static int _heap_remove(heap_t *heap)
{
  if ( heap->n > 0 ) {
    heap->n--;
    return heap->h[heap->n];
  }
  return -1;
}

/* huffmann code generator */
huffcode_t **create_huffman_codes(long *freqs)
{
  huffcode_t **codes;
  heap_t *heap;
  long efreqs[BYTES*2];
  int preds[BYTES*2];
  int i, extf=BYTES;
  int r1, r2;

  memcpy(efreqs, freqs, sizeof(long)*BYTES);
  memset(&efreqs[BYTES], 0, sizeof(long)*BYTES);

  heap = _heap_create(BYTES*2, efreqs);
  if ( heap == NULL ) return NULL;

  for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i);

  while( heap->n > 1 )
  {
    r1 = _heap_remove(heap);
    r2 = _heap_remove(heap);
    efreqs[extf] = efreqs[r1] + efreqs[r2];
    _heap_add(heap, extf);
    preds[r1] = extf;
    preds[r2] = -extf;
    extf++;
  }
  r1 = _heap_remove(heap);
  preds[r1] = r1;
  _heap_destroy(heap);

  codes = malloc(sizeof(huffcode_t *)*BYTES);

  int bc, bn, ix;
  for(i=0; i < BYTES; i++) {
    bc=0; bn=0;
    if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; }
    ix = i;
    while( abs(preds[ix]) != ix ) {
      bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn;
      ix = abs(preds[ix]);
      bn++;
    }
    codes[i] = malloc(sizeof(huffcode_t));
    codes[i]->nbits = bn;
    codes[i]->code = bc;
  }
  return codes;
}

void free_huffman_codes(huffcode_t **c)
{
  int i;

  for(i=0; i < BYTES; i++) free(c[i]);
  free(c);
}

#define MAXBITSPERCODE 100

void inttobits(int c, int n, char *s)
{
  s[n] = 0;
  while(n > 0) {
    s[n-1] = (c%2) + '0';
    c >>= 1; n--;
  }
}

const char *test = "this is an example for huffman encoding";

int main()
{
  huffcode_t **r;
  int i;
  char strbit[MAXBITSPERCODE];
  const char *p;
  long freqs[BYTES];

  memset(freqs, 0, sizeof freqs);

  p = test;
  while(*p != '\0') freqs[*p++]++;

  r = create_huffman_codes(freqs);

  for(i=0; i < BYTES; i++) {
    if ( r[i] != NULL ) {
      inttobits(r[i]->code, r[i]->nbits, strbit);
      printf("%c (%d) %s\n", i, r[i]->code, strbit);
    }
  }

  free_huffman_codes(r);

  return 0;
}

Alternative[edit]

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

typedef struct node_t {
	struct node_t *left, *right;
	int freq;
	char c;
} *node;

struct node_t pool[256] = {{0}};
node qqq[255], *q = qqq - 1;
int n_nodes = 0, qend = 1;
char *code[128] = {0}, buf[1024];

node new_node(int freq, char c, node a, node b)
{
	node n = pool + n_nodes++;
	if (freq) n->c = c, n->freq = freq;
	else {
		n->left = a, n->right = b;
		n->freq = a->freq + b->freq;
	}
	return n;
}

/* priority queue */
void qinsert(node n)
{
	int j, i = qend++;
	while ((j = i / 2)) {
		if (q[j]->freq <= n->freq) break;
		q[i] = q[j], i = j;
	}
	q[i] = n;
}

node qremove()
{
	int i, l;
	node n = q[i = 1];

	if (qend < 2) return 0;
	qend--;
	while ((l = i * 2) < qend) {
		if (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;
		q[i] = q[l], i = l;
	}
	q[i] = q[qend];
	return n;
}

/* walk the tree and put 0s and 1s */
void build_code(node n, char *s, int len)
{
	static char *out = buf;
	if (n->c) {
		s[len] = 0;
		strcpy(out, s);
		code[n->c] = out;
		out += len + 1;
		return;
	}

	s[len] = '0'; build_code(n->left,  s, len + 1);
	s[len] = '1'; build_code(n->right, s, len + 1);
}

void init(const char *s)
{
	int i, freq[128] = {0};
	char c[16];

	while (*s) freq[(int)*s++]++;

	for (i = 0; i < 128; i++)
		if (freq[i]) qinsert(new_node(freq[i], i, 0, 0));

	while (qend > 2)
		qinsert(new_node(0, 0, qremove(), qremove()));

	build_code(q[1], c, 0);
}

void encode(const char *s, char *out)
{
	while (*s) {
		strcpy(out, code[*s]);
		out += strlen(code[*s++]);
	}
}

void decode(const char *s, node t)
{
	node n = t;
	while (*s) {
		if (*s++ == '0') n = n->left;
		else n = n->right;

		if (n->c) putchar(n->c), n = t;
	}

	putchar('\n');
	if (t != n) printf("garbage input\n");
}

int main(void)
{
	int i;
	const char *str = "this is an example for huffman encoding";
        char buf[1024];

	init(str);
	for (i = 0; i < 128; i++)
		if (code[i]) printf("'%c': %s\n", i, code[i]);

	encode(str, buf);
	printf("encoded: %s\n", buf);

	printf("decoded: ");
	decode(buf, q[1]);

	return 0;
}

The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character, with more frequent characters having fewer bits in their encoding. It uses a heap-based priority queue to manage the nodes and constructs the binary tree by removing the nodes with the highest priority (lowest probability). The code then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf form the Huffman encoding for the corresponding character. The code outputs a table of Huffman encodings for each character.


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

const gchar *clickme = "Click Me";
guint counter = 0;

#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
    GtkLabel *l = GTK_LABEL(d);
    char nt[MAXLEN];

    counter++;
    snprintf(nt, MAXLEN, "You clicked me %d times", counter);
    gtk_label_set_text(l, nt);
}

int main(int argc, char **argv)
{
    GtkWindow *win;
    GtkButton *button;
    GtkLabel *label;
    GtkVBox *vbox;

    gtk_init(&argc, &argv);
    win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(win, clickme);
    button = (GtkButton*)gtk_button_new_with_label(clickme);
    label = (GtkLabel*)gtk_label_new("There have been no clicks yet");
    gtk_label_set_single_line_mode(label, TRUE);
    vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
    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(button), "clicked", (GCallback)clickedme, label);
    gtk_widget_show_all(GTK_WIDGET(win));
    gtk_main();
    return 0;
}

Implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button, labelled "click me", updates the label to show the number of times it has been clicked when interacted with.


Library: SQLite
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>

const char *code =
"CREATE TABLE address (\n"
"       addrID		INTEGER PRIMARY KEY AUTOINCREMENT,\n"
"	addrStreet	TEXT NOT NULL,\n"
"	addrCity	TEXT NOT NULL,\n"
"	addrState	TEXT NOT NULL,\n"
"	addrZIP		TEXT NOT NULL)\n" ;

int main()
{
  sqlite3 *db = NULL;
  char *errmsg;

  if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {
      fprintf(stderr, errmsg);
      sqlite3_free(errmsg);
      sqlite3_close(db);
      exit(EXIT_FAILURE);
    }
    sqlite3_close(db);
  } else {
    fprintf(stderr, "cannot open db...\n");
    sqlite3_close(db);
    exit(EXIT_FAILURE);
  }
  return EXIT_SUCCESS;
}

create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.


The code performs a countdown from 10 to 0 using a downward for loop.


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

#define NUMLETTERS 26
#define BUFSIZE 4096

char *get_input(void);

int main(int argc, char *argv[])
{
    char const usage[] = "Usage: vinigere [-d] key";
    char sign = 1;
    char const plainmsg[] = "Plain text:  ";
    char const cryptmsg[] = "Cipher text: ";
    bool encrypt = true;
    int opt;

    while ((opt = getopt(argc, argv, "d")) != -1) {
        switch (opt) {
        case 'd':
            sign = -1;
            encrypt = false;
            break;
        default:
            fprintf(stderr, "Unrecogized command line argument:'-%i'\n", opt);
            fprintf(stderr, "\n%s\n", usage);
            return 1;
        }
    }

    if (argc - optind != 1) {
        fprintf(stderr, "%s requires one argument and one only\n", argv[0]);
        fprintf(stderr, "\n%s\n", usage);
        return 1;
    }

    // Convert argument into array of shifts
    char const *const restrict key = argv[optind];
    size_t const keylen = strlen(key);
    char shifts[keylen];

    char const *restrict plaintext = NULL;
    for (size_t i = 0; i < keylen; i++) {
        if (!(isalpha(key[i]))) {
            fprintf(stderr, "Invalid key\n");
            return 2;
        }
        char const charcase = (isupper(key[i])) ? 'A' : 'a';
        // If decrypting, shifts will be negative.
        // This line would turn "bacon" into {1, 0, 2, 14, 13}
        shifts[i] = (key[i] - charcase) * sign;
    }

    do {
        fflush(stdout);
        // Print "Plain text: " if encrypting and "Cipher text:  " if
        // decrypting
        printf("%s", (encrypt) ? plainmsg : cryptmsg);
        plaintext = get_input();
        if (plaintext == NULL) {
            fprintf(stderr, "Error getting input\n");
            return 4;
        }
    } while (strcmp(plaintext, "") == 0); // Reprompt if entry is empty

    size_t const plainlen = strlen(plaintext);

    char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext);
    if (ciphertext == NULL) {
        fprintf(stderr, "Memory error\n");
        return 5;
    }

    for (size_t i = 0, j = 0; i < plainlen; i++) {
        // Skip non-alphabetical characters
        if (!(isalpha(plaintext[i]))) {
            ciphertext[i] = plaintext[i];
            continue;
        }
        // Check case
        char const charcase = (isupper(plaintext[i])) ? 'A' : 'a';
        // Wrapping conversion algorithm
        ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase;
        j = (j+1) % keylen;
    }
    ciphertext[plainlen] = '\0';
    printf("%s%s\n", (encrypt) ? cryptmsg : plainmsg, ciphertext);

    free(ciphertext);
    // Silence warnings about const not being maintained in cast to void*
    free((char*) plaintext);
    return 0;
}
char *get_input(void) {

    char *const restrict buf = malloc(BUFSIZE * sizeof (char));
    if (buf == NULL) {
        return NULL;
    }

    fgets(buf, BUFSIZE, stdin);

    // Get rid of newline
    size_t const len = strlen(buf);
    if (buf[len - 1] == '\n') buf[len - 1] = '\0';

    return buf;
}

implement a Vigenère cipher for both encryption and decryption. It handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. It also includes an option to decrypt the message with the -d command line flag, while preserving the case and skipping non-alphabetical characters.


demonstrate a for-loop with a step-value greater than one, printing all odd digits.


#include <stdio.h>

int i;
double sum(int *i, int lo, int hi, double (*term)()) {
    double temp = 0;
    for (*i = lo; *i <= hi; (*i)++)
        temp += term();
    return temp;
}

double term_func() { return 1.0 / i; }

int main () {
    printf("%f\n", sum(&i, 1, 100, term_func));
    return 0;
}

Works with: gcc

#include <stdio.h>

int i;

#define sum(i, lo_byname, hi_byname, term)      \
  ({                                            \
  int lo = lo_byname;                           \
  int hi = hi_byname;                           \
                                                \
  double temp = 0;                              \
  for (i = lo; i <= hi; ++i)                    \
    temp += term;                               \
  temp;                                         \
  })

int main () {
    printf("%f\n", sum(i, 1, 100, 1.0 / i));
    return 0;
}

The code is an implementation of Jensen's Device, a programming technique that exploits call by name. It calculates the 100th harmonic number using a sum procedure, which takes in four parameters: an integer, a lower limit, an upper limit, and a term. The term and integer are passed by name, allowing their values to be re-evaluated in the caller's context every time they are required. This results in the correct harmonic number calculation. The code also demonstrates the importance of passing the first parameter by name or reference to ensure changes are visible in the caller's context. The output of the code is 5.18738.


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

void hue_to_rgb(double hue, double sat, unsigned char *p)
{
	double x;
	int c = 255 * sat;
	hue /= 60;
	x = (1 - fabs(fmod(hue, 2) - 1)) * 255;

	switch((int)hue) {
	case 0:	p[0] = c; p[1] = x; p[2] = 0; return;
	case 1:	p[0] = x; p[1] = c; p[2] = 0; return;
	case 2:	p[0] = 0; p[1] = c; p[2] = x; return;
	case 3:	p[0] = 0; p[1] = x; p[2] = c; return;
	case 4:	p[0] = x; p[1] = 0; p[2] = c; return;
	case 5:	p[0] = c; p[1] = 0; p[2] = x; return;
	}
}

int main(void)
{
	const int size = 512;
	int i, j;
	unsigned char *colors = malloc(size * 3);
	unsigned char *pix = malloc(size * size * 3), *p;
	FILE *fp;

	for (i = 0; i < size; i++)
		hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);

	for (i = 0, p = pix; i < size; i++)
		for (j = 0; j < size; j++, p += 3)
			memcpy(p, colors + (i ^ j) * 3, 3);

	fp = fopen("xor.ppm", "wb");
	fprintf(fp, "P6\n%d %d\n255\n", size, size);
	fwrite(pix, size * size * 3, 1, fp);
	fclose(fp);

	return 0;
}

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


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

#define DOUBLE_SPACE 1

#if DOUBLE_SPACE
#	define SPC "　"
#else
#	define SPC " "
#endif

wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄";

typedef unsigned char byte;
enum { N = 1, S = 2, W = 4, E = 8, V = 16 };

byte **cell;
int w, h, avail;
#define each(i, x, y) for (i = x; i <= y; i++)

int irand(int n)
{
	int r, rmax = n * (RAND_MAX / n);
	while ((r = rand()) >= rmax);
	return r / (RAND_MAX/n);
}

void show()
{
	int i, j, c;
	each(i, 0, 2 * h) {
		each(j, 0, 2 * w) {
			c = cell[i][j];
			if (c > V) printf("\033[31m");
			printf("%lc", glyph[c]);
			if (c > V) printf("\033[m");
		}
		putchar('\n');
	}
}

inline int max(int a, int b) { return a >= b ? a : b; }
inline int min(int a, int b) { return b >= a ? a : b; }

static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}};
void walk(int x, int y)
{
	int i, t, x1, y1, d[4] = { 0, 1, 2, 3 };

	cell[y][x] |= V;
	avail--;

	for (x1 = 3; x1; x1--)
		if (x1 != (y1 = irand(x1 + 1)))
			i = d[x1], d[x1] = d[y1], d[y1] = i;

	for (i = 0; avail && i < 4; i++) {
		x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1];

		if (cell[y1][x1] & V) continue;

		/* break walls */
		if (x1 == x) {
			t = (y + y1) / 2;
			cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E;
		} else if (y1 == y) {
			t = (x + x1)/2;
			cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N;
		}
		walk(x1, y1);
	}
}

int solve(int x, int y, int tox, int toy)
{
	int i, t, x1, y1;

	cell[y][x] |= V;
	if (x == tox && y == toy) return 1;

	each(i, 0, 3) {
		x1 = x + dirs[i][0], y1 = y + dirs[i][1];
		if (cell[y1][x1]) continue;

		/* mark path */
		if (x1 == x) {
			t = (y + y1)/2;
			if (cell[t][x] || !solve(x1, y1, tox, toy)) continue;

			cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N;
		} else if (y1 == y) {
			t = (x + x1)/2;
			if (cell[y][t] || !solve(x1, y1, tox, toy)) continue;

			cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W;
		}
		return 1;
	}

	/* backtrack */
	cell[y][x] &= ~V;
	return 0;
}

void make_maze()
{
	int i, j;
	int h2 = 2 * h + 2, w2 = 2 * w + 2;
	byte **p;

	p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1);

	p[1] = (byte*)(p + h2 + 2) + 1;
	each(i, 2, h2) p[i] = p[i-1] + w2;
	p[0] = p[h2];
	cell = &p[1];

	each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V;
	each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V;
	each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W;
	each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S;
	each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S;
	each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E;

	avail = w * h;
	walk(irand(2) * 2 + 1, irand(h) * 2 + 1);

	/* reset visited marker (it's also used by path finder) */
	each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V;
	solve(1, 1, 2 * w - 1, 2 * h - 1);

	show();
}

int main(int c, char **v)
{
	setlocale(LC_ALL, "");
	if (c < 2 || (w = atoi(v[1])) <= 0) w = 16;
	if (c < 3 || (h = atoi(v[2])) <= 0) h = 8;

	make_maze();

	return 0;
}

Sample output:
┌───┬─────┬─────────┬───────┬───┐
│┄┄╮│╭┄┄┄╮│　　╭┄┄┄┄┄╮│　　╭┄┄┄╮│╭┄╮│
│　│┆│┆──┐┆│　│┆──┬─┐┆└──┆┌─┐┆│┆│┆│
│　│┆│╰┄╮│┆│　│╰┄╮│　│╰┄┄┄╯│　│╰┄╯│┆│
│　│┆└──┆│┆└─┼──┆│　└─────┤　└─┬─┘┆│
│　│╰┄┄┄╯│╰┄╮│╭┄╯│　　　　　　　│　　　│╭┄╯│
│　└─────┴─┐┆│┆┌─┴───┐　│　│　│　│┆──┤
│　　　　　　　　　│┆│┆│╭┄┄┄╮│　│　　　│　│╰┄╮│
│　──────┐　│┆│┆│┆──┐┆└─┤　┌─┘　└─┐┆│
│　　　　　　　│　│┆│╰┄╯　　│╰┄╮│　│　　　　　│┆│
│　┌─────┘　│┆├─────┴─┐┆│　│　──┬─┘┆│
│　│　　　　　　　│┆│╭┄┄┄┄┄╮│┆│　│　　　│╭┄╯│
├─┤　──┬─┬─┘┆│┆┌─┬──┆│┆└─┴─┐　│┆┌─┤
│　│　　　│　│╭┄╯│┆│　│╭┄╯│╰┄┄┄╮│　│┆│　│
│　└──　│　│┆──┘┆│　│┆──┴────┆│　│┆│　│
│　　　　　│　　╰┄┄┄╯│　　╰┄┄┄┄┄┄┄╯│　　╰┄┄│
└─────┴───────┴───────────┴─────┘

generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and processes its neighbors. If a neighbor has not been visited, it removes the wall between the current cell and the neighbor, then recursively repeats the process with the neighbor as the current cell. The code requires a UTF8 locale and a unicode capable console. If the console font line-drawing characters are single width, it sets DOUBLE_SPACE to 0.