The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
C
1
Print a literal string on standard output
printf("Hello World\n");
Alternative implementation:
int a;
scanf("%d",&a);
2
Loop to execute some code a constant number of times
for (int i = 0; i < 10; i++) {
    printf("Hello\n");
}
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
void finish(void) {
    printf("My job here is done.\n");
}
4
Create a function which returns the square of an integer
int square(int x){
  return x*x;
}
5
Declare a container type for two floating-point numbers x and y
typedef struct {
  double x;
  double y;
} Point;
6
Do something with each item x of an array-like collection items, regardless indexes.
for (unsigned int i = 0 ; i < items_length ; ++i){
        Item* x = &(items[i]);
	DoSomethingWith(x);
}
Alternative implementation:
for (size_t i = 0; i < sizeof(items) / sizeof(items[0]); i++) {
	DoSomethingWith(&items[i]);
}
7
Print each index i with its value x from an array-like collection items
for (size_t i = 0; i < n; i++) {
  printf("Item %d = %s\n", i, toString(items[i]));
}
8
Create a new map object x, and provide some (key, value) pairs as initial content.
ENTRY a = {"foo", "twenty"};
ENTRY b = {"bar", "three"};
if (hcreate (23)) {
    hsearch(a, ENTER);
    hsearch(b, ENTER);
}
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
struct treenode{
  int value;
  struct treenode* left;
  struct treenode* right;
}
10
Generate a random permutation of the elements of list x
srand(time(NULL));
for (int i = 0; i < N-1; ++i)
{
    int j = rand() % (N-i) + i;
    int temp = x[i];
    x[i] = x[j];
    x[j] = temp;
}
11
The list x must be non-empty.
x[rand() % x_length];
12
Check if the list contains the value x.
list is an iterable finite container.
bool contains(int x, int* list, size_t list_len) {
    for (int i=0 ; i<list_len ; i++)
        if (list[i] == x)
            return true;
    return false;
}
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
double pick(double a, double b)
{
	return a + (double)rand() / ((double)RAND_MAX * (b - a));
}
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
int pick(int a, int b)
{
	int upper_bound = b - a + 1;
	int max = RAND_MAX - RAND_MAX % upper_bound;
	int r;

	do {
		r = rand();
	} while (r >= max);
	r = r % upper_bound;
	return a + r;
}
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
typedef struct node_s
{
    int value;
    struct node_s *nextSibling;
    struct node_s *firstChild;
} node_t;
19
Reverse the order of the elements of list x.
This may reverse "in-place" and destroy the original ordering.
int *p1 = x;
int *p2 = x + N-1;

while (p1 < p2)
{
    int temp = *p1;
    *(p1++) = *p2;
    *(p2--) = temp;
}
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
void search(void ***m,void *x,size_t memb_size,int len_x,int len_y,int *i,int *j)
{
	for(*i=0;*i<len_x;*i+=1)
	{
		for(*j=0;*j<len_y;*j+=1)
		{
			if(!memcmp(m[*i][*j],x,memb_size))
			{
				return;
			}
		}
	}
	*i=*j=-1;
}
21
Swap the values of the variables a and b
a^=b;
b^=a;
a^=b;
22
Extract the integer value i from its string representation s (in radix 10)
int i = atoi(s);
Alternative implementation:
i = (int)strtol(s, (char **)NULL, 10);
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
sprintf(s, "%.2f", x);
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
const char * s = "ネコ";
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
double **x=malloc(m*sizeof(double *));
int i;
for(i=0;i<m;i++)
	x[i]=malloc(n*sizeof(double));
Alternative implementation:
const int m = 2;
const int n = 3;
double x[m][n];
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
double ***x=malloc(m*sizeof(double **));
int i,j;
for(i=0;i<m;i++)
{
	x[i]=malloc(n*sizeof(double *));
	for(j=0;j<n;j++)
	{
		x[i][j]=malloc(p*sizeof(double));
	}
}
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
int compareProp (const void *a, const void *b)
{
    return (*(const Item**)a)->p - (*(const Item**)b)->p;
}

