CS211a - Software Tools and Systems Programming

Exercise Hints to C Programming

 

Chapter 2:

Section 2.4

Exercise 5

For the value of π you can use 3.14 instead (or more digits for better precision).

 

Section 2.5

Exercise 7

Define π as a constant, for instance, 3.14.

 

Chapter 3:

Section 3.1

Exercise 1

d)  Pay attention to the difference between the f conversion and the g conversion.

Exercise 2

d) printf("%6.f", x);  or  printf("%6.0f", x);

 

Section 3.2

Exercise 3

(a) Equivalent.

(b) Equivalent.

(c) Not equivalent. If executed, “%f ”, the second one, will not go on to the rest of the program even when ENTER key is hit (because scanf ignores white-space characters, such as the space, horizontal and vertical tab, and new-line characters).

(d) Equivalent.

Exercise 7*

The values of i, x and j after the call will be 10, 0.3 and 5, respectively.  (scanf returns immediately after 5 is read because it has matched every conversion specification format with an input item, although not all of them.)

Exercise 8*

The values of x, i and y after the call will be 12.3, 45 and 0.6, respectively. (scanf returns immediately after 5 is read because it has matched every conversion specification format with an input item, although not all of them.)

 

Chapter 4:

Section 4.1

Exercise 2*

In both cases, the answer is ‘truncated’ because both of the operands are integers.

Section 4.3

Exercise 7*

a)     0; 2;

b)     4; 11, 6;

c)     0; 8, 7;

d)     3; 4, 5, 4;

Section 4.4

Exercise 9

a) ((a * b) – (c * d)) + e

b) ((a / b) % c) / d

c) (((– a) – b) + c) – (+ d)                    

d) ((a * (- b)) / c) - d

Section 4.5

Exercise 11

a) i += j;

is equivalent to i = i + j; After execution, j=2, i=3.

b) i--;

The value of i is fetched (but not used); i  is decremented by 1 afterwards, i.e., i=0.

c) i * j / i;

is equivalent to (i * j) / i; After execution, the value of the expression is computed and then discarded.

d) i % ++j;

j  is incremented by 1 (i=2) and then the value of the expression is computed and then discarded.

 

Chapter 5:

Section 5.1

Exercise 4*

i > j ? 1 : ( i == j ? 0 : -1 );

Section 5.2

Exercise 5

 

#include <stdio.h>

 

main()

{

  int n, d;

 

  printf("Enter a number:\n");

  scanf("%d", &n);

 

  if (n>=0 && n<=9)

    d=1;

  else if (n<=99)

    d=2;

  else if (n<=999)

    d=3;

  else

    d=4;

   

  printf("The number %d ", n);

  printf("has %d ", d);

  printf("digits\n");

 

  return 0;

}

 

Exercise 11*

The statement is legal, but it does not have the meaning that we expect (it does not test whether n is between 1 and 10). The expression

n >= 1 <= 10

is equivalent to

(n >= 1) <= 10

In other words, the expression first tests whether n is greater than or equal to 1; the 1 or 0 produced by this comparison is then compared to 10, which is why it still prints “n is between 1 and 10” when n is equal to 0.

Exercise 12*

The statement is legal, but it does not have the meaning that we expect (it does not test whether n is between 1 and 10). The expression

n == 1-10

is equivalent to

n == (1-10)

In other words, the expression first tests whether n is equal to (1-10=-9); the 1 or 0 produced by this comparison then controls whether the printf statement is executed, which is why it doesn’t print “n is between 1 and 10” when n is equal to 5.

Section 5.3

Exercise 16*

The output produced is

onetwo

This is because break statement is missing from the cases, which causes control to “fall through” to the next case after execution of the selected case.

 

Chapter 6:

Section 6.1

Exercise 2

 
#include <stdio.h>
 
main()
{
  int m,n,temp;
  
  printf("Enter two integers:\n");
  scanf("%d%d", &m, &n);
  
  if (m<n){  /* Swap m and n if m<n */
    temp=m;
    m=n;
    n=temp;
  }
  
  while (n!=0) {
    temp = m;   /* Save m before getting the remainder */
    m = n;
    n = temp % n;
  }
      
  printf("Greatest common divisor %d :\n", m);
  
  return 0;
}

 

 

