---
# System prepended metadata

title: 110-1 C HOW TO PROGRAM
tags: [程式設計（一）]

---

---
title: 110-1 C HOW TO PROGRAM
---
# Chapter 1

## What are the default devices of standard input stream, standard output stream, and standard error stream? 
* Standard Input Stream (stdin): <font color=rainbow>keyboard</font>
	* Certain C functions take their input from this stream, which is normally the keyboard. 
	* 標準輸入是指輸入至程式的資料（通常是檔案）。
* Standard Output Stream (stdout): <font color=rainbow>screen</font>
	* Programs often output data to this stream, which is normally the screen. 
	* 標準輸出是指程式寫輸出資料的串流。
* Standard Error Stream (stderr): <font color=rainbow>screen</font>
	* Program output the error message to such stream, which is normally the screen. 
	* 標準錯誤輸出是另一輸出串流，用於輸出錯誤訊息或診斷。

## Give the command to compile the source file *myfile.c* to the executable *myfile.exe*. 
gcc my_file.c -o my_file.exe 

## Show the typical C program-development environment. 
C programs typically go through six phases to be executed. These are:
1. <font color=rainbow>edit</font> (create program),
2. <font color=rainbow>preprocess</font> (preprocess the code),
3. <font color=rainbow>compile</font> (compile and get the object code),
4. <font color=rainbow>link</font> (link the object with libraries and create executable file),
5. <font color=rainbow>load</font> (put the program to memory) and
6. <font color=rainbow>execute</font> (take each instruction and execute). 

# Chapter 2

## Write a complete C program to display the following content: Hello Midterm Exam! 
```c=
#include<stdio.h>

int main(void)
{
	printf("Hello Midterm Exam!\n");
}
```

## How to write single-line and multi-line comments in your C code? 
* Single-line comments: 
	```
	//... 
	```
* Multi-line comments: 
	```
	/*...*/ 
	```
    
## What is the starting point to run in every C program? 
Every program in C begins executing at the <font color=rainbow>function main</font>. 

## Give the meaning of void in the parentheses of function main. 
The void in parentheses here means that main <font color=rainbow>does not receive any information</font>. 

## What is the functionality of escape sequence? 
* The backslash (\\) is called an escape character. 
* When encountering a backslash in a string, the compiler looks ahead at <font color=rainbow>the next character</font> and combines it with the backslash <font color=rainbow>to form an escape sequence</font>. 
* 無法直接在代碼中寫出所要的字元時採用的，以多個字元的有序組合來表示原本需要的字元。
* 使用反斜槓「\」來引入一個跳脫序列，如「\r」表示Enter、「\n」表示換行、「\t」表示水平制表符等。

## How does C compiler handle white space? How can we use such property to improve our program?
* Normally <font color=rainbow>ignored</font> by the compiler. 
* Use blank lines, space characters and tab characters to <font color=rainbow>make programs easier to read</font>.

## Give the definition of a legal identifier.
* <font color=rainbow>Any variable namer</font> in C is a valid identifier.
* An identifier is a series of characters consisting of letters, digits and underscores (_) that <font color=rainbow>does not begin with a digit</font>.

## Give a complete C program to add three integers input by a user, and output the result to screen.
```c=
#include<stdio.h>

int main(void)
{
	int x, y, z;

	scanf("%d%d%d", &x, &y, &z);
    
        int sum;
        sum = x + y + z;
    
	printf("%d\n", sum); 
}
```

## What are the two tasks of C preprocessor? 
* header files
* macro expansions
* conditional compilation
* line control
> 2? 3? 4? HOW MANY TASKS???

## What is the meaning of ampersand (&) in scanf?
* Begins with an ampersand (&) — called <font color=rainbow>the address operator</font> in C — followed by the variable name.
* The &, when combined with the variable name, <font color=rainbow>tells scanf the location (or address) in memory at which the variable value is stored</font>.
* The computer then stores the value that the user enters at that location.
* 向函式傳遞物件的地址

## What is the meaning of percent sign (%) in printf and scanf? 
* The % is treated as a special character that <font color=rainbow>begins a conversion specifier （轉換說明）</font>. 
* 把隨後對應的函式參數轉換為相應的格式輸出

## What are the three properties of each variable? 
1. Name
2. Type
3. Value

## What is defined by the rules of operator precedence? What is defined by the operator associativity? 
* C applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those in algebra:
	* Operators in expressions contained within pairs of <font color=rainbow>parentheses</font> are evaluated first.
	* <font color=rainbow>Multiplication(*), division(/) and remainder(%)</font>  operations are applied next.  
	* <font color=rainbow>Addition(+) and subtraction(-) operations</font>  are evaluated next. 
	* <font color=rainbow>The assignment operator(=)</font> is evaluated last. 
