2012年11月25日 星期日

Array and pointer – two key techniques in C program



In the CSCI1110, the topics “array” and “pointer” were taught in chapter 8 - 10. They are two of the key techniques used in writing C program. Now let me summarize what I have learnt from chapter 8 - 10.

Part 1

1.1 Contents of the lectures

In chapter 8-10, I have learnt some fundamental concepts about array and pointer. What are array and pointer? Arrays are data structures consisting of related data items of the same type. An array is a group of contiguous memory locations that all have the same type. To refer to a particular location or element in the array, we specify the array’s name and the position number of the particular element in the array; Pointers are variables whose values are memory addresses. A pointer contains an address of a variable that contains a specific value. A variable name directly references a value, and a pointer indirectly references a value. These two techniques make the design of the program easier since these techniques provide many of the capabilities programmer needs. Therefore, it is very important for a good programmer to acquire a good skill of using array and pointer. In chapter 8-10, the knowledge of array and pointer I had learnt include (1) defining and initializing arrays , (2) passing arrays to functions, (3) defining and initializing pointer variable(4) relationship between pointers and arrays.

(1)   Defining and initializing arrays :

  • Arrays occupy space in memory. We specify the type of each element and the number of elements in the array so that the computer may reserve the appropriate amount of memory.

  • An array of type char can be used to store a character string.

  • Type size_t represents an unsigned integral type. This type is recommended for any variable that represents an array’s size or an array’s subscripts. The header <stddef.h> defines size_t and is often included by other headers (such as <stdio.h>).

  • The element of an array can be initialized when the array is defined by following the definition with an equals sign and braces, {}, containing a comma-separated list of initializers. If there are fewer initializers than elements in the array, the remaining elements are initialized to zero.
  • If the array size is omitted from a definition with an initializer list, the number of elements in the array will be the number of elements in initializer list.





(2)    Passing arrays to functions:

  • To pass an array argument to a function, specify the name of the array without any brackets.
  • Unlike char arrays that contain strings, other array types do not have a special terminator. For this reason, the size of an array is passed to a function, so that the function can process the proper number of elements.
  • C automatically passes arrays to functions by reference – the called functions can be modified the element values in the caller’s original arrays. The name of the array evaluates to the address of the first element of the array. Because the starting address of the array is passed, the called function knows precisely where the array is stored. Therefore, when the called function modifiers array elements in its function body, it’s modifying the actual elements of the array in their original memory locations.


(3)   Defining and initializing pointer variable :

  • A pointer contains an address of another variable that contains a value. In this sense, a variable name directly references a value, and pointer indirectly references a value.
  • Referencing a value through a pointer is called indirection.
  • Pointers can be defined to point to objects of any type.
  • Pointers should be initialized either when they are defined or in an assignment statement. A pointer may be initialized to Null, 0 or an address. A pointer with the value NULL points to nothing. Initializing a pointer to 0 is equivalent to initializing a pointer to NULL, but NULL is preferred. The value 0 is the only integer value that cab be assigned directly to a pointer variable.



(4) Relationship between pointers and arrays

  • Arrays and pointers are intimately related in C and often may be used interchangeably.
  • An array name can be thought of as a constant pointer.
  • Pointers can be used to do any operation involving array subscripting.
  • When a pointer points to the beginning of an array, adding an offset to the pointer indicates which element of the arrays can. This is referred to as pointer/subscript notation.
  • An array name can be treated as a pointer and used in pointer and used in pointer arithmetic expressions that do not attempt to modify the address of the pointer.
  • Pointers can be subscripted exactly as arras can. This is referred to as pointer/subscript notation.
  • A parameter of type const char* typically represents a constant string.




More about arrays and pointer :


1.2 Learning Process:

In order to understand the principle of array and pointer and acquire the techniques of using them, I use different methods to let myself to understand the principle and uses of the techniques during the learning process.

(1)   To understand the principle of array in the view of box and cabinet relationship