Section 6.3

Exercise 9*

5432

Section 6.5

Exercise 15*

for (n = 0; m >0 ; m /=2, n++)

;

Exercise 16*

The call of printf isn’t inside the if statement, so it’s performed regardless of whether d is divisible by 2. To fix it, remove the semicolon after the parentheses of if statement.

if (n % 2 == 0)

  printf(“n is even\n”);

 

Chapter 7:

Section 7.2

Exercise 3

a) 010E2

Not legal.

b) 32.1E+5

Legal; floating-point.

c) 0790

Not legal. Octal constants contain only digits between 0 and 7.

d) 100_000

Not legal.

e)  3.978e-2

Legal; floating-point.

Section 7.3

Exercise 6

d) printf(c); is illegal

Exercise 7

a) ‘A’ has the value of 65

b) 0b1000001 is not a legal way of writing the number 65.

c) 0101 is the octal representation of 65.

d) 0x41 is the hexadecimal representation of 65.

Section 7.5

Exercise 13

The type of the expression  i/j + ‘a’ is int because when one integer is divided by another, the answer will be truncated into an integer. When ‘a’ is added to this integer, ‘a’ is converted to int also.

Exercise 17

a) c * i

has the of value of -3 and the type of int.

b) s + m

has the of value of 7 and the type of long int.

c) f / c

has the of value of 6.5 and the type of float.

d) d / s

has the of value of 3.75 and the type of double.

e) f - d

has the of value of -1.0 and the type of double.

f) (int) f

has the of value of 6 and the type of int.

 

Chapter 8:

Section 8.1

Exercise 2

 

#include <stdio.h>

#define TRUE 1

#define FALSE 0

 

typedef int Bool;

 

main()

{

  Bool digit_seen[10] = {0};

  int digit_rep[10] = {0};

  int i, digit;

  long int n;

 

  printf("Enter a number: ");

  scanf("%ld", &n);

 

  while (n>0) {

    digit = n%10;

    digit_rep[digit] +=1;

    n /= 10;

  }

 

  printf("Digits:\t\t");

  for (i=0;i<10;i++)

    printf("%-6d", i);

  printf("\n");

  printf("Occurrences:\t");

  for (i=0;i<10;i++)

    printf("%-6d", digit_rep[i]);

  printf("\n");

 

  return 0;

 

}

 

Exercise 7

 

#include <stdio.h>

#include <ctype.h>

 

#define N 100

 

main()

{

  int j, i=0;

  char ch, a[N];

 

  printf("Enter message: ");

 

  ch=getchar();

  while (ch!='\n') {

    a[i]=ch;

    i++;

    ch=getchar();

  }

 

  printf("In B1FF-speak: ");

  

  for (j=0; j<i; j++) {

    a[j]=toupper(a[j]);

    switch (a[j]) {

      case 'A': printf("4"); break;

      case 'B': printf("8"); break;

      case 'E': printf("3"); break;

      case 'I': printf("1"); break;

      case 'O': printf("0"); break;

      case 'S': printf("5"); break;

      default:  printf("%c", a[j]);

    }

  }

 

  for (j=1; j<10; j++) {

    printf("!");

  }

 

  printf("\n");

 

  return 0;

}

 

 

Section 8.2

Exercise 11

 

#include <stdio.h>

#define N 5

 

main()

{

  int i, j, row_total=0, column_total=0;

  int a[N][N];

 

  for (i=0; i<N; i++) {

    printf("Enter row %d: ", i+1); 

    for (j=0; j<N; j++) {

      scanf("%d", &a[i][j]);

    }

  }

 

  printf("Row totals: ");

  for (i=0; i<N; i++) {

    row_total =0;

   for (j=0; j<N; j++) {

      row_total += a[i][j];

    }

    printf(" %d", row_total);

  }

  printf("\n");

 

  printf("Column totals: ");

  for (i=0; i<N; i++) {

    column_total =0;

    for (j=0; j<N; j++) {

      column_total += a[j][i];

    }

    printf(" %d", column_total);

  }

  printf("\n\n");

   

  return 0; 

}

 

Exercise 13

 

