Chap 1: Overview of C
 
1.0 Introduction
 
What is a computer?  -->hardware 
What is a computer program?   -->software
 
Computer Organization: 
 - Input unit:  obtain informaion (data and computer program) 
                      from various input device, e.g. keyboard 
 - Output unit:  e.g. screen, printer 
 -  Memory unit 
 -  Arithmetic and logic unit (ALU) 
 -  Central processing unit (CPU): coordinator 
 -  Secondary storage unit
 
What is a program: a set of instructions for computing a job, e.g. compute a leap year
 
What can programs do? 
 -  mathematical computing: leap year, trigonometry, etc 
 -  string manipulation, printing 
 -  storage (file) 
 -  user interations (VR, multimedia) 
 -  music, video ....
 
C language: just like any other human languages-->has a set of rule (syntax)
 
Why C language? 
What are other languages: 
 - Basic, Cobol, Fortran, C++, Lisp, Smalltalk, Ada, Pascal, Prolog, Assembly, .....
 
Writing a program: mapping from problem domain to computer language domain (hard, learn from example)
 
Need data types: 
E.g. Robot Cops: shoot red, protect green 
need data types because we need "exact" communication between human and computers 
==>Basic data types:   int, char, float
 
1.1 The Basics of C Environment  
 

 
 
 
1.2 Program Output
 
 
#include <stdio.h> 

int main(void) 
{ 
   printf("from sea to shining C\n"); 
   return 0; 
}

 
#include <stdio.h> 

int main(void) 
{ 
   printf("from sea to "); 
   printf("shining C"); 
   printf("\n"); 
   return 0; 
}

 
#include <stdio.h> 

int main(void) 
{ 
   printf("from sea\n"); 
   printf("to shining\nC\n"); 
   return 0; 
}

 
#include <stdio.h> 

int main(void) 
{ 
   printf("\n\n\n\n\n"); 
   printf("                    ************************\n"); 
   printf("                    *      from sea                        *\n"); 
   printf("                    *      to shining C                   *\n"); 
   printf("                    ************************\n"); 
   printf("\n\n\n\n\n"); 
   return 0; 
}

 
1.3 Variables, Expressions, Assignment
 
/* The distance of a marathon in kilometers. */ 

#include <stdio.h> 

int main(void) 
{ 
   int miles, yards; 
   float kilometers; 

   miles = 26; 
   yards = 385; 
   kilometers = 1.609 * (miles + yards / 1760.0); 
   printf("\nA marathon is %f kilometers.\n\n", kilometers); 
   return 0; 
}

 
1.4 The Use of #define and #include
 
#define  LIMIT  100 
#define  PI  3.14159 
#defince   C  299792.458   /*speed of light in km/sec  */ 
printf("PI = %f\n", PI);
 
#include  "my_file.h" 
#include <stdio.h>
 
In file pacific_sea.h: 

#include <stdio.h> 

#define  AREA            2337 
#define  SQ_MILES_PER_SQ_KILOMETER  0.386102158 
#define  SQ_FEET_PER_SQ_MILE                 (5280*5280) 
#define  SQ_INCHES_PER_SQ_FOOT            144 
#define  ACRES_PER_SQ_MILE                     640

 
In file pacific_sea.c: 

/*Measuring the Pacific Sea*/ 
#include "pacific_sea.h" 

int main(void) 
{ 
 const int pacif_sea = AREA;   /* in sq kilometers */ 
 double  acres, sq_miles, sq_feet, sq_inches; 

 printf("\nThe Pacific Sea covers an area"); 
 printf(" of %d square kilometers.\n", pacific_sea); 
 sq_miles=SQ_MILES_PER_SQ_KILOMETER*pacific_sea; 
 sq_feet=SQ_FEET_PER_SQ_MILES*sq_miles; 
 sq_inches=SQ_INCHES_PER_SQ_FOOT*sq_feet; 
 acres=ACRES_PER_SQ_MILE*sq_miles; 
 printf("In other units of measure this is:\n\n"); 
 printf("%22.7e acres\n", acres); 
 printf("%22.7e square miles\n", sq_miles); 
 printf("%22.7e square feet\n", sq_feet); 
 printf("%22.7e square inches\n\n", sq_inches); 
 return 0; 
}

 
1.5 The Use of printf() and scanf()
 
printf("abc"); 
printf("%s", "abc"); 
printf("%c%c%c", 'a', 'b', 'c');
 