qsort(items, N, sizeof(Item*), compareProp);
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
unsigned int f(unsigned int i)
{
	return i?i*f(i-1):1;
}
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
unsigned int exp(unsigned int x,unsigned int n)
{
    if(n==0)
    {
        return 1;
    }
    if(n==1)
    {
        return x;
    }
    if(!(n%2))
    {
        return exp(x*x,n/2);
    }
    return x*exp(x*x,(n-1)/2);
}
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
char *t=malloc((j-i+1)*sizeof(char));
strncpy(t,s+i,j-i);
39
Set boolean ok to true if string word is contained in string s as a substring, or to false otherwise.
int ok = strstr(s,word) != NULL;
41
Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
char *strrev(char *s)
{
	size_t len = strlen(s);
	char *rev = malloc(len + 1);

	if (rev) {
		char *p_s = s + len - 1;
		char *p_r = rev;

		for (; len > 0; len--)
			*p_r++ = *p_s--;
		*p_r = '\0';
	}
	return rev;
}
42
Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.
int *v = a;
while (v < a+N)
{
    int *w = b;
    while (w < b+M)
    {
        if (*v == *w)
            goto OUTER;
        
        ++w;
    }
    printf("%d\n", *v);
    
    OUTER: ++v;
}
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
int i,j;
for(i=0;i<sizeof(m)/sizeof(*m);i++)
{
	for(j=0;j<sizeof(*m)/sizeof(**m);j++)
	{
		if(m[i][j]<0)
		{
			printf("%d\n",m[i][j]);
			goto end;
		}
	}
}
end:
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
usleep(5000000);
Alternative implementation:
Sleep(5000);
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
"AzIceaqfA1hX5wS+M8cGnYh5ceevUnOZIzJBbXFD6dgf3tBkb9cvUF/Tkd/iKu2fsg9wAysY"
    "Kw7RMAsVvIp4KcXle/v1RaXrLVnNBJ2H2DmrbUMOZbQUFXe698qmJsqNpLXRA367xpZ54i8k"
    "C5DTXwDhfxWTOZrBrh5sRKHcoVLumztIQjgWh37AzmSd1bLOfUGI0xjAL9zJWO3fRaeB0NS2"
    "KlmoKaVT5Y04zZEc06waU2r6AU2Dc4uipJqJmObqKM+tfNKAS0rZr5IudRiC7pUwnmtaHRe5"
    "fgSI8M7yvypvm+13Wm4Gwd4VnYiZvSxf8ImN3ZOG9wEzfyMIlH2+rKPUVHI+igsqla0Wd9m7"
    "ZUR9vFotj1uYV0OzG7hX0+huN2E/IdgLDjbiapj1e2fKHrMmGFaIvI6xzzJIQJF9GiRZ7+0j"
    "NFLKSyzX/K3JAyFrIPObfwM+y
49
Build list chunks consisting in substrings of input string s, separated by one or more space characters.
chunks[0] = strtok(s, " ");
for (int i = 1; i < N; ++i)
{
    chunks[i] = strtok(NULL, " ");
    
    if (!chunks[i])
        break;
}
50
Write a loop that has no end clause.
forever {
	// Do something
}
Alternative implementation:
for(;;){
	// Do something
}
Alternative implementation:
while(1){
	// Do something
}
Alternative implementation:
loop:
	goto loop;
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
#define DELIM ", "
#define L 64

char y[L] = {'\0'};

for (int i = 0; i < N; ++i)
{
    if (i && x[i][0])
        strcat(y, DELIM);
    
    strcat(y, x[i]);
}
54
Calculate the sum s of the integer list or array x.
int i,s;
for(i=s=0;i<n;i++)
{
	s+=x[i];
}
Alternative implementation:
int sum = 0;
for (int i = 0; i < n; ++i) {
  sum += x[i];
}
55
Create the string representation s (in radix 10) of the integer value i.
char s[0x1000]={};
itoa(i,s,10);
58
Create string lines from the content of the file with filename f.
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));

while(!feof(file))
{
	assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
	len+=fread(lines,1,0x1000,file);
}

assert(lines=realloc(lines,len*sizeof(char)));
Alternative implementation:
int err = 0;
int fd = 0;
void * ptr = NULL;
struct stat st;
if ((fd = open (f, O_RDONLY))
&& (err = fstat (fd, &st)) == 0
&& (ptr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != -1) {
    const char * lines = ptr;
    puts (lines);
    munmap (ptr, st.st_size);
    close (fd);
}
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
fprintf(stderr,"%d is negative\n",x);
60
Assign to x the string value of the first command line parameter, after the program name.
void main(int argc, char *argv[])
{
    char *x = argv[1];
}
61
Assign to variable d the current date/time value, in the most standard type.
time_t d=time(0);
62
Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.
int i=(int)(x-strstr(x,y));
65
From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
printf("%.1lf%%\n", x * 100);
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
srand(s);
70
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
srand((unsigned)time(0));
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
int main(int argc, char *argv[])
{
    while (*++argv) {
        printf("%s", *argv);
        if (argv[1]) printf(" ");
    }
    printf("\n");
    return EXIT_SUCCESS;
}
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);