/* 0--UP; 1--DOWN; 2--LEFT; 3--RIGHT */

 

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

 

#define N 10

#define NUM_LETTER 26

#define A 65

#define TRUE 1

#define FALSE 0

 

typedef int Bool;

 

main()

{

  char a[N][N];

  int i, j, k, direction;

  Bool premature=FALSE;

 

  for (i=0; i<N; i++) {

    for (j=0; j<N; j++) {

      a[i][j]='.';

    }

  }

 

  srand((unsigned) time(NULL));

 

  i=0; j=0; a[0][0]='A'; k=1;

  while (k<NUM_LETTER) {

    direction = rand() % 4;   

    switch (direction) {

      case 0: if (i-1>=0 && a[i-1][j]=='.') {i=i-1; a[i][j]=A+k; k++;}

              else if (i+1<N && a[i+1][j]=='.') {i=i+1; a[i][j]=A+k; k++;}

              else if (j-1>=0 && a[i][j-1]=='.') {j=j-1; a[i][j]=A+k; k++;}

              else if (j+1<N && a[i][j+1]=='.') {j=j+1; a[i][j]=A+k; k++;}

        else {premature=TRUE; goto done;}

              break;

      case 1: if (i+1<N && a[i+1][j]=='.') {i=i+1; a[i][j]=A+k; k++;}

              else if (i-1>=0 && a[i-1][j]=='.') {i=i-1; a[i][j]=A+k; k++;}

              else if (j-1>=0 && a[i][j-1]=='.') {j=j-1; a[i][j]=A+k; k++;}

              else if (j+1<N && a[i][j+1]=='.') {j=j+1; a[i][j]=A+k; k++;}

        else {premature=TRUE; goto done;}

              break;

      case 2: if (j-1>=0 && a[i][j-1]=='.') {j=j-1; a[i][j]=A+k; k++;}

              else if (j+1<N && a[i][j+1]=='.') {j=j+1; a[i][j]=A+k; k++;}

              else if (i-1>=0 && a[i-1][j]=='.') {i=i-1; a[i][j]=A+k; k++;}

              else if (i+1<N && a[i+1][j]=='.') {i=i+1; a[i][j]=A+k; k++;}

        else {premature=TRUE; goto done;}

              break;

      case 3: if (j+1<N && a[i][j+1]=='.') {j=j+1; a[i][j]=A+k; k++;}

              else if (j-1>=0 && a[i][j-1]=='.') {j=j-1; a[i][j]=A+k; k++;}

              else if (i-1>=0 && a[i-1][j]=='.') {i=i-1; a[i][j]=A+k; k++;}

              else if (i+1<N && a[i+1][j]=='.') {i=i+1; a[i][j]=A+k; k++;}

        else {premature=TRUE; goto done;}

              break;

    }

  }

 

done:     

  for (i=0; i<N; i++) {

    for (j=0; j<N; j++) {

      printf("%c ", a[i][j]);

    }

    printf("\n");

  }

 

  if (premature==TRUE)

    printf("Premature termination\n\n");

  else

    printf("Normal termination\n\n");

     

  return 0;

 

}

 

 

Chapter 9:

Section 9.1

Exercise 5

 
int num_digits(int n)
{
  int sum=0;
  while (n!=0) {
    n=n/10;
    sum += 1;
  }
  return sum;
}

 

Exercise 7

a) i = f(83, 12);

Legal. i has the value of 95.

b) x = f(83, 12);

Legal. x has the of value of 95.

c) i = f(3.15, 9.28);

3.15 and 9.28 will be truncated to integers, 3 and 9, respectively. i has the value of 12.

d) x = f(3.15, 9.28);

3.15 and 9.28 will first be truncated to integers, 3 and 9, respectively. x has the value of 12, although it has the type of float.

e) f(83, 12);

Legal, but the return value will be discarded.

Section 9.3

Exercise 9*

The output of the program is x=1, y=2. The values of x and y will not be swapped as we expect. The reason is that the parameters a and b in the function swap are not affected by the assignments inside the body of the function. As a result, the values of x and y remain unchanged after the function call.

Section 9.4

Exercise 11

To fix the error, put the return statement outside of the for loop.

Section 9.6

