Skip to main content.

01_hello.c Download

#include <stdio.h>

int main() 
{
    printf( "hello, world\n" );
}


/*
Discuss:

- compilation
    (Windows)
    - MinGW (http://www.mingw.org/)
    - SCITE setup (http://www.scintilla.org/SciTE.html)
                  (installer: http://gisdeveloper.tripod.com/scite.html)
     "Options" --> "Open cpp properties"
      Change line from:
        cc=g++ -pedantic -Os -fno-exceptions -c $(FileNameExt) -o $(FileName).o
      to:
        cc=gcc -pedantic -Os -fno-exceptions $(FileNameExt) -o $(FileName).exe

- C program: functions & variables
- main: special - program begins executing
- character string (string constant)
- \n - escape sequence
- printf: formatted print
- see 02_hello.c

Exercises (page 8)

 */
01_hello.c Download

02_hello.c Download
#include <stdio.h>

main() 
{
      printf("hello, ");
      printf("world");
      printf("\n");
}

02_hello.c Download

03_tempconv.c Download
#include <stdio.h>

/* print Fahrenheit-Celsius table
   for fahr = 0, 20, ..., 300 */
main() 
{
      int fahr, celsius;
      int lower, upper, step;

      lower = 0;      /* lower limit of temperature scale */
      upper = 300;    /* upper limit */
      step = 20;      /* step size */

      fahr = lower;
      while (fahr <= upper) {
            celsius = 5 * (fahr-32) / 9;
            printf("%d\t%d\n", fahr, celsius);
            fahr = fahr + step;
      }
}

/*
Discuss:

- comments
- declarations (types)
- variables
- arithmetic expressions
- loops
- formatted output

- types:
    basic data types (int, float, char, short, long, double)
    arrays
    structs
    unions
    pointers to above
    functions that return above

- indentation, braces

- see 04_tempconv.c, 05_tempconv.c

Exercises (page 13): 1.4

*/
03_tempconv.c Download

04_tempconv.c Download
#include <stdio.h>

/* print Fahrenheit-Celsius table
   for fahr = 0, 20, ..., 300; floating-point version */
main() 
{
      float fahr, celsius;
      float lower, upper, step;

      lower = 0;      /* lower limit of temperatuire scale */
      upper = 300;    /* upper limit */
      step = 20;      /* step size */

      fahr = lower;
      while (fahr <= upper) {
            celsius = (5.0/9.0) * (fahr-32.0);
            printf("%3.0f %6.1f\n", fahr, celsius);
            fahr = fahr + step;
      }
}
04_tempconv.c Download

05_tempconv.c Download
#include <stdio.h>

/* print Fahrenheit-Celsius table */
main()
{
      int fahr;

      for (fahr = 0; fahr <= 300; fahr = fahr + 20)
          printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}


/*
Discuss:

- for statement
- see 06_tempconv.c

Exercise 1-5 (page 14)

*/
05_tempconv.c Download

06_tempconv.c Download
#include <stdio.h>

#define LOWER  0     /* lower limit of table */
#define UPPER  300   /* upper limit */
#define STEP   20    /* step size */