mpz_gcd(_x, _a, _b);
gmp_printf("%Zd\n", _x);
75
Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);

mpz_lcm(_x, _a, _b);
gmp_printf("%Zd\n", _x);
77
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
float complex _x = -2 + 3 * I;

_x *= I;
78
Execute a block once, then execute it again as long as boolean condition c is true.
do {
	someThing();
	someOtherThing();
} while(c);
79
Declare the floating point number y and initialize it with the value of the integer x .
float y = (float)x;
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
int y = (int)x;
81
Declare integer y and initialize it with the rounded value of floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
int y = (int)floorf(x + 0.5f);
82
Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.
unsigned n;
for (n = 0; s = strstr(s, t); ++n, ++s)
	;
84
Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2
uint32_t c = i;
c = (c & 0x55555555) + ((c & 0xAAAAAAAA) >> 1);
c = (c & 0x33333333) + ((c & 0xCCCCCCCC) >> 2);
c = (c & 0x0F0F0F0F) + ((c & 0xF0F0F0F0) >> 4);
c = (c & 0x00FF00FF) + ((c & 0xFF00FF00) >> 8);
c = (c & 0x0000FFFF) + ((c & 0xFFFF0000) >> 16);
85
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.
bool addingWillOverflow(int x, int y) {
  return ((x > 0) && (y > INT_MAX - x)) ||
         ((x < 0) && (y < INT_MIN - x));
}
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
exit (EXIT_SUCCESS);
Alternative implementation:
return 0;
Alternative implementation:
abort();
88
Create a new bytes buffer buf of size 1,000,000.
void *buf = malloc(1000000);
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
enum {
    E_OK,
    E_OUT_OF_RANGE
};

int square(int x, int *result) {
    if (x > 1073741823) {
        return E_OUT_OF_RANGE;
    }
    *result = x*x;
    return E_OK;
}
93
Implement procedure control which receives one parameter f, and runs f.
void control (void (*f)()) {
        (*f)();
}
95
Assign to variable x the length (number of bytes) of the local file at path.
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
int x = ftell(f);
Alternative implementation:
struct stat st;
if (stat (path &st) == 0) x = st.st_size;
96
Set boolean b to true if string s starts with prefix prefix, false otherwise.
bool b = !strncmp(s, prefix, sizeof(prefix)-1);
100
Sort elements of array-like collection items, using a comparator c.
int c(const void *a,const void *b)
{
	int x = *(const int *)a;
	int y = *(const int *)b;

	if (x < y) return -1;
	if (x > y) return +1;
	return 0;
}

int main(void)
{
	int arr[]={1,6,3,7,2};
	qsort(arr,sizeof(arr)/sizeof(*arr),sizeof(*arr),c);

	return 0;
}
105
Assign to the string s the name of the currently executing program (but not its full path).
#ifdef _WIN32
#define PATH_SEP '\\'
#else
#define PATH_SEP '/'
#endif

int main(int argc, char* argv[])
{
    char *s = strchr(argv[0], PATH_SEP);
    s = s ? s + 1 : argv[0];

    return 0;
}
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
char *dir = getcwd(NULL, 0);
107
Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)
int main()
{
    char exe[PATH_MAX], real_exe[PATH_MAX];
    ssize_t r;
    char *dir;

    if ((r = readlink("/proc/self/exe", exe, PATH_MAX)) < 0)
      exit(1);
    if (r == PATH_MAX)
	r -= 1;
    exe[r] = 0;
    if (realpath(exe, real_exe) == NULL)
	exit(1);
    dir = dirname(real_exe);
    puts(dir);
}
109
Set n to the number of bytes of a variable t (of type T).
n = sizeof (t);
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
bool blank = true;
for (const char *p = s; *p; p++) {
	if (!isspace(*p)) {
		blank = false;
		break;
	}
}
111
From current process, run program x with command-line parameters "a", "b".
int system("x a b");
117
Set n to the number of elements of the list x.
size_t n = sizeof(x)/sizeof(*x);
Alternative implementation:
int n;
int x[5];
n = sizeof(x)/sizeof(*x);
120
Read an integer value from the standard input into the variable n
int n;
scanf("%d", &n);
Alternative implementation:
int n[15];
fgets(n, 15, stdin);
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
enum Suit {
    SPADES,
    HEARTS,
    DIAMONDS,
    CLUBS
};
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert(isConsistent());
127
Import the source code for the function foo body from a file "foobody.txt".
void foo()
{
#include "foobody.txt"
}
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if (c1)
{
    f1();
} 
else if (c2)
{
    f2();
}
else if (c3)
{
    f3();
}
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
char b = 0;
int n = strlen(s);
for (int i = 0; i < n; i++) {
	if (! (b = (s[i] >= '0' && s[i] <= '9')))
		break;
}
Alternative implementation:
bool b = true;
const int n = strlen(s);
for (int i = 0; i < n; ++i) {
  if (!isdigit(s[i])) {
    b = false;
    break;
  }
}
138
Create a new temporary file on the filesystem.
const char tmpl[] = "XXXXXX.tmp";
int fd = mkstemp(tmpl);
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
char s[32];
snprintf(s, sizeof(s), "%x", i);
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should never do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
bool b = (access(_fp, F_OK) == 0) ? true : false;
149
As an exception, this content is not under license CC BY-SA 3.0 like the rest of this website.
 