For ordinary value, it is like a box for storing one value.

However, for array, it is like a cabinet containing many drawers. Each drawer stores one value. We can refer to each drawer as 1st drawer, 2nd drawer, 3rd drawer, etc.


(2) To understand the principle of pointer in form of graphical representation.


The above figure shows the representation of the pointer in memory, assuming that integer variable y is stored at location 1000, and pointer variable yPtr is stored at location 2000. Pointer variable yPtr stores the address of variable y ans has a value of 1000.

(3)  Record the common programming error in using array and pointer.

Since the use of array and pointer is complex, we may make some programming errors easily in using them. In order to acquire the techniques of using these two techniques accurately without mistakes or errors, I recorded the common programming error in using array and pointer and some error-prevention skills during the learning process.
  • Forgetting to initialize the elements of an array.
  • Providing more initializers in an array initializer list than there are elements in the array is a syntax error.
  • Assigning a value to a symbolic constant in an executable statement is a syntax error. A symbolic constant is not a variable. The compiler does not reserve space for symbolic constants as it does for variables that hold values at execution time.

  • Referring to an element outside the array bounds.

  • The asterisk (*) notation used to declare pointer variables does not distribute to all variable names in a declaration. Each pointer must be declared with the * prefixed to the name; e.g. if you wish to declare xPtr and yPtr as int pointers, use int* xPtr, *yPtr; .

  • Initializer pointers to prevent unexpected results.

  • Dereferencing a pointer that has not been properly initialized or that has nor been assigned to a point toa specific location in memory is an error.

  • Attempting to modify an array name with pointer arithmetic is a compilation error.

Part 2

2.1 A interesting topic in the lesson – application of arrays

A brief description about the math library function in C program :

Arrays in C can have many important computing applications. In the lecture, the applications below are introduced.

First, it can be used in sorting. Because of the way the successive comparsions are made, a large value may move down the array many positions on a single pass, but a small value may move up only one position.

Second, it can be used in searching. It is a process of finding a particular element of an array. The linear search compare each element of the array with the search key. Because the array is not in any particular order, it’s just as likely that the value will be found in the first element as in the last. On average, therefore, the search key will be compared with half the elements of the array.

Third, arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays, which the C standard refers to as multidimensional arrays, is to represent tables of values consisting of information arranged in rows and columns.

2.2 My opinion, commends, ideas, and further information about application of array

I think the application of arrays is very useful and important in our real life.It can be used for solving mathematics problem and writing different program.

For example , a two-dimensional array ,which have two subscripts (row and column) , can be used to create a 2D board. For example , we can write a connect four game by C program in an easy way because we can use a two-dimensional array to create a game board.



Apart from it, another application of arrays that had not mentioned in the lecture is computing mean, median and mode using arrays.

For example, by the following C program using array :

