Scope and extent - 作用域和生存周期

The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value.

Extent, on the other hand, is a runtime (dynamic) aspect of a variable. Each binding of a variable to a value can have its own extent at runtime.

Iteration vs. Recursion

Given relationship between problem/solution and subproblem/partial solution, we can proceed in forward direction, i.e. iteratively, or in backward direction, i.e. recursively.

Summation

$$\begin{eqnarray}
&&sum(\{~\}) &= 0 \\
&&sum(\{a_1,\dots,a_{n+1}\}) &= sum(\{a_1,\dots,a_n\})+a_{n+1}
\end{eqnarray}$$

Or

$$\begin{equation}
sum(\{a_1,\dots,a_n\})=\left\{
\begin{array}{ll}
0 & \text{if } n = 0 \\
sum(\{a_1,\dots,a_{n-1}\})+a_n & \text{if } n > 0
\end{array}
\right.
\end{equation}$$

Coding

???

Array

int a[10];

or

#define SIZE 10

int a [SIZE];

Tyical Operations

1,access:

for loop a[i]

2,left/right shift

for loop,a[i] = a[i + 1],or a[i] = a[i - 1]。Attention to the order of sequence of operations

Remarks:

1,In case of array as function argument,the array can be accessed in function, because the array name itself is the address of the array.

2,array can not be assigned such as b = a;,INVALID!

3,Do NOT use int a[n];!!!

Is \(a+(b+c)\) same as \((a+b)+c\)?

Not necessary!

while (a)
{
    ...
    ...
    if (b) 
        continue;
    ...
    ...
    ...
}

可以改成

while (a)
{
    ...
    ...
    if (!b) 
   {
    ...
    ...
    ...

    }
}
while (a)
{
    ...
    ...
    if (b) 
        break;
    ...
    ...
    ...
}

建议改为

while (a && !b)
{
    ...
    ...
    if (!b) 
   {
    ...
    ...
    ...

    }
}

for (i=0;i<n;i++)
{
    ...
}

The above for structure can be transformed to a while structure:

i=0;
while (i<n)
{
    ...
i++; }

And following while and do-while are equivalent:

do
{
    ...;
}while (b);
{
    ...;
}
while (b)
{
    ...;
}

In case of unknown number of integers to be read, we could use EOF to tell C program the end of input.

In linux system, we can use Control-D to initiate EOF, while in windows system, we use Control-Z to initiate EOF, when input from keyboard.

For example,

#include<stdio.h>

int main()
{
	int num;
        int count = 0;
	int total = 0;
	
	while(scanf("%d", &num) != EOF)
        {
		total = total + num; 
                count++;
	}
	printf("%d integers read,the total = %d\n", count, total);
	return 0;
}

stdin

12
23
34
45
56
^D//indicate a keyboard input Ctrl-D in linux or Ctrl-Z in windows

stdout

5 integers read,the total = 170

当输入输出数据量很大时,通常不适合手工输入。此时可以采用C语言的重定向功能:

把输入数据放入一个文本文件,文件名为:data.in,然后在程序开始处,调用下面的函数。之后正常的输入就会从该文件读取。
freopen("data.in","r",stdin);

如果要把打印结果输出到文件:data.out,可以在程序打印之前,调用下面函数,之后的打印均输出到该文件。
freopen("data.out","w",stdout);

文件的命名不一定如例子所示,只要一致就行。