* When we say evaluation proceeds from left to right, we’re referring to the associativity of the operators.
* [Precedence and order of evaluation MSVC表格](https://docs.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-170)


# Chapter 3

## What are the two components in a pseudocode? 
* Action statements
* Decision statements 

## What are the three control structures and the corresponding seven control statements in C? 
All programs can be written in terms of sequence, selection and iteration structures. 
* Sequence
* Three types of selection 
	* if (single-selection) statement
	* if…else (double-selection) statement
	* switch (multiple-selection) statement 
* Three types of iteration(repetition) 
	* while
	* do…while
	* for 

## Give the four rules for forming structured programs. 
![](https://i.imgur.com/D28aLiV.png)

## What are the two rules of connecting control statements? Using the simplest flow chart to explain the two ways of connection. 
* Control-statement stacking
  ![](https://i.imgur.com/b6Fp8qR.png)
* Control-statement nesting
  ![](https://i.imgur.com/cVyYs7G.png)
  
## Give the statements to print “Passed” if the student’s grade is greater than or equal to 60 and “Failed” if the student’s grade is less than 60.
```c=
#include<stdio.h>

int main(void)
{
  int grade;
	
  scanf("%d", &grade);

  if (grade >= 60)
	  printf("Passed\n");
  else
	  printf("Failed\n");
}
```

## Use conditional operator to print “Passed” if grade is greater than or equal to 60 and print “Failed”, otherwise. 
* ```conditional operator=
  puts( grade >= 60 ? "Passed" : "Failed" );
  ```
* ```conditional operator=
  grade >= 60 ? puts( "Passed" ) : puts( "Failed" );
  ```

## List the values of x, y, and z after performing the following statement (9%) 
```
int x = 4, y, z; 
y = ++x; 
z = x++; 
```
```c=
#include<stdio.h>

int main(void)
{
  int x = 4, y, z;
	
  while (x == 4){
	  y = ++x;    // x = 4 + 1 = 5; y = x = 5
	  z = x++;    // z = x = 5; x = 5 + 1 = 6
	  printf("%d %d %d", x, y, z);    // 6 5 5
  }
}
```

## Given the statements “double x = 4.467”, what are the results of the following statements?a)printf(“%f”, x); b) printf(“%.2f”, x) 
```c=
#include<stdio.h>

int main(void)
{
  double x = 4.467;
  printf( "%f\n", x);     // 4.467000
  printf( "%.2f\n", x);   // 4.47
}
```

## Considering the following scenario: if a is greater than or equal to b than c is zero; otherwise, c is one. 
* Write the corresponding C statements using double selection statement. 
  ```c=
  if (a >= b)
	  c = 0;
  else
	  c = 1;
	```
* Write the corresponding C statements using conditional operator.
  ```conditional operator=
  puts( a >= b ? c = 0 : c = 1);
  ``` 
  
## Write a complete C program to sum up ten floating-point numbers entered from keyboard. 
```c=
#include<stdio.h>
int main(void)
{
  unsigned int counter = 0;
  float sum = 0;

  while (counter < 10){
	  float num;
	  printf("Enter the %d number: ", counter + 1);
	  scanf_s("%f", &num);
	  sum = sum + num;
	  counter = counter + 1;
  }    //end while
	  printf("The sum is %f.", sum);
}    //end function main
```

## Write a complete C program to sum up an arbitrary number of floating-point values entered from keyboard. 
```c=
#include<stdio.h>

int main(void)
{
  unsigned int counter = 0;
  float value;

  printf("Enter value, -1 to end: ");
  scanf_s("%f", &value);
  float sum = 0;
  while (value != -1) {
	  sum = sum + value;
	  counter = counter + 1;
	  printf("Enter value, -1 to end: ");
	  scanf_s("%f", &value);
  }    //end while
  if (value == -1)
  printf("Sum is %f", sum);
}    //end function main
```

## Distinguish between preincrementing(predecrementing) and postincrementing(postdecrementing) a variable. 
*  If increment or decrement operators are placed <font color=rainbow>before a variable</font>, they’re referred to as the <font color=rainbow>preincrement or predecrement operators</font>, respectively. 
*  If increment or decrement operators are placed <font color=rainbow>after a variable</font>, they’re referred to as the <font color=rainbow>postincrement or postdecrement operators</font>, respectively.
*  Preincrementing and Postincrementing
    *  指++、--的運算子擺在運算元的前面，此時先針對運算元作++、--的動作後再執行整個運算式的敘述。
*  Postincrementing and Postdecrementing
    *  指++、--的運算子擺在運算元的後面，此時先針對運算元作敘述，++、--的動作後再針對運算元作++、--的動作。


# Chapter 4

## Show problem of following code, and show how to fix it. Suppose x, y, z are declared as integers.
```c=
int x, y, z;

if ( x < 2 )
	if ( y > 4 )
		z = x + y;
else
	z = x - y;
```

## Write a complete C program to sum up the odd integers from 1 to 100.
```c=
int x;
int sum = 0;

for (x = 1; x <= 100; x++){
  if (x % 2 != 0){
	  sum = sum + x;
  }
}

printf("%d", sum);  // sum = 2500
```

## Write C code for the following scenarios using logical operators.
1. If x is greater than 5 or x is less than 3 then set z to zero
```c=
int x, z;

scanf("%d", &x);

if (x > 5 || x < 3){
	z = 0;
}
```  
2. If x is greater than 3 and y is less than 5 then set z to one
```c=
int x, y, z;

scanf("%d %d", &x, &y);


if (x > 3 && y < 5){
	z = 1;
}
``` 

## Write C code to print the integers from 1 to 20 using for, while, and do...while statements.
* ```c=
  int x;

  for (x = 1; x <= 20; x++){
	  printf("%d ", x);
  }
  ```
* ```c=
  int x = 1;

  while (x <= 20){
	  printf("%d ", x);
	  ++x;
  }
  ```
* ```c=
  int x = 1;

  do {
	  printf("%d ", x);
  } while (++x <= 20);
  ```

## How to use the return value of scanf to ensure secure C programming? Use scanf("%d %d", &x, &y)to explain the method.
```c=
scanf("%d %d", &x, &y); // read two integers
```
* If the input is successful, scanf will return 2, indicating that two values were read.
* If the user enters a string for the first value, scanf will return 0 and neither number 1 nor number 2 will receive a value.
* If the user enters an integer followed by a string, scanf will return 1 and only number 1 will receive a value.

## What is the function of rules of operator precedence? What is operator associativity? Explain the problem of order of evaluation of operands in C.
* The operators are shown top to bottom in decreasing order of precedence.
* The second column indicates the associativity of the operators at each level of precedence.
![](https://i.imgur.com/0P8im0s.png)

## Explain why controlling counting loops with floating-point values is dangerous.
Floating-point vlaues are not precise enough, because you can't really check a float number for equality.

## What will occur if a case in the switch selection statement has no break?
Forgetting a break statement when one is needed in a switch statement is a logic error.

## Explain the effect of short-circuit evaluation in C.
An expression containing && or || operators is evaluated only until truth or falsehood is known.

## What will happen if a programmer intentionally creates a for-loop with the for header: for(; ;)?
An infinite loop.

## What are lvalueand rvalue? What will happen if we assign value to an rvalue?
* Variable names are said to be lvalues(for “left values”) because they can be used on the left side of an assignment operator.
* Constants are said to be rvalues(for “right values”) because they can be used on only the right side of an assignment operator.
* lvalues can also be used as rvalues, but not vice versa.

## Give x = 12, y = 6, and z = 1. What is the output of x, y, and z after executing the following code?
```c=
int x = 12, y = 6, z = 1;

if (( x > 6 ) || ( y = 1) ) {
  z = 4;	//x = 12, y = 6, z = 4
}
```

## What is off-by-one error? (OBOE)
* It uses the loop-continuation condition counter <= 10.
* If you incorrectly wrote counter < 10, then the loop would be executed only 9 times.


# Chapter 5

## What is argument coercion? When will it happen?
* The forcing of arguments to the appropriate type.
> Argument Coercion 引數的強制轉換[color=yellow]
>> 若主程式碼呼叫的函式參數和函式設定的引數類型不同，類型會強制轉換[color=green]

## What are the three ways of returning control back to the calling function?
* If the function <font color=yellow>does not return</font> a result, control is returned simply when 
    * <font color=rainbow>the function-ending right brace is reached</font>, or 
    * <font color=rainbow>by executing the statement return</font>;
* If the function <font color=yellow>does return</font> a result, the statement <font color=rainbow>return expression</font>; returns the value of expression to the caller. 

## Briefly describe the two methods passed by value and passed by reference when passing arguments.
* When arguments are <font color=yellow>passed by value</font>, <font color=rainbow>a copy of the argument’s value</font> is made and<font color=rainbow> passed</font> to the called function.<font color=yellow> Pass-by-value</font> should be used whenever the called function <font color=rainbow>does not need to modify the value</font> of the caller’s original variable. 
* Changes to the copy do <font color=rainbow>not</font> affect an original variable’s value in the caller.
* When an argument is <font color=yellow>passed by reference</font>, the caller <font color=rainbow>allows</font> the called function <font color=rainbow>to modify</font> the original variable’s value.
* <font color=yellow>Pass-by-value</font> should be used whenever the called function <font color=rainbow>does not need to modify the value</font> of the caller’s original variable. 
> Pass by value (Call by value)[color=yellow]
>> 實際參數和形式參數占用不同的記憶體空間，因此形式函數的變動不會影響到實際參數。[color=yellow]

> Pass by reference (Call by reference)[color=green]
>> 實際參數和形式參數占用相同的記憶體空間，因此當形式函數更動時會影響到實際參數。[color=green]

## What are the two main functions of function call stack and stack frame when calling functions?
PLEASE HELP

> Call Stack[color=yellow]
>> 指存放某個程式的正在執行的函式的資訊的棧[color=yellow]

> Stack Frame[color=green]
>> call stack 由 stack frames 組成，每個 stack frame 對應於一個未完成執行的函式。[color=green]

## Explain the behavior of the following statement:<br>int c = a + rand() % b;
PLEASE HELP

## What will happen when a called function completes its task?
Returns to the calling function when its task is completed.

## Write a function which returns the minimum of four characters.
```c=
#include<stdio.h>

int minimum(int x, int y, int z)
{
	int min = x;

	if (y < min)
		min = y;

	if (z < min)
		min = z;

	return min;
}

int main(void)
{
	int number1, number2, number3;

	printf("%s", "Enter three integers: ");
	scanf("%d%d%d", &number1, &number2, &number3);

	printf("Minimum is: %d\n", minimum(number1, number2, number3));
}
```

## How to round a floating-point value x to the hundred and thousand position, and store it to an integer y?
* Round to the hundredths position
    ```
    y = floor (x / 100 + 0.5) * 100
    ```
* Round to the thousand position
    ```
    y = floor (x / 1000 + 0.5) * 1000
    ```

## Write a function to calculate and returns the final position of an object with three parameters speed $v$, acceleration $a$, and time $t$ using the following formula: $s = vt + \frac{1}{2}𝑎𝑡^2$. Remember to use appropriate data type.
```c=
float FinalPosition(float v, float a, int t)
{
	float s = (v * t) + (a * t * t) / 2; 

	return s;
}
```

## Unexpectedness is important in many applications. Please give a method in C to randomize your random number generator which may change the random sequence over time.
* ```c=
  #include<stdio.h>
  #include<stdlib.h>    // Required header for rand
  
  int FindRandom(int range)    // 1 ~ range
  {
      // scaling factor = range + 1
      
       int result = (rand() % (range + 1)) + 1 
      // + 1 to shif the range from 0 ~ (range - 1) t0 1 ~ range
  
      return result;
  }
  ```
* ```c= 
  #include <stdio.h>
  #include <stdlib.h>    // Required header for rand and srand
  #include <time.h>    // Required header for time

  int FindRandom(int range)
  {
      srand(time(NULL));

      int result = (rand()%(range + 1))+1;

      return result;

  }
  ```


## How to round a floating-point value x to the hundred and thousand position, and store it to an integer y?
* Round to the hundredths position
    ```c=
    y = floor (x / 100 + 0.5) * 100
    ```
* Round to the thousand position
    ```c=
    y = floor (x / 1000 + 0.5) * 1000
    ```
> The function floor(x) returns the largest integer less than x. 


## ADD - A Game of Chance: Craps 花旗骰 (Introducing "enum 枚舉") 
```c=
// Simulating the game of craps.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // contains prototype for function time

// enumeration constants represent game status
enum Status { CONTINUE, WON, LOST }; 
/* The constant CONTINUE has the value 0, WON has the value 1 and 
LOST has the value 2. */

int rollDice(void); // function prototype

int main(void)
{
    // randomize random number generator using current time
    srand(time(NULL));

    int myPoint; // player must make this point to win
    enum Status gameStatus; // can contain CONTINUE, WON, or LOST    
    int sum = rollDice(); //first roll of the dice

    // determine game status based on sum of dice
    switch (sum) {

    // win on first roll
    case 7: // 7 is a winner
    case 11: // 11 is a winner
        gameStatus = WON;
        break;

    // lose on first roll
    case 2: // 2 is a loser
    case 3: // 3 is a loser
    case 12: //12 is a loser
        gameStatus = LOST;
        break;

    // remember point
    default:
        gameStatus = CONTINUE; // player should keep rollong
        myPoint = sum; // remember the point
        printf("Point is %d\n", myPoint);
        break; // optional
    }

    // while game not complete
    while (CONTINUE == gameStatus) { // player should keep rolling
        sum = rollDice(); // roll dice again

        // determine game status
        if (sum == myPoint) { // win by making points
            gameStatus == WON;
        }
        else {
            if (7 == sum) { // lose by rolling 7
                gameStatus = LOST;
            }
        }
    }

    // display won or lost message
    if (WON == gameStatus) { // did player win?
        puts("Player wins");
    }
    else { // player lost
        puts("Player loses");
    }

    return 0;
}

// roll dice, calculate sum and display results
int rollDice(void)
{
    int die1 = 1 + (rand() % 6); // pick random die1 value
    int die2 = 1 + (rand() % 6); // pick random die2 value

    // display results of this roll
    printf("Player rolled %d + %d = %d\n", die1, die2, die1 + die2);
    return die1 + die2; // return sum of dice    
}
```


## Storage class influences the storage duration and scope of a variable. Give a definition for each of storage duration and scope. 
1. Storage Durations: 
    1. Automatic storage duration 
        * Lifetime：函數或者{}區塊內
        * Default Value: nothing
    2. Static storage duration 
        * Lifetime：程式執行期間
        * Default Value: 0
2. Scope: 
    1. Function Scope
        * 自定義位置至函數結束，只適用label
    2. File Scope
        * 自定義位置至檔案結束
    3. Block Scope
        * 自定義位置至定義的函數或者{}區塊結束
    4. Function-Prototype Scope.
        * 自定義位置至函數原型結束
3. Linkage: 
> [C語言變數 Storage Class](https://magicjackting.pixnet.net/blog/post/71949519)[color=lightblue]


## Consider the following code:
```c=
#include <stdio.h>
int x = 10; // (a) for x
int add(int x, int y); // (b) for add, (c) for x 
int main(void)
{
   double x = 2.34, y = 4.56; // (d) for x
   if ( (x == 2) || (y == 5) ) {
      int z = add(x, y); // (e) for z
   }
   int w = add(x, y);
   //here
   return 0;
}
int add(int num1, int num2) {
   static int base; // (f) for base
   base++;
   x = num1 + num2 + base;
   return x;
}
```
1. What is the final value of x, y, z and w at line 11?

|  | x | y | z | w |
| -------- | -------- | --- | --- | -------- |
| Line 11 | 2.340000 | 4.560000 | undefined | 7 |


2. Give the storage class (auto, static, extern, register), storage duration (automatic, static) and scope (function, function prototype, file, block) of identifiers in lines 2, 3, 6, 8, and, 15.

|  | Storage Class | Storage Duration | Scope |
| -------- | -------- | --- | -------- |
| 2 | external | automatic | file |
| 3 | register | automatic | function prototype |
| 6 | automatic | automatic | block |
| 8 | automatic | automatic | block |
| 15 | static | static | function |
> UNSURE[color=red]


## ADD - Scope Rules
```c=
//  scoping
#include <stdio.h>

void useLocal(void);    // function prototype
void useStaticLocal(void);    // function prototype
void useGlobal(void);    // function prototype

int x = 1;  // global variable

int main(void)
{
    int x = 5;  // local variable to main

    printf("local x in outer scope of main is %d\n", x);    // 5

    {   // start new scope
        int x = 7;  // local variable to new scope

        printf("local x in inner scope of main is %d\n", x);    // 7
    }   // end new scope

    printf("local x in outer scope of main is %d\n", x);    // 5

    useLocal(); // automatic local
    useStaticLocal();   // static local
    useGlobal();    // global
    useLocal(); // reinitializes automatic local
    useStaticLocal();   // retain its prior value
    useGlobal();    // retains its prior value

    printf("\nlocal x in main is %d\n", x); // 5

    return 0;
}

//  useLocal reinitializeslocal variable x during each call
void useLocal(void)
{
    int x = 25; // intitialized each time useLocal is called

    printf("\nlocal x in useLocal is %d after entering useLocal\n", x);    // 25
    ++x;
    printf("local x in useLocal is %d before exiting useLocal\n", x);    // 26
}

//  useStatical initializes static local variable x only the first time
//  the function is called; value of x is saved between calls to this
//  function
void useStaticLocal(void)
{
    // initialized once
    static int x = 50;

    printf("\nlocal static x is %d on entering useStaticLocal\n", x);
    ++x;
    printf("local static x is %d on exiting useStaticLocal\n", x);
}

// function useGlobal modifies global variable x during each call
void useGlobal(void)
{
    printf("\nglobal x is %d on entering useGlobal\n", x);
    x *= 10;
    printf("global x is %d on exiting useGlobal\n", x);
}
```
```
local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5

local x in useLocal is 25 after entering useLocal
local x in useLocal is 26 before exiting useLocal

local static x is 50 on entering useStaticLocal
local static x is 51 on exiting useStaticLocal

global x is 1 on entering useGlobal
global x is 10 on exiting useGlobal

local x in useLocal is 25 after entering useLocal
local x in useLocal is 26 before exiting useLocal

local static x is 51 on entering useStaticLocal
local static x is 52 on exiting useStaticLocal

global x is 10 on entering useGlobal
global x is 100 on exiting useGlobal

local x in main is 5
```


## The greatest common divisor (GCD) of two numbers x and y is x if y = 0; otherwise it equals to the GCD of y, and x mod y. Write the recursive function for finding the GCD of two numbers.
```c=
int gcd(int x, int y)
{
    if ( y == 0 )
        return x;
    else
        return gcd(y, x % y);
}
```
```c=
#include <stdio.h>

int gcd(int x, int y)
{
    if (y == 0)
        return x;
    else
        return gcd(y, x % y);
}

int main()
{
    int a, b;

    printf("Enter two numbers: ");

    scanf("%d %d", &a, &b);    // 98 56
    
    printf("GCD of %d and %d is %d.", a, b, gcd(a, b));
    // GCD of 98 and 56 is 14.

    return 0;
}
```


## ADD - Recursion: Fibonacci Series
```c=
// Recursive fibonacci function
#include <stdio.h>

unsigned long long int fibonacci(unsigned int n);

int main(void)
{
	unsigned int number; // number input by user

	// obtain integer from user
	printf("%s", "Enter an integer: ");
	scanf("%u", &number);

	// calculate fibonacci value for number inpur by user
	unsigned long long int result = fibonacci(number);

	// display result
	printf("Fibonacci(%u) = %llu\n", number, result);

	return 0;
}

// Recursive definition of function fibonacci
unsigned long long int fibonacci(unsigned int n)
{
	// base case
	if (0 == n || 1 == n) {
		return n;
	}
	else { // recursive step
		return fibonacci(n - 1) + fibonacci(n - 2);
	}
}
```
```c=
//  Recursion using Tail recursion: Fibonacci
unsigned long long int tailfibonacci(int n, unsigned long long fib1, unsigned long long int fib2)
{
	// base case
	if (n > 0) {
		return tailfibonacci(n - 1, fib2, fib1 + fib2);
	}
	else { // recursive step
		return fib1;
	}
}
```
```
Enter an integer: 0
Fibonacci(0) = 0

Enter an integer: 1
Fibonacci(1) = 1

Enter an integer: 2
Fibonacci(2) = 1

Enter an integer: 3
Fibonacci(3) = 2

Enter an integer: 10
Fibonacci(10) = 55

Enter an integer: 20
Fibonacci(20) = 6765

Enter an integer: 30
Fibonacci(30) = 832040

Enter an integer: 40
Fibonacci(40) = 102334155
```


## Explain the behavior of the following code:
```c=
#include <stdio.h>
int main(void)
{
    int c;
    if ( ( c = getchar() ) != EOF ) {
        main();
        printf("%c", c);
    }
    return 0;
}
```
1. The OS calls the function main at first.
    *  If the user input character is not EOF, then the other main function is called.
2.  The second called main function will waits the user input like the first main function.
    1. The last called main function which encounters EOF returns first, and then the second last one, and so forth.
    2. The input character will be output before the main function return.
3. Therefore, the input: abcde has the output: edcba


## What does the following recursive function do? Apply the recursive formula for mystery(a, b) until the base case, and show the results of “mystery(4, 15);”
```c=
unsigned int mystery(unsigned int a, unsigned int b) {
    if ( a >= b ) {    // base case
        return a;
    }
    else {
        return a + mystery(a + 1, b - 1);
    }
}
```
```c= 
#include <stdio.h>

unsigned int mystery(unsigned int a, unsigned int b) {
    if (a >= b) {
        return a;
    }
    else {
        printf("%u + mystery(%u, %u)\n", a, a + 1, b - 1);
        return a + mystery(a + 1, b - 1);
        }
}

int main()
{
    unsigned int x = 4;
    unsigned int y = 15;

    // 4 + 5 + 6 + ...... + 10 = 49
    // a + (a + 1) + (a + 2) + ...... + (b - 1 - a)
    // 6 'a's
    printf("\nmystery(4, 15) = %u\n", mystery(x, y));

    return 0;
}
```


# Chapter 6

## Briefly describe the definition of array in C.
由相同類型的元素（element）的集合所組成的資料結構，分配一塊連續的記憶體來儲存。


## What will happen for the following two definitions? 
a) int array[5] = {0,1,2,3}
$\qquad$If there are fewer initializers than elements in the array, the remaining elements are initialized to zero. 
$\qquad$* array[0] = 0
$\qquad$* array[1] = 1
$\qquad$* array[2] = 2
$\qquad$* array[3] = 3
$\qquad$* array[4] = 0
b) int array[5] = {0,1,2,3,4,5};
$\qquad$Causes a syntax error because there are six initializers and only five array element.


## List the array contents of the following definition and describe how it happened.
int array[5] = {1};
$\qquad$If there are fewer initializers than elements in the array, the remaining elements are initialized to zero. 
$\qquad$* array[0] = 1
$\qquad$* array[1] = 0
$\qquad$* array[2] = 0
$\qquad$* array[3] = 0
$\qquad$* array[4] = 0


## What will happen before compilation when symbolic constant is used?
在程式編譯之前，Preprocessor 先以 symbolic constant 取代常數值。


## Give two advantages of using symbolic constant.
1. 增加程式原始碼的可讀性
2. 容易修改


## What will happen when using printf function to print a string without null character?
The characters of the string are printed until a terminating null character is encountered.


## Given the following function, show the array contents after calling it twice.
```c=
void staticArray()
{
    static int array[5];
    for (size_t i= 0, i< 5, ++i) {
        array[i] += 3;
    }
}
```
```
3 3 3 3 3
6 6 6 6 6
```


## ADD - Case Study: Computing Mean, Median and Mode Using Array
```c=
#include <stdio.h>

#define SIZE 99

void Mean(const unsigned int answer[])
{
	printf("%s\n%s\n%s\n", "********", " Mean", "********");
	unsigned int total = 0;
	for (size_t j = 0; j < SIZE; j++) {
		total += answer[j];
	}
	printf("The mean is the average value of the data\n"
		"items. The mean is equal to the total of\n"
		"all the data items (%u), The mean value for\n"
		"this run is %u / %u = %.4f\n\n",
		SIZE, total, SIZE, (double)total / SIZE);
}

void BubbleSort(unsigned int a[]);
void PrintArray(const unsigned int a[]);

void Median(unsigned int answer[])
{
	printf("\n%s\n%s\n%s\n%s",
			"********", " Median", "********",
		"The unsorted array of responses is");
	PrintArray(answer);
	BubbleSort(answer);
	printf("%s", "\n\nThe sorted array is");
	PrintArray(answer);
	printf("\n\nThe median is element %u of\n"
		"the sorted %u element array.\n"
		"For this run the median is %u\n\n",
		SIZE / 2, SIZE, answer[SIZE / 2]);
}

void Mode(unsigned int freq[], const unsigned int answer[])
{
	printf("\n%s\n%s\n%s\n", "********", " Mode", "********");
	for (size_t rating = 1; rating <= 9; ++rating) {
		freq[rating] = 0;
	}
	for (size_t j = 0; j < SIZE; j++) {
		freq[answer[j]]++;
	}
	printf("%s%11s%19s\n\n%54s\n%54s\n\n",
		"Response", "Freqency", "Histogram",
		"1    1    2    2", "5    0    5    0    5");
	unsigned int largest = 0;
	unsigned int ModeValue = 0;
	for (size_t rating = 1; rating <= 9; rating++) {
		printf("%8u%11u          ", rating, freq[rating]);
		if (freq[rating] > largest) {
			largest = freq[rating];
			ModeValue = rating;
		}
		for (unsigned int h = 1; h <= freq[rating]; h++) {
			printf("%s", "*");
		}
		puts(" ");
	}
	printf("\nThe mode is the most frequent value.\n"
		"For this run the mode is %u which occurred"
		" %u times.\n", ModeValue, largest);
}

void BubbleSort(unsigned int a[])
{
	for (unsigned int pass = 1; pass < SIZE; pass++) {
		for (size_t j = 0; j < SIZE - 1; j++) {
			if (a[j] > a[j + 1]) {
				unsigned int hold = a[j];
				a[j] = a[j + 1];
				a[j + 1] = hold;
			}
		}
	}
}

void PrintArray(const unsigned int a[])
{
	for (size_t j = 0; j < SIZE; j++) {
		if (j % 20 == 0) {
			puts(" ");
		}
		printf("%2u", a[j]);
	}
}

int main()
{
	unsigned int frequency[10] = { 0 };
	unsigned int response[SIZE] =
	{6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
	 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
	 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
	 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
	 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
	 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
	 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
	 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
	 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
	 4, 5, 6, 1, 6, 5, 7, 8, 7 };
	Mean(response);
	Median(response);
	Mode(frequency, response);
	return 0;
}
```


## When should we use linear search and binary search?
* Linear Search
    * Small or unsorted arrays.
* Binary Search
    * Sorted arrays.


## Show the contents of the following arrays by tables. 
int array1[2][3]={{1,2,3},{4,5,6}};
int array2[2][3]={1,2,3,4,5};
int array3[2][3]={{1,2},{4}};

| array1 | Column 0 | Column 1 | Column 2 |
| -------- | -------- | --- | -------- |
| Row 0 | 1 | 2 | 3 |
| Row 1 | 4 | 5 | 6 |

| array2 | Column 0 | Column 1 | Column 2 |
| -------- | -------- | --- | -------- |
| Row 0 | 1 | 2 | 3 |
| Row 1 | 4 | 5 | 0 |

| array3 | Column 0 | Column 1 | Column 2 |
| -------- | -------- | --- | -------- |
| Row 0 | 1 | 2 | 0 |
| Row 1 | 4 | 0 | 0 |


## Give the two representations of the solution of the n-Queen puzzle. How to use them to represent the following solution of 4-Queen puzzle?
1. Backtracking Algorithm


## What is variable length array in C? What is the difference when applying $sizeof$ to constant size array and variable length array?
1. A variable-length array is an array whose length, or size, is defined in terms of an expression evaluated at execution time.
2. In early versions of C sizeof was always a compile-time operation, but when applied to a VLA, sizeof operates at runtime. 


## Give a brief description of buffer overflow.
[Buffer overflow](https://en.wikipedia.org/wiki/Buffer_overflow)


## Show how to define an array of integer of size 10 with all zero at initialization using symbolic constant SIZE.
```c=
#define SIZE 10
```


## How to prevent the $scanf$ from inputting too many characters which surpassing the array length? Use the following definition as an example to show your answer. <br>char string[100];
```c=
scanf("%99s", string);
```


## A vector is a sequence of numbers which can be represented by an array in C. The addition of two vectors is defined as follows. Given two vectors $U$ and $V$ of the same size, the i^th^ element of vector $W=U+V$ has the value $w_i=u_i+v_i$. Give a function named as $vecAdd$ for the vector addition $W=U+V$ of any size. Assume that the arrays are of integer type.



## Show how to prevent the calling function from modifying the contents of an array argument. You have to give the function prototype to show your answer.
```c=
void modifyArray(int b[], size_t size);
```


## Write the bubble sort.
```c=
#include <stdio.h>

#define SIZE 10

void BubbleSort(int a[])
{    // the largest element goes up
	for (int i = SIZE - 1; i > 0; i--) {    // from n & (n-1) to 1 & 0
		for (size_t j = 0; j < i; j++) {    // from 0 to (i-1) 
			if (a[j] > a[j + 1]) {
				int temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
}

void output(int a[])
{
	for (size_t i = 0; i < SIZE; i++) {
		printf("%4d", a[i]);
	}
	printf("\n\n");
}

int main()
{
	int array[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
	puts("Data items in original order: \n");
	output(array);
	BubbleSort(array);
	puts("Data items in ascending order: \n");
	output(array);

	return 0;
}
```
```
Data items in original order:

   2   6   4   8  10  12  89  68  45  37

Data items in ascending order:

   2   4   6   8  10  12  37  45  68  89


```


## Sorting Arrays: Selection Sort
```c=
#include <stdio.h>

#define SIZE 10

void swap(int a[], size_t x, size_t y);

void SelectionSort(int a[])
{    // take out the smallest element and throw it to the front
	for (size_t i = 0; i < SIZE - 1; i++) {    // from 0 to [(SIZE-1)-1]
		size_t smallest = i;
		for (size_t j = i + 1; j < SIZE; j++) {    // for (SIZE-i) times
			if (a[j] < a[smallest]) {
				smallest = j;
			}
		}
		swap(a, i, smallest);
	}
}

void output(int a[])
{
	for (size_t i = 0; i < SIZE; i++) {
		printf("%4d", a[i]);
	}
	printf("\n\n");
}

int main()
{
	int array[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
	puts("Data items in original order: \n");
	output(array);
	SelectionSort(array);
	puts("Data items in ascending order: \n");
	output(array);

	return 0;
}

void swap(int a[], size_t x, size_t y)
{
	int temp = a[x];
	a[x] = a[y];
	a[y] = temp;
}
```


## Write the insertion sort according to the following algorithm.
1  $\quad$for 𝑖 ← 2 to |𝐴|
2  $\qquad$do 𝑘𝑒𝑦 ← 𝐴~𝑖~
3  $\quad$$\qquad$𝑗 ← 𝑖 - 1
4  $\quad$$\qquad$while 𝑗 > 0 and 𝐴~𝑗~ > 𝑘𝑒𝑦
5  $\qquad$$\qquad$do 𝐴~𝑗+1~ ← 𝐴~𝑗~
6  $\quad$$\quad$$\qquad$𝑗 ← 𝑗-1
7  $\quad$$\qquad$𝐴~𝑗+1~ ← 𝑘𝑒𝑦
8  $\quad$return 𝐴
```c=
#include <stdio.h>

#define SIZE 10

void InsertionSort(int a[])
{    // similar to sorting cards
	for (size_t i = 1; i < SIZE; i++) {    // from (0+1) to (SIZE-1)
		size_t moveitem = i;
		int insert = a[i];
		while (moveitem > 0 && a[moveitem - 1] > insert) {    // while n > (n-1)
			a[moveitem] = a[moveitem - 1];
			moveitem--;
		}
		a[moveitem] = insert;
	}
}

void output(int a[])
{
	for (size_t i = 0; i < SIZE; i++) {
		printf("%4d", a[i]);
	}
	printf("\n\n");
}

int main()
{
	int array[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
	puts("Data items in original order: \n");
	output(array);
	InsertionSort(array);
	puts("Data items in ascending order: \n");
	output(array);

	return 0;
}
```


## Write C code for the following algorithm. <br>Algorithm: MERGE (𝐴, p, q, r)
1  $\quad$for 𝑛~1~ ← q – p + 1, 𝑛~2~ ← r - q
2  $\quad$L ← MAKE-ARRAY(𝑛~1~ + 1), R ← MAKE-ARRAY(𝑛~2~+ 1)
3  $\quad$L[1..𝑛~1~] ← A[p..q], R[1..𝑛~2~] ← A[q+1..r]
4  $\quad$𝐿~𝑛1+1~+1 ← ∞, 𝑅~𝑛2+1~← ∞
5  $\quad$𝑖 ← 1, 𝑗 ← 1
6  $\quad$**for** 𝑘 ← p **to** r
7  $\qquad$**do if** 𝐿~𝑖~ ≤ 𝑅~𝑗~
8  $\quad$$\qquad$**then** 𝐴~𝑘~ ← 𝐿~𝑖~
9  $\qquad$$\qquad$ 𝑖 ← 𝑖 + 1
10 $\quad$$\qquad$**else** 𝐴~𝑘~ ← 𝑅~𝑗~
11 $\qquad$$\qquad$ 𝑗 ← 𝑗 + 1
```c=
#include <stdio.h>

#define SIZE 10

void Merge(int a[], size_t left, size_t middle1, size_t middle2, size_t right)
{
	size_t LeftIndex = left;
	size_t RightIndex = middle2;
	size_t CombinedIndex = left;
	int TempArray[SIZE];
	while (LeftIndex <= middle1 && RightIndex <= right) {
		if (a[LeftIndex] <= a[RightIndex]) {
			TempArray[CombinedIndex++] = a[LeftIndex++];
		}
		else {
			TempArray[CombinedIndex++] = a[RightIndex++];
		}
	}
	if (LeftIndex == middle2) {
		while (RightIndex <= right) {
			TempArray[CombinedIndex++] = a[RightIndex++];
		}
	}
	else {
		while (LeftIndex <= middle1) {
			TempArray[CombinedIndex++] = a[LeftIndex++];
		}
	}
	for (size_t i = left; i <= right; i++) {
		a[i] = TempArray[i];
	}
}

void MergeSort(int a[], size_t low, size_t high) 
{
	if ((high - low) >= 1) {
		size_t middle1 = (low + high) / 2;
		size_t middle2 = middle1 + 1;

		MergeSort(a, low, middle1);
		MergeSort(a, middle2, high);

		Merge(a, low, middle1, middle2, high);
	}
}

void output(int a[])
{
	for (size_t i = 0; i < SIZE; i++) {
		printf("%4d", a[i]);
	}
	printf("\n\n");
}

int main()
{
	int array[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
	puts("Data items in original order: \n");
	output(array);
	MergeSort(array, 0, SIZE - 1);
	puts("Data items in ascending order: \n");
	output(array);

	return 0;
}
```


## Give the C code for linear search.
```c=
#include <stdio.h>

#define SIZE 100

size_t LinearSearch(const int array[], int key, int size)
{
	for (size_t n = 0; n < size; n++) {
		if (array[n] == key) {
			return n;
		}
	}
	return -1;
}

int main()
{
	int a[SIZE];
	for (size_t x = 0; x < SIZE; x++) {
		a[x] = 2 * x;
	}
	printf("Enter integer search key: ");
	int SearchKey;
	scanf_s("%d", &SearchKey);
	size_t index = LinearSearch(a, SearchKey, SIZE);
	if (index != -1) {
		printf("Found value at index %d\n", index);
	}
	else {
		puts("Value not found");
	}
	return 0;
}
```


## Give the C code for binary search.
```c=
#include <stdio.h>
#define SIZE 15

void printRow(const int b[], size_t low, size_t mid, size_t high)
{
	for (size_t i = 0; i < SIZE; ++i) {
		if (i < low || i > high) {
			printf("%s", "    ");
		}
		else if (i == mid) {
			printf("%3d*", b[i]);
		}
		else {
			printf("%3d ", b[i]);
		}
	}
	puts("");
}

size_t binarySearch(const int b[], int searchKey[], size_t low, size_t high)
{
	while (low <= high) {
		size_t middle = (low + high) / 2;
		printRow(b, low, middle, high);
		if (searchKey == b[middle]) {
			return middle;
		}
		else if (searchKey < b[middle]) {
			high = middle - 1;
		}
		else {
			low = middle + 1;
		}
	}
	return -1;
}

void printHeader(void)
{
	puts("\nIndices:");
	for (unsigned int i = 0; i < SIZE; i++) {
		printf("%3u ", i);
	}
	puts("");
	for (unsigned int i = 1; i <= 4 * SIZE; ++i) {
		printf("%s", "-");
	}
	puts("");
}

int main()
{
	int a[SIZE];
	for (size_t i = 0; i < SIZE; ++i) {
		a[i] = 2 * i;
	}
	printf("%s", "Enter a number between 0 and 28: ");
	int key;
	scanf("%d", &key);
	printHeader();
	size_t result = binarySearch(a, key, 0, SIZE - 1);
	if (result != -1) {
		printf("\n%d found at index %d\n", key, result);
	}
	else {
		printf("\n%d not found\n", key);
	}
	return 0;
}
```
> Debugging[color=red]


## Give the definition of a 7-by-8 array of floating points. How to reference the element at the 3^rd^ row and the 5^th^ column?



## Write a function $addMatrix$ to return the sum of a $ROW$-by-$COL$ two-dimensional array of integers, where $ROW$ and $COL$ are symbolic constants.





# Chapter 7

## What can be used to initialize a pointer?
1. NULL
2. 0
3. an address


## Why we prefer NULL than 0 when initializing a pointer?
NULL highlights the fact that the variable is of a pointer type.


## What may occur when dereferencing a pointer that has not been properly initialized? Why?
A fatal execution-time error, or it could accidentally modify important data and allow the program to run to completion with incorrect results.


## Give the two ways to pass arguments to a function. Which one is used in C, and how can C simulate the other one?
1. Pass-by-Value
    * <font color=orange>All arguments in C are passed by value.</font>
2. Pass-by-Reference
    * In C, we use pointers and the indirection operator to simulate pass-by-reference. 


## What is the main function of const qualifier? How many possibilities does it have in function parameters? Give one example for each possibility.
1. The const qualifier enables you to inform the compiler that the value of a particular variable <font color=orange>should not be modified</font>.
2. Six possibilities exist for using (or not using) const with function parameters
    1. two with pass-by-value parameter passing
    2. four with pass-by-address parameter passing.
        1. a non-constant pointer to non-constant data, 
        2. a constant pointer to non-constant data, 
        3. a non-constant pointer to constant data, and 
        4. a constant pointer to constant data. 


## Show how to determine the size in bytes of the following variables in C with portability:
a)
```
int x = 5;   
int *y = x;   
double z[x];    
char w[5];    
```


```
Answer:
int = 4, x = 4
int = 4, *y = 4
double = 8, z = 40
char = 1, w = 5
```
```c=
#include <stdio.h>

int main() 
{
    int x = 5;    // 4 bytes
    int *y = x;    // 4 bytes
    double z[x];    // 8 bytes * x
    char w[5];    // 1 byte * 5
    
    printf("int = %d, x = %d\n", sizeof(int), sizeof(x));
    printf("int = %d, *y = %d\n", sizeof(int), sizeof(*y));
    printf("double = %d, z = %d\n", sizeof(double), sizeof(z));
    printf("char = %d, w = %d\n", sizeof(char), sizeof(w));
    
    return 0;
}
```


b) What’s the difference when determining the size for the last two arrays?



## Given the following definition:
int v[5];
Suppose v is at location 5000 in memory.
a) Define a pointer vPtr to the array v.
b) There are four ways to access the array elements. Give their name and show how to use them to access the third element in v.
c) Show the value stored in vPtr after the following statement is executed. Assume an integer is 2 bytes.
    vPtr+= 3;