Exercise 14

 
int fact(int n)
{
  int product=1;
  while (n>0) {
    product *= n;
    n--;
  }
  return product;
}

 

Exercise 16*

 
#include <stdio.h>
 
void pb(int n)
{
  if (n!=0) {
    pb(n/2);
    putchar('0'+n%2);
  }
}
 
main()
{
  int n;
  printf("Input a number n:\n");
  scanf("%d", &n);
  pb(n);
  printf("\n");
  return 0;
  
}

 

This program returns the binary representation of an integer number.

Exercise 17

 
#include <stdio.h>
 
#define N 10
 
void selection_sort(int a[], int n);
 
main()
{
  int a[N], i;
  printf("Enter %d numbers to be sorted: ", N);
  for (i=0; i<N; i++)
    scanf(“%d”, &a[i]);
  
  selection_sort(a, N);
 
  printf(“In sorted order: ”);
  for (i=0; i<N; i++)
    printf(“%d”, a[i]);
  printf(“\n”);
  
  return 0;
  
}
 
void selection_sort(int a[], int n)
{
  int i, temp;
  if (n==1) return;
  for (i=0; i<n; i++)
    if (a[i]>a[n-1]) {
      temp = a[n-1];
      a[n-1] = a[i];
      a[i] = temp;
    }
  selection_sort(a, n-1);
}
 
 

 

 

Chapter 10:

Section 10.2

Exercise 1

 

#include <stdio.h>

#include <stdlib.h>

 

#define STACK_SIZE 100

#define TRUE 1

#define FALSE 0

 

typedef int Bool;

 

char contents[STACK_SIZE]; /* external */

int top=0;                 /* external */

int count=0;               /* external */

 

 

void make_empty(void);

Bool is_empty(void);

Bool is_full(void);

void push(char ch);

char pop(void);

void stack_overflow(void);

void stack_underflow(void);

 

 

main()

{

  char ch, popped_char;

 

  make_empty();

 

  printf("Enter a series of parentheses and/or braces: ");

 

  while ((ch = getchar()) != '\n') {

    if (ch == '(' || ch == '{')

      push(ch);

    else if (ch == ')' || ch == '}') {

      popped_char = pop();

      if ((popped_char == '(' && ch == ')') || (popped_char == '{' && ch == '}'))

        continue; 

      else {

        printf("Parentheses/braces are NOT nested properly.\n");

        exit(EXIT_FAILURE);

      }

    }

    else {

      printf("Input should be parentheses and/or braces.\n");

      exit(0);

    }

  }

 

  if (is_empty())

    printf("Parentheses/braces are nested properly.\n");

  else

    printf("Parentheses/braces are NOT nested properly.\n");

  if (count>0)

    printf("Parentheses/braces are NOT nested properly.\n");

   

  return(0);

}

 

 

void make_empty(void)

{

  top = 0;

}

 

Bool is_empty(void)

{

  return top == 0;

}

 

Bool is_full(void)

{

  return top == STACK_SIZE;

}

 

void push(char ch)

{

  if (is_full())

    stack_overflow();

  else

    contents[top++] = ch;

}

 

char pop(void)

{

  if (is_empty())

    stack_underflow();

  else

    return contents[--top];

}

 

void stack_overflow(void)

{

  printf("Stack overflow\n");

  exit(EXIT_FAILURE);

}

 

void stack_underflow(void)

{

  count++;

}Top of FormBottom of Form

 

 

Section 10.4

Exercise 2

(a)   The f function:  a, b, c

(b)  The g function:  a, d

(c)   The block in which e is declared:  a, d, e

(d)  The main function: a, f

 

Chapter 11:

Section 11.2

Exercise 1

(a)   and (g) are aliases for i.

Section 11.4

Exercise 3

 

void avg_sum(float a [], int n, float *avg, float *sum)

{

int i;

 

*sum = 0.0;

for (i = 0; i < n; i++)

    *sum += a[i];

*avg = *sum/n;

}

 

 

Exercise 4

 

#include <stdio.h>

 

void swap(int *p, int *q);

 

main()

{

  int x=1, y=2;

 

  swap(&x,&y);

  printf("x= %d, y= %d\n", x, y);

  return 0;

 

}

 

 