#include<stdio.h>
#include<conio.h>
main()
{
int marks[100];
int i,n,sum,average;
printf("enter the number of students");
scanf("%d",&n);
printf("enter %d student's marks",n);
sum=0;
for(i=0;i<n;i++)
{
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
average=sum/n;
printf("the sum of the marks of %d studens is %d\n",n,sum);
printf("the average of %d students is %d\n",n,average);
getch();
}

We can find out the average of marks of studens easily.

From these examples, we can see that arrays in C program is a very useful tool for program design. It can help engineer to solve difficult and complex mathematics or engineering problem in the real applications. In fact, arrays have a wide range of application such as ,to implement mathematical vectors and matrices, implement other data structures, determine partial or complete control flow in program. As a engineering student, I must acquire the techniques of using arrays for solving engineering problems.

More about application of array:


I think writing what I had learnt from the lesson in the blog is a good learning method. It not only reminds me what I had learnt but also helps me to revise for the examination. In the coming lecture, I will learn more advanced knowledge about C program. I will keep to write down my learning from the class in this blog. Hopefully, it can acquire a good skill of writing C program at the end of this semester and become a professional programer one day.

2012年11月6日 星期二

C functions - useful prepackaged modules for programmer



In the CSCI1110, chapter 7 –function was taught from week 7 to week 8. This is one of the key topics in the curriculum of CSCI1110. Now let me summarize what I have learnt from chapter 7 –function.

Part 1

1.1 Contents of the lectures

In chapter 7, I have learnt some fundamental concepts about C functions. What are C functions? Modules in C are called functions. C programs are typically written by combining new functions you write with prepackaged functions available in the C standard library. The C standard library provides a rich collection of functions for performing common mathematical calculations, string manipulations, character manipulations, inputs/outputs, and many other useful operations. This makes the design of the program easier since these functions provide many of the capabilities programmer needs. Therefore, it is very important for a good programmer to acquire a good skill of using C functions. In chapter 7, the knowledge of C functions I had learnt include (1) function definitions, (2) function prototypes, (3) pre-defined function.

(1)   Function definitions :

  • The general format for a function definition is

       Return-value-type function-name( parameter-list)
        {
                Definitions
                Statements
        }

  • The return-value-type states the type of the value returned to the calling function. If a function does not return a value, the return-value-type is declared as void.



  • The function-name is any valid identifier.


  • The parameter-list is a comma-separated list containing the definitions of the variables that will be passed to the function. If a function dose not receive any value, parameter-list is declared as void.




  • The function body is the set of definitions and statements that constitute the function.


  • The arguments passed to a function should match in number, type and order with the parameters in the function definition.


  • When a program encounter a function call, control is transferred from the point of invocation to the called function, the statements of the called function are executed and control returns to the caller.


  • A called function can return control to the caller in one of three ways. If the function does not return a value, control is returned when the function-ending right brace is reached, or by executing the statement return ;

 If the function does return a value, the statement return    
 expression; returns the value of expression.
 

(2)   Function Prototypes :
  • A function prototype declares the function’s return type and declares the number, types, and order of the parameters the function expects to receive.
  • Function prototype enables the compiler to verify the functions are called correctly.
  • The compiler ignores variable names mentioned in the function prototype.
  • Argument in a mixed-type expression are converted to the same type via the C standard’s usual arithmetic conversion rules.

(3)   Pre-defined function :
  • C provides many built-in functions. To call them, we have to know the following info (which can be found from manuals): name, functionality, parameters, return value
  • You also need to know which header file(s) to include. E.g. 
        - To use printf(), you have to include "stdio.h" as
     #include <stdio.h>
   -To use math functions, you have to include "math.h" as
     #include <math.h>

More about C function : 

Website :
http://www2.its.strath.ac.uk/courses/c/section3_9.html

Video:


1.2 Learning Process:

In order to understand the principle of C functions and acquire the techniques of using different functions for performing useful operations, I use different methods to let myself to understand the principle and uses of the techniques during the learning process.

(1)   To understand the principle of C functions in the view of   
        worker-function relationship

The principle of C functions is that, functions are invoked by a function call, which specifies the function name and provides information (as arguments) that the function needs to perform its designated task.

However, this concept is quite abstract and difficult to understand.
In order to understand the principle of C functions clearly, I regard the relationship between the caller and the called function as a worker-function relationship :

A boss (the caller) asks a worker (the called function) to perform a task and report back when the task is done. For example, a function needing to display information on the screen calls the worker function printf to perform that task, then printf display information and reports back – or returns – to the caller when its task is completed. The boss function does not know how the worker functions, and the boss will be unware of this.


Figure showing a boss function communicating with several worker functions in a hierarchical manner.

(2)  Record the common programming error in using C functions.

Since the use of C functions is complex, we may make some programming errors easily in using C function. In acquire the techniques of using different functions for performing useful operations accurately without mistakes or errors, I recorded the common programming error in using C functions and some error-prevention skills during the learning process.
  • Specifying function parameters of the same type as double x,y instead of double x, double y results in a compilation error.
  • Placing a semicolon after the right parenthesis enclosing the parameter list of a function definition is a syntax error.
  • Defining a parameter again as a local variable in a function is a compilation error.
  • Defining a function inside another function is a syntax error.
  • Forgetting the semicolon at the end of a function prototype is a syntax error.
  • Converting from a higher data type in the promotion hierarchy to a lower type can change the data value. Many compilers issue warnings in such cases. 

Part 2

2.1 A interesting topic in the lesson – math library function in C program

A brief description about the math library function in C program :
  
C mathematical operations are a group of functions in the standard library of the C programming language implementing basic mathematical functions.



Math library functions allow programmer to perform certain common mathematical calculations. It is normally used in a program by writing the name of the function followed by left parenthesis followed by the argument of the function followed by a right parenthesis.

Most of the mathematical functions are placed in math.h header (cmath header in C++). 
The functions that operate on integers, such as abs, labs, div, and ldiv, are instead specified in the stdlib.h header (cstdlib header in C++).
Any functions that operate on angles use radians as the unit of angle.


More about C math library :

 

2.2 My opinion, commends, ideas, and further information about math library function in C program

I think Math library function in C program is a very useful tool for solving mathematics or engineering problem in real world. By calling the Math library function in C program, we can perform some complex mathematics calculation or solve some difficult mathematics problem in an easier way.

In the below, there are some advanced examples about use of Math library function that are not included in the lecture.

For example, we can use log2( ) function to convert numbers in the base 10 to the base 2 easily.

#include <math.h>
#include <stdio.h>

  int main(void)
  {
    double val = 1.0;
    do {
      printf("%f %f\n", val, log2(val));
      val++;
    } while (val<11.0);
    return 0;
  }

For the above C program using log2( ) function in the Math library, the following result can be obtained.


Apart from it, the Math library function in C program can also perform more complex mathematics calculation. For example, we may use it to create a matrix, which is commonly used in solving engineering problems.

To create a sparse matrix froma standard numeric array, we may use the mlfSparse()
routine. mlfSparse() converts the numeric array into sparse storage format.

#include <math.h>
#include <stdio.h>

  int main(void)
  {
static double row_subscripts[] = { 3, 4, 5, 4, 5, 6 };
static double col_subscripts[] = { 4, 3, 3, 5, 5, 4 };

mxArray *i = NULL;
mxArray *j = NULL;
mxArray *S = NULL;

mlfAssign(&i, mlfDoubleMatrix(1, 6, row_subscripts, NULL));
mlfAssign(&j, mlfDoubleMatrix(1, 6, col_subscripts, NULL));
mlfAssign(&S, mlfSparse(i, /* Row subscripts */
j, /* Column subscripts */
mlfScalar(9), /* Data */
mlfScalar(8),
mlfScalar(7),
NULL));

mlfPrintMatrix(S);
mlfPrintMatrix(mlfFull(S));

mxDestroyArray(i);
mxDestroyArray(j);
mxDestroyArray(S);

    return 0;
  }

For the above C program using mlfSparse(C math library reference), the following result can be obtained.



In fact, the C Math Library is commonly used as a component in different mathematics or engineering softwares.Fr example, the C Math Library is a component of the MATLAB Compiler. The MATLAB Compiler includes the Compiler, the C Math Library and the Graphics Library. The Math library provides the core math and data analysis routines from MATLAB in object library form. We can use the Math library with the MATLAB Compiler to create math functions based on MATLAB in your external applications ,or embed the Math library in standalone applications.



From these examples, we can see that Math library function is a very useful function in C program. It helps engineer to solve difficult and complex engineering mathematics problem in the real applications. As a engineering student, I must acquire  the techniques of using this function for solving engineering problems.

More about C mathematical function :
http://en.wikipedia.org/wiki/C_mathematical_functions

In the coming lecture, I will learn more advanced knowledge about C program. I will continue to make effort on writing C program and hope that I can acquire a good skill of writing C program at the end of this semester.