d) From c), what if the following statement is further executed?
    vPtr++;
e) From d), given another pointer v2Ptr which points to the second element in v, what is the value of the following statement?
    size_t x = vPtr – v2Ptr;
1. int* vPtr = v;
2. There are four ways to pass a pointer to a function
    1. a non-constant pointer to non-constant data
    2. a constant pointer to non-constant data
    3. a non-constant pointer to constant data
    4. a constant pointer to constant data
3. v[3]; 5006
4. v[4]; 5008
5. 4


## What is the meaning of void *? What will occur if such pointer is dereferenced?
1. A <font color=orange>generic pointer</font> that can represent any pointer type.
2. A pointer to void <font color=orange>cannot be dereferenced</font>.


## Why a pointer to void cannot be dereferenced?
The compiler must know the data type to determine the number of bytes to be dereferenced for a particular point.


## Describe the functionality of the following function.
```c=
void mystery1(char *s1, const char *s2)
{
    while (*s1 != '\0') ++s1; 
    for (; *s1 = *s2; ++s1, ++s2); 
}
```



## Describe the functionality of the following function.
```c=
size_t mystery(const char *s)
{    
    size_t x = 0;
    for (; *s != ‘\0’, ++s) ++x;
    return x;
}
```



## Describe the functionality of the following function.
```c=
int mystery(const char *s1, const char *s2)
{
    int result = 1;
    for (; *s1 != '\0' && *s2 != '\0'; ++s1, ++s2) {
        if (*s1 != *s2) {
            result = 0
        } 
      } return result;
}
```