printf()  ==> 
%c            as a character 
%d            as a decimal integer 
%e            as a floating point number in scientific notation 
%f            as a floating point number 
%g            in the e-format or f-format, whichever is shorter 
%s            as a string
 
printf("%c%3c%5c\n",  'A', 'B', 'C');
 
scanf("%d", &x);    ==>   address
 
scanf()     ===> 
%c            to a character 
%d            to a decimal integer 
%f             to a floating point number (float) 
%lf            to a floating point number (double) 
%LF          to a floating point number (long double) 
%s             to a string
 
#include <stdio.h> 

int main(void) 
{ 
 char c1, c2, c3; 
 int i; 
 float x; 
 double y; 

 printf("\n%s\n%s", 
      "Input three characters," 
      "an int, a float, and a double: "); 
 scanf("%c%c%c%d%f%lf", &c1, &c2, &c3, &i, &x, &y); 
 printf("\nHere is the data that you typed in:\n"); 
 printf("%3c%3c%3c%5d%17e%17e\n", c1, c2, c3,i,x,y); 
 return 0; 
}

 
1.6 Flow of Control
 
              if (expr)  
                  statement
 
a = 1; 
if (b == 3) 
      a = 5; 
printf("%d", a);
 
Compund statement: 

if (a == 3) { 
   b = 5; 
   c = 7; 
}

 
           if (expr) 
                 statement1 
           else 
                 statement2
 
if (cnt == 0) { 
   a = 2; 
   b = 3; 
   c = 5; 
} 
else { 
   a = -1; 
   b = -2; 
   c = -3; 
} 
printf("%d", a+b+c);
 
while
#include <stdio.h> 

int main(void) 
{ 
  int  i = 1, sum = 0; 

  while (i <= 5) { 
     sum += i; 
     ++i; 
  } 
  printf("sum = %d\n", sum); 
  return 0; 
}

 
          for (expr1; expr2; expr3) 
                  statement; 

is equivalent to: 

         expr1; 
         while (expr2) { 
                 statement; 
                 expr3; 
         }

 
for (i = 1; i <= 5;  ++i) 
      sum += i;
 
/* Compute the minimum, maximum, sum, and average */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 int  i;
 double x, min, max, sum, avg;

 if(scanf("%lf", &x)!=1) {
    printf("No data found - bye!\n");
    exit(1);
 }
 min = max = sum = avg = x;
 printf("%5s%9s%9s%9s%12s%12s\n%5s%9s%9s%9s%12s%12s\n\n",
     "Count", "Item", "Min", "Max", "Sum", "Average",
     "-----", "-----", "---", "---", "---", "-------");
 printf("%5d%9.1f%9.1f%9.1f%12.3f%12.3f\n",
     1, x, min, max, sum, avg);
 for(i =2; scanf("%lf", &x) == 1; ++i) {
    if( x < min)
       min = x;
    else if (x > max)
       max = x;
    sum += x;
    avg = sum / i;
    printf("%5d%9.1f%9.1f%9.1f%12.3f%12.3f\n",
       i, x, min, max, sum, avg);
 }
 return 0;
}

 
1.7 Functions
 
function declaration:
double pow(double x, double y);
function prototype:
double pow(double, double);
 
#include < stdio.h>

float maximum(float x, float y);
float minimum(float x, float y);
void prn_info(void);

int main(void)
{
 int i, n;
 float max, min, x;

 prn_info();
 printf("Input n: ");
 scanf("%d", &n);
 printf("\nInput %d real numbers: ",n);
 scanf("%f", &x);
 max = min = x;
 for(i =2; i<=n; ++i) {
    scanf("%f", &x);
    max = maximum(max, x);
    min = minimum(min, x);
 }
 printf("\n%s%11.3f\n%s%11.3f\n\n",
    "Maximum value:", max,
    "Minimum value:", min);
 return 0;
}

float maximum(float x, float y)
{
 if (x > y)
    return x;
 else
    return y;
}

float minimum(float x, float y)
{
 if(x < y)
    return x;
 else
    return y;
}

void prn_info(void)
{
 printf("\n%s\n%s\n\n",
   "This program reads an integer value for n, and then",
   "processes n real numbers to find max and min values.");
}

 
CALL BY VALUE
 

#include < stdio.h>

   void try_to_change_it(int);