void swap(int *p, int *q)

{

  int temp;

 

  temp=*p;

  *p=*q;

  *q=temp;

}

 

 

 

Chapter 13:

Section 13.3

Exercise 3*

The value of i is 12;

The value of s is abc34;

The value of j is 56;

Section 13.4

Exercise 7*

The program prints: Grinch

Exercise 8*

(a) The value of f(“abcd”, “babc”) is 3;

(b) The value of f(“abcd”, “bcd”) is 0;

(c) In general, when passed two strings s and t, function f returns the number of characters that appear in both strings before the first character which appears in s but not in t occurs. 

Section 13.5

Exercise 10*

(a) strcpy(str, “tire-bouchon”);

The value of the string str is:  tire-bouchon

(b) strcpy(&str[4], “d-or-wi”);

The value of the string str is:  d-or-wi

(c) strcat(str, “red?”);

 The value of the string str is:  tired-or-wired?

 

 

Chapter 16:

Section 16.1

Exercise 1

 

#include <conio.h>

struct {

        int x,y;

}x;

struct{

        int x,y;

}y;

int main(int argc, _TCHAR* argv[])

{

        x.x=1;

        x.y=2;

        y.x=3;

        y.y=4;

        printf("x.x=%d,x.y=%d,y.x=%d,y.y=%d",x.x,x.y,y.x,y.y);

        getch();

        return 0;

}

 

 

Output:

x.x=1,x.y=2,y.x=3,y.y=4

 

 

 

Section 16.4

Exercise 10

#include <conio.h>

struct{

        float a;

        union{

               char b[4];

               float c;

               short int d;

        }e;

        char f[4];

}s;

int main(int argc, _TCHAR* argv[])

{

        printf("C compiler allocate %d bytes for char\n",sizeof(char));

        printf("C compiler allocate %d bytes for short int\n",sizeof(short

int));

        printf("C compiler allocate %d bytes for float\n",sizeof(float));

        printf("C compiler allocate %d bytes for s\n",sizeof(s));

        getch();

        return 0;

}

 

Output:

C compiler allocate 1 bytes for char

C compiler allocate 2 bytes for short int

C compiler allocate 4 bytes for float

C compiler allocate 12 bytes for s

 

 

Exercise 11

#include <conio.h>

enum{RECTTANGLE, CIRCLE};

struct point{

        int x,y;

};

struct shape{

        int shape_kind;

        struct point center;

        union{

               struct{

                       int length, width;

               }rectangle;

               struct{

                       int radius;

               }circle;

        }u;

}s;

int main(int argc, _TCHAR* argv[])

{

        s.shape_kind=RECTTANGLE;       //Legal as long as have the definiation of

enum{RECTTANGLE, CIRCLE};

        s.center.x=10;                        //Legal

        s.u.rectangle.length =25;      //s.length=25 illegal

        s.u.rectangle.width =8;               //legal

        s.u.circle.radius =5;          //s.u.circle=5  and s.u.radius are illegal

        getch();

        return 0;

}

 

 

Exercise 12

#include <stdio.h>

#define PI 3.1415

 

enum{RECTTANGLE, CIRCLE};

struct point{

       int x,y;

}p,*center;

typedef enum {FALSE, TRUE} Bool;

struct shape{

       int shape_kind;

       struct point center;

       union{

             struct{

                    int length, width;

             }rectangle;

             struct{

                    int radius;

             }circle;

       }u;

}s;

 

double AreaCompute(struct shape *pShape);

struct point *CenterCompute(struct shape *pShape);

void MoveShape(struct shape *pShape,int dx,int dy);

Bool isWithin(struct shape *pShape, struct point *pPoint);

 

 

double AreaCompute(struct shape *pShape){

       if (pShape ->shape_kind==RECTTANGLE){

             return pShape ->u.rectangle.length *pShape ->u.rectangle.width ;

       }

       else if (pShape->shape_kind==CIRCLE){

             return PI *pShape ->u.circle.radius *pShape ->u.circle.radius;

       }

       else

             return 0;

}

struct point *CenterCompute(struct shape *pShape){

       return &(pShape->center);

}