## What is the advantage of using an array of pointers rather than a two-dimensional array for storing an array of strings?
1. Such a data structure like a two-dimensional array would have to have a fixed number of columns per row, and that number would have to be <font color=orange>as large as the largest string</font>.
2. Therefore, considerable <font color=orange>memory could be wasted</font> when storing a large number of strings of which most were shorter than the longest string.


## Briefly describe the phenomenon of indefinite postponemen.
An algorithm that could execute for an unknown amount of time because it depends on random numbers to exit a function.


## Given the definition int x = 5; show how to set the value of x to 10 by using pointer.
```c=
#include <stdio.h> 

int main()
{
	int x = 5;
	int* y = &x;

	*y *= 2;

	printf("%d", x);

	return 0;
}
```


## Given three integers int x, y, z;
a) Write the function to add x and y into z by using three integer pointers. 
```c=
int add(int x, int y)
{
	int* a = &x;
	int* b = &y;
	int* c = *a + *b;

	return c;
}
```

b) Modify your function head so that it can protect x and y from being modified in the function.
```c=
int add(const int x, const int y)
{
	int* a = &x;
	int* b = &y;
	int* c = *a + *b;

	return c;
}
```

c) Modify your function head so that it can also protect the pointers from being modified in the function.
```c=
int add(int x, int y)
{
	const int* const a = &x;
	const int* const b = &y;
	const int* const c = *a + *b;

	return c;
}
```


