#include <stdio.h>
main() /*count digits, white space, others */
{
int c, i, nwhite, nother, ndigit[10];
nwhite =nother = 0;
for (i = 0; i < 10; i++)
ndigit[i] = 0;
while((c =getchar()) != EOF) {
switch(c){
case '0':case '1':case '2':case '3': case '4' :
case '5':case '6':case '7':case '8':case '9':
ndigit[c - '0']++;
break;
case ' ':
case '\n':
case '\t':
nwhite++;
break;
default:
nother++;
break;
}
}
printf("digits =");
for(i = 0; i < 10; i++)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
return 0;
}
Author: curious_cat
binary search.
/*binsearch: find x in v[0] <= v[1] ....<= v[n -1] */
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n -1;
while (low <= high){
mid = (low + high) / 2;
if (x < v[mid])
high = mid - 1;
else if (x > v[mid])
low = mid + 1;
else
return mid; /*found match */
}
return -1; /* no match */
}
count the number of 1 bits in integer argument.
/*bitcount: count 1 bits in x */
int bitcount(unsigned x)
{
int b;
for (b =0; x != 0; x >>= 1)
if (x & 01)
b++;
return b;
}
return right-adjusted n-bit field that begins at p.
/*getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p + 1 - n) & ~(~0 << n);
}
strcat:concatenate t to end of s.
/*strcat: concatenate t to end of s; s must be big enough */
void strcat(char s[], char t[])
{
int i, j;
i = j = 0;
while(s[i] != '\0') /*find end of s*/
i++;
while ((s[i++] = t[j++]) != '\0') /* copy t */
;
}
remove all occurrences of the character c from the string s
/*squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for(i = j = 0; s[i] !='\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
pseudo-random number generator.
unsigned long int next = 1;
/*rand: return pseudo-random integer on 0...32767 */
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int )(next/65536) % 32768;
}
/*srand; set seed for rand() */
void srand(unsigned int seed)
{
next = seed;
}
lower: convert char to lower case.
/*lower: convert c to lower case:ASCII only */
int lower(int c)
{
if (c >= 'A' && c <= 'Z')
return c + 'a' - 'A';
else
return c;
}
atoi:convert string to integer
int atoi(char s[])
{
int i, n;
n = 0;
for(i =0; s[i] >= '0' && s[i] <= '9';++i)
n = 10 * n + (s[i] - '0');
return n;
}
Is it a leap year?
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n', year);