Aims and Objectives
Another Looping Construct
Symbolic Constants
Character Input and Output
Counting Characters
Another Program...
Arrays
Functions
Call by Value
Call by Reference
A function to fetch a line of input
for (initialisation ; condition ; expression) { statements; }
The temperature conversion program with a for loop instead of a while loop
// program name: temp_conv1.c #include <stdio.h> main() { int fahr; for (fahr=0; fahr <= 300; fahr = fahr+20) { printf("%3d %6.1f\n",fahr,(5.0/9.0)*(fahr-32)); } }
for (fahr=0; fahr <= 300; fahr = fahr+20)
#define NAME value
Example
// program name: temp_conv2.c #include <stdio.h> #define LOWER 0 /* lower limit of table */ #define UPPER 300 /* upper limit */ #define STEP 20 /* step size */ main() { int fahr; for (fahr=LOWER; fahr<=UPPER; fahr=fahr+STEP) { printf("%3d %6.1f\n",fahr,(5.0/9.0)*(fahr-32)); } }
getchar(); /* get an input character */
putchar(c); /* send an output character */
//program name: readchar.c #include <stdio.h> main() { int c; /* store the next char input */ while ((c = getchar()) != EOF) { putchar(c); } }
' 'will generate an error!
//program name: countAllChars.c #include <stdio.h> main() { int c; /* for input char */ int nc, ns, nl; /* declare vars */ nc = ns = nl = 0; /* init. vars to 0 */ while ((c = getchar()) != EOF) { ++nc; if (c == ' ') ++ns; else if (c == '\n') ++nl; } printf("nc=%d; ns=%d; nl=%d", nc,ns,nl); }
//program name: countChars.c #include <stdio.h> main() { int c; int nc = 0; /* declare vars */ while ((c = getchar()) != EOF) { if (! (c == ' ' || c == '\n')) ++nc; } printf("nc=%d", nc); }
//program name: countAlpha.c #include <stdio.h> main() { int c; /* store input char */ int nletters[26]; /*array of 26 cells */ int i; /* handy variable */ for (i = 0; i < 26; ++i) nletters[i] = 0; while ((c = getchar()) != EOF) { if (c >= 'a' && c <= 'z') ++nletters[c - 'a']; else if (c >= 'A' && c <= 'Z') ++nletters[c - 'A']; } for (i = 0; i < 26; ++i) { c = 'a' + i; putchar(c); printf(" = %d\n", nletters[i]); } } Output for input: aAbcBc a = 2 b = 2 c = 2
//program name: power.c #include <stdio.h> int power(int base, int n); /* prototype */ main() { int i; /* handy variable */ for (i = 0; i <= 10; ++i) printf("2^%d %d\n",i,power(2,i)); } int power(int base, int i) { int n; /*handy variable */ for (n = 1; i > 0; --i) n = n * base; return n; }
//program name: readLine.c #include <stdio.h> #define MAX 80 /* max line length */ int getline(char line[],int max); /*prototype*/ main() { char s[MAX]; getline(s, MAX); printf("%s", s); } int getline(char s[], int max) { int c, i; /*store an input char, index*/ for(i=0; i < max && (c=getchar()) != '\n' && c != EOF; s[i++] = c) ; if (c == '\n') s[i++] = '\n'; s[i] = '\0'; return i; }