## Write the function head for manipulating an integer array by an integer pointer with
a) non-constant pointer to non-constant data
```c=
void NCPtoNCD(int* sPtr);
```
b) non-constant pointer to constant data
```c=
void NCPtoCD(const int* sPtr);
```
c) constant pointer to non-constant data
```c=
int* const ptr = &x;
```
d) constant pointer to constant data
```c=
constint* const ptr = &x;
```
Assume that we don’t need any return value.



## Write the function swap to exchange two integer arguments. Add proper const to the function head.
```c=
void swap(int *x,int *y)
{
    int temp;
    temp = *x; 
    *x = *y;    
    *y = temp;  
}
```


## Define an array of pointers to store the following strings: “C”, “How”, “To”, “Program”. Show how they are arranged in memory.
```c=
char* array[] = {"C", "How", "To", "Program"};
```
```c=
#include <stdio.h>

int main()
{
	char* array[] = {"C", "How", "To", "Program"};
	int counter = 0;
	while (array[counter]) {
		printf("%d %s\n", counter, array[counter]);
		counter++;
	}
	return 0;
}
```
```
0 C
1 How
2 To
3 Program
```


## a) Define a function pointer to a function with two arguments of type double and a return value of type integer.
```c=
int(*compare)((double a, double b);
```
[Functions Pointers in C Programming with Examples](https://www.guru99.com/c-function-pointers.html)
```c=
return_type (*function_name)(arguments);
```


## b) How to call the function pointed by the function pointer in a)?
```c=
compare(work[count], work[count + 1]);
```


## a) Define an array of five function pointers to functions with two arguments of string, one argument of type integer, and no return value.
```c=
void (*function_name[5])(char, char, int) = {string1, string2, integer};
```


## b) How to call the function pointed by the third function pointer in the array of function pointer in a)?
```c=
(*function_name[2])(2);
```


# Chapter 8

## Briefly describe the following four functions: *islower*, *isupper*, *tolower*, *toupper*.
* int islower(int c); 
    * Returns a true value if *c* is a *lowercase letter* and 0 (false) otherwise.
* int isupper(int c); 
    * Returns a true value if *c* is an *uppercase letter* and 0 (false) otherwise.
* int tolower(int c); 
    * If c is an *uppercase letter*, tolower returns c as a *lowercase letter*. Otherwise, tolower returns the argument unchanged.
* int toupper(int c); 
    * If c is a *lowercase letter*, toupper returns c as an *uppercase letter*. Otherwise, toupper returns the argument unchanged.


## Briefly describe the following four functions: isspace, iscntrl, ispunct, isprint, isgraph.
* int isspace(int c); 
    * Returns a true value if *c* is a *whitespace character*—newline ('\n'), space (' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t') or vertical tab ('\v')—and 0 (false) otherwise.
* int iscntrl(int c); 
    * Returns a true value if *c* is a *control character*—horizontal tab ('\t'), vertical tab ('\v'), form feed ('\f'), alert ('\a'), backspace ('\b'), carriage return ('\r'), newline ('\n') and others—and 0 (false) otherwise.
* int ispunct(int c); 
    * Returns a true value if *c* is a *printing character other than a space, a digit, or a letter*—such as $, #, (, ), [, ], {, }, ;, : or %—and returns 0 otherwise.
* int isprint(int c); 
    * Returns a true value if *c* is a *printing character* (i.e., a character that’s visible on the screen) *including a space* and returns 0 (false) otherwise.
* int isgraph(int c); 
    * Returns a true value if *c* is a *printing character other than a space* and returns 0 (false) otherwise. 



## Given the following code:
```
const char *string = "3.141592 is the value of pi with 6 digits in the right of the floating point.";
```
```
double *stringPtr = NULL;
double x = strtod(string, &stringPtr);
stringPtr = strpbrk(stringPtr, "0123456789");
int y = strtoul(stringPtr, NULL, 10);
```
### a) What are the values of *x* and *y*.
1. x = 3.141592
2. y = 6
### b) Why we should use *&stringPtr* rather than *stringPtr* for *strtod* in line 2?
Line 2 indicates that x is assigned the double value converted from string, and stringPtr is assigned the location of the first character after the converted value in string. 
### c) Describe the functionality of *strpbrkin* line 3.
Line 3 locates the first occurrence in stringPtr of any character
from "0123456789").
> CODE:
>> ```c=
>> #include <stdio.h>
>> #include <stdlib.h>
>> #include <string.h>
>> 
>> int main(void)
>> {
>> 
>> 	const char* string = "3.141592 is the value >> of pi with 6 digits in the right of the floating point.";
>> 	double* stringPtr = NULL;
>> 	double x = strtod(string, &stringPtr);
>> 	stringPtr = strpbrk(stringPtr, "0123456789");
>> 	int y = strtoul(stringPtr, NULL, 10);
>> 
>> 	printf("%lf %d", x, y);
>> 
>> 	return 0;
>> }
>> ```
> MORE:
>> * double strtod(const char *nPtr, char **endPtr);
>>     * Converts the string nPtr to double.
>> * long strtol(const char *nPtr, char **endPtr, int base);
>>     * Converts the string nPtr to long.
>> * unsigned long strtoul(const char *nPtr, char **endPtr, int base);
>>     * Converts the string nPtr to unsigned long.
>> * char *strpbrk(const char *s1, const char *s2);
>>     * *Locates the first occurrence* in string s1 of any character in string s2. If a character from string s2 is found, a pointer to the character in string s1 is returned. Otherwise, a NULL pointer is returned. 


