Sample Basic C Programs: Program #1: Fahrenheit and Celsius, Version 1
Sample Basic C Programs: Program #1: Fahrenheit and Celsius, Version 1
Page 1 of 12
/* * print a table for Fahrenheit to Celsius * from 0 F to 300 F * floating point version */ void main(void) { float fahr; /* fahrenheit temperature */ /* * print out the lines for the table */ for(fahr = LOWER; fahr <= UPPER; fahr += STEP) printf("%3.0f\t%6.1f\n", fahr, (5.0/9.0) * (fahr - 32)); /* * say goodbye */ exit(0); }
Page 2 of 12
Page 3 of 12
Page 4 of 12
/* * count the number of lines, words, and chars in the input * a word is a maximal sequence of nonspace characters, so * the quote "+++ --- hi bye 879+3" has 5 words ("+++", "---", * "hi", "bye", and "879+3") */ void main(void) { register int c; /* input char */ register int nl; /* line count */ register int nw; /* word count */ register int nc; /* char count */ register int state; /* in or not in a word? */ /* * initialize */ nl = nw = nc = 0; state = NOTIN_WORD; /* * handle input a char at a time */ while((c = getchar()) != EOF){ /* got another character */ nc++; /* is it a newline? */ if (c == '\n') nl++; /* is it a word separator? */ if (c == ' ' || c == '\t' || c == '\n') /* YES -- change state */ state = NOTIN_WORD; else if (state == NOTIN_WORD){ /* NO -- we're now in a word; update */ /* the counter and state if need be */ state = IN_WORD; nw++; } } /* * announce the results and quit */
Page 5 of 12
Page 6 of 12
Page 7 of 12
Page 8 of 12
Page 9 of 12
Page 10 of 12
Page 11 of 12
Page 12 of 12