void MoveShape(struct shape *pShape,int dx,int dy){

       pShape->center.x+=dx;

       pShape->center.y+=dy;

}

Bool isWithin(struct shape *pShape, struct point *p){

       if (pShape->shape_kind==RECTTANGLE){

             if (( p->x > pShape->center.x - pShape->u.rectangle.width /2) && (p->x < pShape->center.x+pShape->u.rectangle.width /2) &&

                       ( p->y > pShape->center.y - pShape->u.rectangle.length /2) && (p->y < pShape->center.y+pShape->u.rectangle.length /2))

                    return TRUE;

             else  

                    return FALSE;

       }

       else if (pShape->shape_kind==CIRCLE){

             if (((p->x * p->x)+(p->y * p->y)) < (pShape->u.circle.radius * pShape->u.circle.radius))

                    return TRUE;

             else  

                    return FALSE;

            

       }

       else

             return FALSE;

 

}

int main()

{

 

       s.shape_kind=RECTTANGLE;  

       s.center.x=10;                  

       s.center.y=23;

       s.u.rectangle.length =25; 

       s.u.rectangle.width =8;         

       printf("area of s is %5.2f\n",AreaCompute(&s));

       s.u.rectangle.length =25; 

       s.u.rectangle.width =8;         

       s.u.circle.radius =5;

       printf("area of s is %5.2f\n",AreaCompute(&s));

 

 

       center=CenterCompute(&s);

       printf("Center of s is x=%d,y=%d\n",center->x,center->y);

       MoveShape(&s,2,3);

       printf("New s position is x=%d,y=%d\n",s.center.x,s.center.y);

      

 

       p.x=12;p.y=26;

       if(isWithin(&s,&p)==TRUE){

             printf("point lies within s");

       }

       else

             printf("point does not lie within s");

       getchar();

       return 0;

}

 

 

Output:

area of s is 200.00

area of s is 40.00

Center of s is x=10,y=23

New s position is x=12,y=26

point lies within s

 

Section 16.5

Exercise 16

#include <conio.h>

enum {

        FALSE,TRUE    

}b;

int i;

int _tmain(int argc, _TCHAR* argv[])

{

 

        b=FALSE;

        printf("b=%d\n",b);

        b=TRUE;

        printf("b=%d\n",b);

        i=b;

        printf("i=%d\n",i);

        i=2*b+1;

        printf("i=%d\n",i);

        getch();

        return 0;

}

 

 

Output:

b=0

b=1

i=1

i=3

 

 

 

Chapter 17:

Section 17.5

Exercise 8

 

void delete_list(struct node *list){

        for(struct node *p=list;p!=NULL;p=list){

               list =list->next;

               printf("%d,",p->value );

               free(p);

        }

 

}

 

 

Section 17.5

Exercise 8

 

#include "stdafx.h"

#include <conio.h>

#include <stdio.h>

int f1(int(*f)(int));

int f2(int i);

int f1(int(*f)(int)){

        int n=0;

        while((*f)(n)) n++;

        return n;

}

int f2(int i){

        return i*i+i-12;

}

void main(void)

{

        printf("Answer: %d\n",f1(f2));

        getch();

}

 

Output:

Answer: 3

 

Extra Exercises:

Implement a tree according to the representations in the course notes.

 

#include <stdlib.h>

struct s_node {

        int data;

        struct s_node * left;

        struct s_node * right;

};

 

 

/* declare the structure of a tree */

struct tree{              

     int data;

             struct tree *left;

     struct tree *right;

};

 

typedef struct tree treenode;

typedef treenode *b_tree;            

 

/* insert a node in the binary tree*/

b_tree insert_node(b_tree root,int node)

{

     b_tree newnode;

     b_tree currentnode;

     b_tree parentnode;

 

     newnode=(b_tree)malloc(sizeof(treenode));    

 

/* Allocate space for the new node */

     newnode->data=node;

     newnode->right=NULL;

     newnode->left=NULL;

 

     if(root==NULL)

          return newnode;

     else

     {   currentnode=root;

          while(currentnode!=NULL)

          {   parentnode=currentnode;

               if( currentnode->data>node)

                    currentnode=currentnode->left;

               else   currentnode=currentnode->right;

          }

          if(parentnode->data>node)

               parentnode->left=newnode;

          else  parentnode->right=newnode;

     }

     return root;

}

 