## Briefly describe the functionality of fgets with the third argument as stdin.
The third argument specifies the stream from which to read characters—in this case, we use the standard input stream (stdin).
* char *fgets(char *s, int n, FILE *stream);
    * Inputs characters from the specified stream into the array s until a *newline* or *end-of-file* character is encountered, or until n - 1 bytes are read. In this chapter, we specify the stream as *stdin*—the *standard input stream*, which is typically used to read characters from the keyboard. A *terminating null character* is appended to the array. Returns the string that was read into *s*. If a newline is encountered, it’s included in the string stored in *s*. 


## Briefly describe the functionality of *sscanf* and *sprintf*. What is the main difference between *sscanf*/ *sprintf* and *scanf*/ *printf*?
* int sscanf(char *s, const char *format, ...);
    * Equivalent to *scanf*, except the input is read from the array *s* rather than from the keyboard. 
    * Returns the number of items successfully read by the function, or *EOF* if an error occurs. 
* int sprintf(char *s, const char *format, ...);
    * Equivalent to *printf*, except the output is stored in the array *s* instead of printed on the screen. 
    * Returns the number of characters written to *s*, or *EOF* if an error occurs.


## Given the following definitions:
```c=
char string1[255] = "Hello ", 
string2[255] = "Hello World", string3[255], string4[255];
```
What are the results of the following codes:
### a) 
```c=
printf("%s", strncat(strncpy(string3, string1, 2), string2, 5));
```
```
He   Hello
```
### b) 
```c=
printf("%s", strcat(strcpy(string3, string1), string2));
```
```
Hello Hello World
```
> CODE
>> ```c=
>> #define _CRT_SECURE_NO_WARNINGS
>> 
>> #include <stdio.h>
>> #include <string.h>
>> 
>> int main(void)
>> {
>> 	char string1[255] = "Hello ",
>> 		string2[255] = "Hello World", 
>> 		string3[255], string4[255];
>> 
>> 	printf("%s", strncat(strncpy(string3, string1, 2), string2, 5));
>> 
>> 	printf("\n");
>> 
>> 	printf("%s", strcat(strcpy(string3, string1), string2));
>> 
>> 	return 0;
>> }
>> ```