155
Delete from filesystem the file having path filepath.
int main(void)
{
	if (unlink(filepath) == -1)
		err(1, "unlink");
	return 0;
}
157
Initialize a constant planet with string value "Earth".
const char *_planet = "Earth";
162
execute bat if b is a program option and fox if f is a program option.
int main(int argc, char * argv[])
{
        int optch;
        while ((optch = getopt(argc, argv, "bf")) != -1) {
                switch (optch) {
                        case 'b': bat(); break;
                        case 'f': fox(); break;
                }
        }
        return 0;
}
163
Print all the list elements, two by two, assuming list length is even.
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);
165
Assign to variable x the last element of list items.
int length = sizeof(items) / sizeof(items[0]);
int x = items[length - 1];
167
Create string t consisting of string s with its prefix p removed (if s starts with p).
size_t l = strlen(p);
const char * t = strncmp(s, p, l) ? s : s + l;
173
Number will be formatted with a comma separator between every group of thousands.
setlocale(LC_ALL, "");
printf("%'d\n", 1000);
176
From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
const char* hexstring = "deadbeef";
size_t length = sizeof(hexstring);
unsigned char bytearray[length / 2];

for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2)
	bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25;
178
Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.
int isInsideRect(double x1, double y1, double x2, double y2, double px, double py){
	return px >= x1 && px <= x2 && py >= y1 && py <= y2; 
}
180
Create list x containing the contents of directory d.

x may contain files and subfolders.
No recursive subfolder listing.
struct dirent ** x = NULL;
int n = scandir (p, &x, NULL, alphasort);
182
Output the source of the program.
int main(){char*s="int main(){char*s=%c%s%c;printf(s,34,s,34);return 0;}";printf(s,34,s,34);return 0;}
Alternative implementation:
main(p){printf(p="main(p){printf(p=%c%s%1$c,34,p);}",34,p);}
186
Exit a program cleanly indicating no error to OS
exit(EXIT_SUCCESS);
190
Declare an external C function with the prototype

void foo(double *a, int n);

and call it, passing an array (or a list) of size 10 to a and 10 to n.

Use only standard features of your language.
void foo(double *a, int n);
double a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
foo (a, sizeof(a)/sizeof(*a));
191
Given a one-dimensional array a, check if any value is larger than x, and execute the procedure f if that is the case
unsigned i;
for (i = 0; i < sizeof(a) / sizeof(a[0]); ++i) {
	if (a[i] > x) {
		f();
		break;
	}
}
198
Abort program execution with error condition x (where x is an integer value)
exit(x);
204
Given a real number a, print the fractional part and the exponent of the internal representation of that number. For 3.14, this should print (approximately)

0.785 2
  double d = 3.14;
  double res;
  int e;

  res = frexp(d, &e);
  printf("%f %d\n",res,e);
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
const char * foo = getenv("FOO");
if (foo == NULL) foo = "none";
208
Given the arrays a,b,c,d of equal length and the scalar e, calculate a = e*(a+b*c+cos(d)).
Store the results in a.
  for (i=0; i<n; i++)
    a[i] = e*(a[i]+b[i]*c[i]+cos(d[i]);
252
Assign to the variable x the value "a" if calling the function condition returns true, or the value "b" otherwise.
x = condition() ? "a" : "b";
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
for (int i = 5; i >= 0; i--) {
	printf("%d\n", i);
}
262
Assign to t the number of trailing 0 bits in the binary representation of the integer n.

E.g. for n=112, n is 1110000 in base 2 ⇒ t=4
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);
299
Write a line of comments.

This line will not be compiled or executed.
// This is a comment.