/* print Fahrenheit-Celsius table */
main()
{
      int fahr;

      for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
          printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

/*
Discuss:

- symbolic constants


*/
06_tempconv.c Download

07_copy.c Download
#include <stdio.h>

/* copy input to output;   */
main()
{
      int c;

      c = getchar();
      while (c != EOF) {
            putchar(c);
            c = getchar();
      }
}


/*
Discuss:

- getchar(): reads next input character from text stream
- why returns int? (not char)
- see 08_copy.c


*/
07_copy.c Download

08_copy.c Download
#include <stdio.h>

/* copy input to output;   */
main()
{
      int c;

      while ((c = getchar()) != EOF)
            putchar(c);
}

/*
Discuss:

- assignment is an expression (value is value of lhs after assigment)
- common loop idiom (parentheses needed b/c of precedence)
- c = getchar() != EOF  <===> c = (getchar() != EOF)
    why returns 0 or 1?

Exercise 1-7 (page 17)

*/
08_copy.c Download

09_count.c Download
#include <stdio.h>

/* count characters in input;  */
main()
{
      long nc;

      nc = 0;
      while (getchar() != EOF)
            ++nc;
      printf("%ld\n", nc);
}

/*
Discuss:

- ++, --, post-/pre-
- change long to double, printf( "%.0f...
         for (nc = 0; getchar() != EOF; ++nc)
            ;
    empty loop body

*/
09_count.c Download

10_countline.c Download
#include <stdio.h>

/* count lines in input */
main()
{
      int c, nl;

      nl = 0;
      while ((c = getchar()) != EOF)
            if (c == '\n')
               ++nl;
      printf("%d\n", nl);
}

/*
Discuss:

- counting lines = counting newline characters
- == (equality operator), no warning/error if use = instead!
- character constants
    integer value equal to numerical value in machine's 
    character set (e.g. ASCII)
    if (c == 10) ... (same thing...)

Exercises 1-8, 1-9, 1-10 (page 20)

*/
10_countline.c Download

11_countword.c Download
#include <stdio.h>

#define IN   1  /* inside a word */
#define OUT  0  /* outside a word */

/* count lines, words, and characters in input */
main()
{
   int c, nl, nw, nc, state;

   state = OUT;
   nl = nw = nc = 0;
   while ((c = getchar()) != EOF) {
       ++nc;
       if (c == '\n')
           ++nl;
       if (c == ' ' || c == '\n' || c == '\t')
           state = OUT;
       else if (state == OUT) {
           state = IN;
           ++nw;
       }
   }
   printf("%d %d %d\n", nl, nw, nc);
}


/*
Discuss:

- UNIX program wc
- nl = nw = nc = 0  <===>  nl = (nw = (nc = 0));
- || ==> 'OR',  && ==> 'AND'
- else statement

Exercises 1-11, 1-12 (page 21)

*/
11_countword.c Download

12_countdigit.c Download
#include <stdio.h>

/* count digits, white space, others */
main()
{
   int c, i, nwhite, nother;
   int ndigit[10];

   nwhite = nother = 0;
   for (i = 0; i < 10; ++i)
       ndigit[i] = 0;

   while ((c = getchar()) != EOF)
       if (c >= '0' && c <= '9')
           ++ndigit[c-'0'];
       else if (c == ' ' || c == '\n' || c == '\t')
           ++nwhite;
       else
           ++nother;

   printf("digits =");
   for (i = 0; i < 10; ++i)
       printf(" %d", ndigit[i]);
   printf(", white space = %d, other = %d\n",
       nwhite, nother);
}


/*
Discuss:

- arrays, subscripts
- else if
- testing for digits


*/
12_countdigit.c Download

13_power.c Download
#include <stdio.h>

int power(int m, int n);

/* test power function */
main()
{
    int i;

    for (i = 0; i < 10; ++i)
        printf("%d %d %d\n", i, power(2,i), power(-3,i));
    return 0;
}

/* power:  raise base to n-th power; n >= 0 */
int power(int base, int n)
{
    int i,  p;

    p = 1;
    for (i = 1; i <= n; ++i)
        p = p * base;
    return p;
}

/*
Discuss:

- functions (encapsulate computations, use without worry about implem.)
- function declaration (function prototype), definition
- parameter vs. argument (formal argument/actual argument)
- arguments, call by value
- local variables
- call by reference using pointers (later), arrays are call by reference

  change power:
    int p;
    for (p=1; n>0; --n)
        p = p * base;
    return p;


Exercise 1-15 (page 27)

*/
13_power.c Download

14_longline.c Download
#include <stdio.h>
#define MAXLINE 1000   /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */
main()
{
   int len;            /* current line length */
   int max;            /* maximum length seen so far */
   char line[MAXLINE];    /* current input line */
   char longest[MAXLINE]; /* longest line saved here */

   max = 0;
   while ((len = getline(line, MAXLINE)) > 0)
       if (len > max) {
           max = len;
           copy(longest, line);
       }
   if (max > 0)  /* there was a line */
       printf("%s", longest);
   return 0;
}

/* getline:  read a line into s, return length  */
int getline(char s[],int lim)
{
   int c, i;

   for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
       s[i] = c;
   if (c == '\n') {
       s[i] = c;
       ++i;
   }
   s[i] = '\0';
   return i;
}

/* copy:  copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
   int i;

   i = 0;
   while ((to[i] = from[i]) != '\0')
       ++i;
}


/*
Discuss:

- character arrays (most common use of arrays)
- pseudocode
    while (there's another line)
        if (it's longer than previous longest)
            save it
            save its length
    print longest line

- getline() - fetch next line of input,
  copy() - to copy new line to save it

- strings and null character '\0' terminator


Exercise 1-16, 1-18

*/
14_longline.c Download

15_longline.c Download
#include <stdio.h>

#define MAXLINE 1000    /* maximum input line size */

/* external variables */
int max;                /* maximum length seen so far */
char line[MAXLINE];     /* current input line */
char longest[MAXLINE];  /* longest line saved here */

int getline(void);
void copy(void);

/* print longest input line; specialized version */
main()
{
   int len;
   extern int max;
   extern char longest[];

   max = 0;
   while ((len = getline()) > 0)
       if (len > max) {
           max = len;
           copy();
       }
   if (max > 0)  /* there was a line */
       printf("%s", longest);
   return 0;
}

/* getline:  specialized version */
int getline(void)
{
   int c, i;
   extern char line[];

   for (i = 0; i < MAXLINE - 1 
        && (c=getchar()) != EOF && c != '\n'; ++i)
            line[i] = c;
   if (c == '\n') {
       line[i] = c;
       ++i;
   }
   line[i] = '\0';
   return i;
}

/* copy: specialized version */
void copy(void)
{
   int i;
   extern char line[], longest[];

   i = 0;
   while ((longest[i] = line[i]) != '\0')
       ++i;
}

/*
Discuss:

- local vs. global/external variables
- local = automatic (created & disappear as function called/exited)
- external variables: defined exactly once outside of any functions,
                      declared in functions that want to use
- splitting into files, header files


*/
15_longline.c Download