## Function *strncpy* does not necessarily copy the terminating null character of its second argument. Give an example for such circumstance.
* This occurs only if the number of characters to be copied is more than the length of the string. 
* For example, if "test" is the second argument, a *terminating null character* is written only if the third argument to strncpy is at least 5 (four characters in "test" plus a terminating null character). If the third argument is larger than 5, some implementations append null characters to the array until the total number of characters specified by the third argument are written and others stop after writing the first null character.


## Briefly describe the functionality of *strcpy*, *strncpy*, *strcat*, *strncat*.
* char *strcpy(char *s1, const char *s2)
    * *Copies* string *s2* into array *s1*. The value of *s1* is returned.
* char *strncpy(char *s1, const char *s2, size_t n)
    * *Copies at most n characters* of string *s2* into array *s1* and returns *s1*.
* char *strcat(char *s1, const char *s2)
    * *Appends* string *s2* to array *s1*. The first character of *s2* *overwrites the terminating null character* of *s1*. The value of *s1* is returned.
* char *strncat(char *s1, const char *s2, size_t n)
    * *Appends at most n characters* of string *s2* to array *s1*. The first character of *s2* *overwrites the terminating null character* of *s1*. The value of s1 is returned.


## Briefly describe the functionality of *strcmp* and *strncmp*, and show the meaning of their return values.
* int strcmp(const char *s1, const char *s2);
    * *Compares* the string *s1* with the string *s2*. 
    * The function returns 0, less than 0 or greater than 0 if *s1* is equal to, less than or greater than *s2*, respectively.