/* Build a binary tree */

b_tree create_btree(int *data,int len)

{

     b_tree root=NULL;

     int i;

 

     for(i=0;i<len;i++)

          root=insert_node(root,data[i]);

     return root;

}

 

/* inorder traversal */

void inorder(b_tree point){

     if(point!=NULL){

          inorder(point->left);

          printf("%d,",point->data);

          inorder(point->right);

     }

}

 

/* main function */

void main( )

{

     b_tree root=NULL;

     int index;

     int value;

     int nodelist[20];

     printf("\n input elements of tree(exit for 0):\n");

     index=0;

 

     /* read value in arrays */

     scanf("%d",&value);

 

     while(value!=0)

     {

          nodelist[index]=value;

          index=index+1;

          scanf("%d",&value);

     }

     /* build binary tree */

     root=create_btree(nodelist,index);

 

     /* inorder traversal */

     printf("\nThe inorder traversal result is :");

     inorder(root);

     printf("\n");

}

 

 

 

 

Input:

12

13

10

22

0 (marking the end of input)

 

Output:

The inorder traversal result is :10,12,13,22,

 

______________________________________________________________________________________________________________

 

 

 

UNIX System V

 

Chapter 5

Review Exercises

 

2.  $ sort numbers > phone_list

 

4.  $ cat part1 part2 > book

 or

 $ cat part [12] > book

 

5.  $ sort list | lp

 

6.  PID, Process Identification Number, gives the number of the process. When trying to abort a process that is running in the background, we    must use the kill command and to kill a selected process, corresponding PID must be given accordingly.

 

7.  a)  $ ls section*

     b)  $ ls section?

     c)  $ ls i*

     d)  $ ls section [13] ref [13]

 

 

Advanced Review Exercises

 

8.  To create a filename containing a space, surround the filename with double quotes.

 

10.    The command copies the content of answers to answers.0194

 

 

 

Chapter 10

Review Exercises

 

1.    $ PATH=/usr/ucb:/usr/bin:/usr/lbin:/usr/bin:/home/my/bin:

The file in /usr/ucb will be executed when you type whereis on the command line.

 

2.    You can use the command below:

$ ./program_name

The ./ explicitly tells the shell to look for an executable file in the working directory.

 

3.    The output for the program is shown below:

$person

$person

Single quotation and the backslash character can prevent the shell from substituting the value (jenny) of the variable (person).

 

4.    $ cat comm_arguments

number=1

for args

do

echo $args

if [ “$number” –eq 12 ]

    then

        exit 0

fi

number= `expr $number + 1`

          done

 

 

5.    Two ways to identify the PID of your login shell:

1)    $ echo $$

2)    $ ps –l

When you call ps with the –l option, it displays a long listing of information about each process. The line of the ps display with sh in the COMMAND column refers to the process running the shell.

 

 

6.    After modification:

$cat  journal

:

# journal: add journal entries to the file

# $HOME/journal

 

file=$HOME/journal

 

# Check for existence of file:

ls “$file” 2> /dev/null | grep “$file” > /dev/nul

if [ $? != 0 ]

then

    echo “$file not found” 1>&2

    exit 1

     fi

    

# Check for write permission

if [ ! -w “$file” ]

then

    echo “$file: need write permission” 1>&2

     fi

 

date >> $file

echo “Enter name of person or group:  \c”

read person

echo “$person” >> $file

echo >> $file

cat >> $file

echo “---------------------------------------------” >> $file

echo >> $file

 

     In order to be able to execute the script, you need to use chmod to add execute permission.

 

 

7.    Two ways you can execute a shell script when you do no have the execute access permission:

1)    Use chmod utility to change the access privilege associated with a file. For example,

$ chmod u+x script_name

will give the owner execute permission.

2)    Use the sh command to exec a shell to run the script directly. However, you do need read permission.

$ sh script_name

 

8.    The advantages of using a shell function instead of a shell script include:

1)    Shell function can be accessed more quickly than a shell script;

2)    The shell preprocesses (parses) a function so that it starts up more quickly than a script;