int main(void)
{
 int a = 1;

 printf("%d\n", a);   /* 1 is printed*/
 try_to_change_it(a);
 printf("%d\n", a);   /* 1 is printed again! */
 return 0;
}

void try_to_change_it(int a)
{
    a = 777;
}

 
1.8 Arrays, Strings, and Pointers
 
Arrays:

int a[3];

 
#include <stdio.h>

#define CLASS_SIZE 5

int main(void)
{
 int i, j, score[CLASS_SIZE], sum = 0, tmp;

 printf("Input %d scores: ", CLASS_SIZE);
 for(i = 0; i < CLASS_SIZE; ++i) {
    scanf("%d", &score[i]);
    sum += score[i];
 }
 for(i = 0; i < CLASS_SIZE - 1; ++i)  /*bubble sort*/
    for(j = CLASS_SIZE - 1; j > i; --j)
       if (socre[j-1] < score[j]) {  /*check the order*/
          tmp = score[j-1];
          score[j-1] = score[j];
          score[j] = tmp;
       }
 printf("\nOrdered scores:\n\n");
 for(i = 0; i < CLASS_SIZE; ++i)
    printf("   score[%d]=%5d\n", i, score[i]);
 printf("\n%18d%s\n%18.1f%s\n\n",
    sum, " is the sum of all the scores",
    (double)sum/CLASS_SIZE, " is the class average");
 return 0;
}

 
STRINGS:

/*Have a nice day! */

#include <ctype.h>
#include <stdio.h>

#define MAXSTRING  100

int main(void)
{
 char c, name[MAXSTRING];
 int i, sum = 0;

 printf("\nHi! What is your name? ");
 for(i=0; (c=getchar()) != '\n'; ++i) {
    name[i] = c;
    if(isalpha(c))
       sum += c;
 }
 name[i] = '\0';
 printf("\n%s%s%s\n%s",
    "Nice to meet you ", name, ".",
    "Your name spelled backwards is ");
 for(--i; i >=0; --i)
    putchar(name[i]);
 printf("\n%s%d%s\n\n%s\n",
    "and the letters in your name sum to ", sum, ".",
    "Have a nice day!");
 return 0;
}

 
POINTERS:

#include <stdio.h>
#include <string.h>

#define MAXSTRING   100

int main(void)
{
 char  c = 'a', *p, s[MAXSTRING];

 p = &c;
 printf("%c%c%c ", *p, *p +1, *p +2);
 strcpy(s, "ABC");
 printf("%s %c%c%s\n", s, *s + 6, *s +7, s+1);
 strcpy(s, "she sells sea shells by the seashore");
 p = s+14;
 for( ; *p != '\0'; ++p) {
    if (*p == 'e')
       *p = 'E';
    if (*p == ' ')
       *p = '\n';
 }
 printf("%s\n", s);
 return 0;
}

 
1.9 Files
 
#include <stdio.h>

int main(void)
{
  int c;
  FILE  *ifp;

  ifp = fopen("my_file", "r");

 
Three modes for a file
"r"    for read
"w"   for write
"a"   for append
 
#include <stdio.h>

int main(int argc, char *argv[])
{
   .....

 
/*Count uppercase letters in a file. */

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
 int c, i, letter[26];
 FILE  *ifp, *ofp;

 if(argc != 3) {
    printf("\n%s%s%s\n\n%s\n%s\n\n",
       "Usage:  ", argv[0], "  infile  outfile",
       "The uppercase letters in infile will be counted.",
       "The results will be written in outfile.");
    exit(1);
 }
 ifp = fopen(argv[1], "r");
 ofp = fopen(argv[2], "w");
 for(i = 0; i < 26; ++i)  /*initialize array to zero*/
    letter[i] = 0;
 while ((c = getc(ifp)) != EOF)
    if(c>='A' && c<= 'Z')  /*find uppercase letters*/
       ++letter[c-'A'];
 for(i = 0; i < 26; ++i) {   /*print results*/
    if (i %6 == 0)
       putc('\n', ofp);
    fprintf(ofp, "%c:%5d    ", 'A'+i, letter[i]);
 }
 putc('\n', ofp);
 return ;0;
}

 
1.10 Operating System Considerations
 
steps to be followed in writing and running a C program:
1. vi pgm.c
2. cc pgm.c
3. a.out
 
Interrupting a program:
ctrl-c
 
Redirection of the input and the output:

ls
ls > tmp
a.out
a.out < infile
a.out > outfile
a.out < infile > outfile