* int strncmp(const char *s1, const char *s2, size_t n);
    * * Compares up to n characters* of the string *s1* with the string *s2*. 
    * The function returns 0, less than 0 or greater than 0 if *s1* is equal to, less than or greater than *s2*, respectively. 


# Chapter 9

## Give the definition of precision for the following conversion specifier in *printf*:
### a) *%d*
Default precision is 1.
### b) *%e*
Default precision is 6. If precision is 0 or the period (.) appears without a number following it, no decimal point is printed.
### c) *%g*
Six significant digits are printed, and any trailing zeros are truncated.
### d) *%s*
Characters are printed until a null character is found.
> [Format specification syntax: printf and wprintf functions](https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=msvc-170#precision-specification)[color=blue]


## What is the function of conversion specification *%g* in *printf*?
Conversion specifier g (or G) prints in either e (E) or f format with *no trailing zeros*.


## Show the results of the following statements:
### a) *printf(“%e”, +1234567.89);*
1.234568e+06
### b) *printf(“%f”, 1234567.89);*
1234567.890000
### c) *printf(“%G”, 1234567.89);*
1.23457E+06


## What is the functionality of specifying field width?
*Right justifying* those numbers that contain fewer digits than the field width.


## What will happen if the printing values are wider than the field?
Offset other data being printed, producing confusing outputs.


## Given *int x[5] = {1, 12, 123, 1234, 12345};*
Show the results of the following code:
### a) *for (size_t i= 0; i< 5; ++i) printf(“%4d\n, ” x[i]);*
```
    1
   12
  123
 1234
 12345
 
```
### b) *for (size_t i= 0; i< 5; ++i) printf(“%-4d\n, ” x[i]);*
```
 1
 12
 123
 1234
 12345
 
 ```


## Briefly describe the functions of the following flags for *printf*:
### a) *–*
Left justify the output within the specified field.
### b) *+*
Display a plus sign preceding positive values and a minus sign preceding negative values.
### c) *space*
Print a space before a positive value not printed with the + flag.
### d) *0*
Pad a field with leading zeros.


## Given *int x = 468*; Write the results of the following statement:
```c=
printf(“%d\n%+d\n% d\n%06d\n”, x, x, x, x);
```
```
468
+468
 468
000468

```


## What is the function of *%i* conversion specification in *scanf*?
Conversion specifier %i can input decimal, octal and hexadecimal integers.


## What is the function of scan set in *scanf*?
Scan a string for a set of characters that are stored in an array.


## Given an input string “*acbdddcba*”. Show the result of the following statements:
```c=
scanf(“%[abc]”, string1);printf(“%s”, string1);
```
acb


## Given an input string “*dcbaecb*”. Show the result of the following statements:
```c=
scanf(“%[^ab]”, string1);
printf(“%s”, string1);
```
dc


## What is assignment suppression character?
The assignment suppression character reads data from the input stream and discards the data.


## How to print x if it is of type
### a) *int*
printf("%d\n", x);
### b) *unsigned short*
printf("%hu\n", x);
### c) *long double*
printf("%lf\n", x);
printf("%le\n", x);
printf("%lg\n", x);
### d) *char*
printf("%c\n", x);
### e) *string*
printf("%s\n", x);


## Given two integers *a* and *b*, and a floating-point *c*. How to specify the field width *a* and the precision *b* using integer expressions when printing *c*?
printf("%*.%f", a, b, c);


## Given three input *70*, *070*, and *0x70*. How to read then as decimal, octal, and hexadecimal integers, respectively?
int a, b, c;
scanf("%d %i %i", &a, &b, &c);


## Given three input *70*, *70*, and *70*. How to read then as decimal, octal, and hexadecimal integers, respectively?
int a, b, c;
scanf("%d %o %x", &a, &b, &c);


## How to restrict the input to characters “*wxyz*” using *scanf*? How to restrict the input to characters which are **not** “*wxyz*” using *scanf*?
1. scanf("%[wxyz]", string);
2. scanf("%[^wxyz]", string);


## How to use a single statement to read the *day*, *month*, and *year* stored in the following two different formats: day-month-year and day/month/year?
scanf("%d%*c%d%*c%d", &month, &day, &year);


###### tags: `程式設計（一）` 