You can either declare the shell function in your .profile file or enter the function directly from the command line (the shell executes a shell function in the same shell that called it).

 

 

 

Advanced Review Exercises

 

9. The go_home script never receives the value of old_dir from report_dir. As a result, go_home displays nothing for “Last working directory: 

     To correct it, put the following at the very beginning of report_dir:

     export old_dir

 

10. The output of the program is as follows:

This is line 1.

This is line 2. \n

This is line 1. This is line 2.

 

For the first echo “$twoliner\n”, the double quotation marks turn off the special meaning of \n, but preserve the spacing between the first line and the second line.

For the second echo $twoliner, the newline character was interpreted as a single space instead.

 

 

Extra Exercises

 

1.    Write a shell script to achieve the following:

Make a copy of all files with the .f extension, and give the new files the same names as the original files but with .sav appended at the end.

 

Solution:

# Make a copy of each file with the .f extension.

# New files have same names as originals with .sav

# appended on the name.

ext=.f

files = `ls *$ext`

for file in $files

do

    echo "Copying $file "to" $file.sav

    cp $file $file.sav

done

exit 0

 

 

2.    Write a script that will return the number of arguments on the command line.

Solution:

          echo "There were $# arguments on the command line."

          exit 0

 

 

3.    Write a series of scripts that will count the number of arguments on the command line, first using the for statement, then the while and finally the until statement. (Three scripts).

Script 1: 

          NUM=0

          for i in $*

          do          

              NUM=`expr $NUM + 1`

          done

          echo "There were $NUM arguments."

          exit 0

 

Script 2:

          NUM=0

          while test $# -gt 0

          do

              NUM=`expr $NUM + 1`

             shift              

          done

          echo "There were $NUM arguments."

          exit 0

 

Script 3:

          NUM=0

          until test $# -eq 0

          do                 

              NUM=`expr $NUM + 1`

             shift

          done

          echo "There were $NUM arguments."

          exit 0

 

 

4.    Given a file of numbers (one per line), write a script that will find the lowest and highest number.

Solution:

          # script to print lowest and highest number from a file.

          #

          if test $# -eq 0

          then

             echo usage: minmax filename

             exit 1

          fi

 

          sort -n numbers > sorted.numbers

 

          read SMALLEST < sorted.numbers

          LARGEST=`tail -1 sorted.numbers`

 

          rm sorted.numbers

 

          echo " "

          echo "The smallest number is $SMALLEST."

          echo "The largest number is $LARGEST."

          echo " "

          exit 0

 

This script should contain code to check if sorted.numbers exists. It is left to the reader to add that code (as described in review exercise 6).

 

 

5.    Write a script that would recognize if a word entered from the keyboard started with an upper or lower case character or a digit. Use the "case" statement.

This makes use of pattern matching within the case statement.

     Solution:

echo -e "Enter a word or number: \c"; read ANS

case $ANS in

    [a-z]*) echo "lower case"

          ;;

    [A-Z]*) echo "upper case"

        ;;

    [0-9]*) echo "number."

          ;;

    *) echo "not upper, lower, or number."

esac

exit 0

 

 

6.    This uses an infinite while loop and the break command.

Solution:

FILE="myfile"

if test -f $FILE

then

   echo "File already exist."

else

   echo "creating myfile."

   touch myfile

   while :

   do

       echo -e "would you like to erase it? \c"

       read ANS

       case $ANS in

          [yY] | [yY][eE][sS])  echo "Fine, then we'll erase it."

                   rm myfile

                   break

                   ;;

          [nN] | [nN][oO]) echo "OK we will keep it, then."

                   break

                   ;;

          *) echo "You must enter a yes or no!"

       esac

   done

fi

exit 0

 

 

7.    Write a Bourne shell script to automatically compile your Fortran or C programs (prog.f or prog.c). The script should, if a name is not provided in the command line, prompt the user to input the program to be compiled. Hint: use awk -F. 'print $1'.

Solution:

          if test $# -eq 0

          then

              echo " "

              echo "Enter program to be compiled."

             read PROGRAM

          else

              PROGRAM=$1

          fi

 

          NAME=`echo $PROGRAM | awk -F. '{print $1}'`

          make $NAME