Você está na página 1de 8

1.

INTRODUCTION AND R EVISION


C is the most important computer programming language ever invented (by Dennis Ritchie of Bell Lab. at
AT&T in 1972). It is also the most popular programming language so far. Although Java has become a
fashionable and fast growing language due to its platform-independent and Internet applicable features, its
drawbacks in computing efficiency and real-time applications have to be addressed and improved before it can
completely replace C. In fact, most (if not all) operating systems and many UNIX and Windows application
software packages are written in C (or C++). C is a powerful and versatile in terms of computing efficiency,
real-time processing and human-machine interaction. C has become a must to anyone who wants to get a job in
computer science/engineering and IT fields.
But C has many variant versions on various operating systems and machines. C is not as platform-
independent. Nevertheless, ANSI C is fairly portable and is an internationally recognised standard C and is
available in almost all C/C++ software packages or compilers. That is, all C/C++ compilers have ANSI C as an
option. ANSI C is the foundation for C++, an object-oriented (OO) language extended from C (by Bjarne
Stroustrup at AT&T). This course is mainly concerned with ANSI C.

1.1 Review or Overview of C language basics

• C programming language is a block-based computer routines.


• Each block is self-contained function (enclosed by braces {……}), which can take input variables
and generate or return outputs.
• Each statement ends with a semicolon, “ ; ”, except headers.
• A program can have as many function blocks as it requires, but must have a main function, e.g.
int main (void){ ……}, which specifies calculation routines that the program does.
• (Other) functions have to be declared and defined before they can be called and used by the main
function, except for those predefined functions provided in C libraries.

A typical function (including main function) declaration looks like this:


type function_name (take_in_variables)
{
declarations;
statements;
return value; /* not required if type is void */
}

C was originally proposed mainly as a procedure language for scientific calculations, in which routines
were defined according to a plan. However, its use of data structures has led to the concept of encapsulation of
not only various data types but also functions to form classes, which has transformed the old data structures into
"living" objects, the core of object-oriented languages such as C++.

Top-down (procedure) programming style:


type main(void)
{
statements;
……
Functions(a, b, …);
……
return value;
}

Data/Variable names (identifiers) and types:

identifiers: {letter|underscore} or {letter|underscore|digit} upto normally 32 characters.


types: char, int, long, float, double, etc.

Comments:

C: anything between a pair of /* */ (they can be in different lines)


C++: anything after // in one line.

2nd Year High Level Programming in C,  H. Yin, 01/02. 3


Always use meaningful identifiers or variable names and comment every part of the code to make
the code readable and easy to maintain!!

Operators:

+, -, *, /, %, ++, --, =, +=, - =, ( ), >, <, >=, <=, ==, !=, &&, ||, etc.
!!! expression with operator "=" means assignment, NOT A MATHEMATICAL EQUATION!!!
a=a+b;
a=7/2; (int a=3 or float a=3.000000).
a=7/2.0; (int a=3 or float a=3.5000).

a++ or ++a ??? (both when used as a single expression are equivalent to a=a+1;). But they are different.
See the following example:

/*********************************************************************************
* Example1_1: demonstrate the difference between prefix and post fix increments *
* H. Yin *
*********************************************************************************/
#include<stdio.h>

int main(void)
{
int a, b, c=0;

a=++c; /* increment c and then use it, so, c=1, a=1 */


b=c++; /* use c and then increment it, so, b=1, c=2 */

printf("\n%d, %d, %d", a,b,++c); /* 1, 1, 3 are printed */


return 0;
}
/****************************** End of Example1_1 *****************************/

Loops:

if( ), if( ) …else,


for ( ), do{…} while( ),
switch {cases …;}, break, continue.

Functions:

Declaration: type Function_name(var1, var2, ...)

Definition: type Function_name(var1, var2, ...)


{
statements;
……
return value;

Math functions (include<math.h>):

sin( ), cos( ), tan( ), atan( ), sqrt( ), pow( , ), exp( ), log( ), etc.

Basic data storage types:

auto, extern, static, register.

Arrays and strings:

Definition: type array_name[size]; /* array subscripts: 0 to size-1 */

A string is an array of characters with '\0' NULL character (not '0') at the end.

2nd Year High Level Programming in C,  H. Yin, 01/02. 4


/******************************************************************************
* Example1_2: simple array and strings *
* H. Yin *
******************************************************************************/
#include<stdio.h>
#include<string.h>

int main(void)
{
char name[20]="Abc D. Efghi"; /* initialisation */
int i;

printf(“\nname=%s\n”,name); /* name=abc D. Efgh */


for (i=0;i<20;++i) /* print individual characters, one by one */
printf(“%c”,name[i]); /* Abc D. Efgh */

strcpy(name, “ “); /* clear up the name array */


printf(“\nname=%s”,name); /* name= */

strcpy(name, “Bill Clinton“); /* clear up the name array */


printf(“\nname=%s”,name); /* name=Bill Clinton */

strcpy(name, “ “); /* clear up the name array */


name[0]='A';
name[1]='l';
name[2]=’i’;
name[3]=’ ’;
name[4]=’D’;
name[5]=’.’;
name[6]=’ ’;
name[7]=’G’;
name[8]=name[9]=’e’;
name[10]=’\0’;
printf(“\nname=%s”,name); /* name=Ali D. Gee */

return 0;
}
/************************** End of Example1_2 ********************************/

Once a string is declared as an array of characters, its members can only be changed either
individually (assigning each character a value) or using string functions.

Pointers:

A pointer is a memory address of a variable.

Input and output functions:

scanf("formats", variable_addresses);

e.g.
scanf("%f", &a); /* take a real number from input stream (keyboard) and assign it to variable a */

printf("strings and formats", variables);

e.g.
printf("\nThe value of a is: %f", a); /* print out (on screen) the message and
the value of a in float format */

More details for these two functions will be given in Chapter 2.

Files:
fopen(.), fclose(.), fprintf(.),fscanf(.), etc.

2nd Year High Level Programming in C,  H. Yin, 01/02. 5


Fundamentals of a typical C program :

/***************************************************************/
/* comments */ (can be any where)
preprocessors or micros (header files)
function prototypes

type main(void)
{
variable/structure declarations with/without initialisations;

expression/assignment;
function calls;
flow controls;
} statements

return values;
}

function definitions
{
……
}
/*****************************************************************/

Compilation:

cc –o execute_name program_name.c othe_files(.c/.h)

………………………………………………………..…………
: Edit C program code and saved as a source file (program.c) :
:…………………………………………………………………:

compiling process:

Pre-processer: include a copy of header files or function prototypes;
provide access to relevant parts of function libraries.

Compiler: check the syntax of the source code, and if there are no errors,
translate the program into machine language - object file
in UNIX: program.o
in MS-DOS/WINDOWS: program.obj

Linker(Loader): combine the program object file with other pre-defined (library) functions
and/or pre-compiled function object files, into an executable file.
in UNIX: execute_name.anything/nothing, or, a.out by default.
in MS-DOS/WINDOWS: execute_name.exe

The compiler may produce warnings and errors. Warnings may not affect compilation and/or execution
of the program, but an error will stop compilation. There are syntax errors and compile-time errors.

Debugging:

If program is compiled without errors does not necessarily mean that the program is bug-free or even
executable. If errors occur during the execution, the program may stop, or hang, or produce
meaningless outputs or even damaging actions. These errors are called run-time errors. Debugging can
be carried out by single-step execution or by setting breakpoints at selected statements.

UNIX tools: dbx


Windows tools: Borland C/C++, Visual C/C++, etc.

2nd Year High Level Programming in C,  H. Yin, 01/02. 6


1.2 Examples

Task 1: Input a value in miles and convert it to kilometers

Data requirements:

Input: miles
Output: kilometers
Formula: 1 mile=1.609 kilometers

Algorithm:

Get the distance in miles


Convert the distance to kilometers using above formula
Display the distance in kilometers

A flow chart or diagram is always drawn against the algorithm. Pseudo-code methods could also be
used at this stage for programs of small or medium size.

Implementation:

c code (name it as, e.g. mile2km.c):

/******************************************************************************
* mile2km.c: Converting distance in miles to kilometers *
* H. Yin *
******************************************************************************/
#include<stdio.h>
#define KMS_PER_MILE 1.609
/* symbolic constants: by tradition such identifiers in pre-processors are written in capital letters though not necessary */

int main(void) /*or int main() */


{
float miles, kms;

/* Get the distance in miles */


printf("Enter the distance in miles> ");
scanf("%f",&miles);

/* Convert the distance to kilometers */


kms=miles*KMS_PER_MILE;

/* Display the distance in kilometers */


printf("%f miles equal %f kilometers. \n", miles,kms);

return 0; /* or return (0); */


}
/***************************** End of mile2km.c *******************************/

Compile to object file ( .o or .obj, e.g. mile2km.obj) or executable file (a.out or .exe, e.g. mile2km.exe):

cc –o mile2km mile2km.c

Testing (run the program):

mile2km
Enter the distance in miles> 10.0
10.000000 miles equal 16.090000 kilemeters.

2nd Year High Level Programming in C,  H. Yin, 01/02. 7


Task 2: Read in a number of real numbers and print the maximum and minimum values.

/*****************************************************************************
* maxmin.c: Read in n numbers, count them and compute the maximum, *
* minimum, sum and average. *
* H. Yin *
*****************************************************************************/
#include<stdio.h>

float maximum(float x, float y);


float minimum(float x, float y);

int main (void)


{
int i, n;
float max, min, x, sum, avg;

printf("How many numbers do you want to enter? ");


scanf("%d", &n);
printf("\nInput %d real numbers (separated by a space):\n ", n);
scanf("%f", &x);
max=min=sum=x;
avg=x/n;
for (i=2; i<=n; ++i){
scanf("%f", &x);
max=maximum(max, x);
min=minimum(min, x);
sum+=x;
avg+=x/n;
}
printf("\n%s%d\n%s%11.3f\n%s%11.3f\n%s%11.3f\n%s%11.3f\n",
"The number of inputs: ", n,
"Maximum value: ", max,
"Minimu value: ", min,
"Sum: ", sum,
"Average: ", avg);
return 0;
}
float maximum(float x, float y)
{
if (x>y)
return x;
else
return y;
}
float minimum(float x, float y)
{
if (x<y)
return x;
else
return y;
}
/*************************** End of maxmin.c *********************************/

A running result:
C:\People\Hujun\Teaching\4303-2001\examples>maxmin
How many numbers do you want to enter? 6

Input 6 real numbers: 1 23 43 -23.5 6.89234 88

The number of inputs: 6


Maximum value: 88.000
Minimu value: -23.500
Sum: 138.392
Average: 23.065

2nd Year High Level Programming in C,  H. Yin, 01/02. 8


Task 3: String handling-greeting

/******************************************************************************
* name1.c: Enter a name and print a greeting message *
* H. Yin *
******************************************************************************/
#include<stdio.h>
#include<ctype.h>
#define MAXSTRING 100

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

printf("\nHi! What is your name? ");


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

A testing result:
C:\People\Hujun\Teaching\4303-2001/examples>name1

Hi! What is your name? David Beckham

Nice to meet you David Beckham!


Your name spelled backwards is mahkceB divaD
and the letters in your name sum to 1171.

Have a nice day!

Another string handling example:

/**************************************************************************
* names2.c: scanf and gets for strings *
* H. Yin *
**************************************************************************/
#include<stdio.h>
#include<ctype.h>
#define MAXSTRING 100

int main(void)
{
char name1[MAXSTRING], name2[MAXSTRING];

printf("What is your name? ");


gets(name1); /*read in a string stopped by new-line: '\n' */
puts("Pleased to meet you ");
puts(name1);

printf("What is your name again? ");

2nd Year High Level Programming in C,  H. Yin, 01/02. 9


scanf("%s",name2); /*%read in a nonwhite space string*/
printf("\nHello %s!",name2);
/* if put this part in front of above section, then name2 gets the first
name, while name1 gets the middle or last name, as scanf only
takes the first nonspace string, which is the first name, and
may not convert its input and leave them in the stdin buffer,
fflush(stdin) can be used to clear stdin buffer */

return 0;
}
/*************************** End of name2.c ***********************************/

A running result:
C:\People\Hujun\Teaching\4303-2001/examples>names2
What is your name? Alan Smith
Pleased to meet you
Alan Smith

What is your name again?


Alan Smith

Hello Alan !

1.3 Recommended textbooks

1. A Book on C, 3rd edition, Al Kelley and Ira Pohl, The Benjamin Cummings Publishing Company, Inc.,
1995, ISBN 0-8053-1677-9. (£25)
2. The Indispensable Guide to C, Paul Davies, Addison-Wesley, 1995, ISBN 0-201-62438-9. (£25)
3. C How to Program – With Introducing C++ and Java, 3 rd edition, H. M. Deitel and P. J. Deitel, Prentice
Hall, 2000, ISBN-0-13-089572-5.

The first one is highly recommended by professional programmers and is well written, well structured,
compact but also comprehensive. It will be the main textbook for this module. The lecture notes are abstract of
the book with a number of expansions. The second is full of details and explained examples, and is particular
helpful to the beginners. The third book is a newly revised one and covers all aspects of C with fairly through
introduction to C++ and Java.

It is worth mentioning the following two books:

The C Programming Language, B. W. Kernighan and D. M. Ritchie, (1 st edition: 1978), (regarded as C Bible)
The C++ Programming Language, Bjarne Stroustrup, (1st edition: 1985), (regarded as C++ Bible).

1.4 Exercises (unmarked):

1. Write a program that prompts user to enter a power figure (e.g. 60) of a light bulb in watts and then to
calculate both RMS and peak currents (in Amp) it takes and prints on screen.
2. Use printf( ) and scanf( ) functions to write a program that asks you to input your last name, first name,
course title, reg. No. and university name respectively and then prints them in lines on screen.
3. Print all possible characters on your screen (using printf("%c ", a); a=0 to 255).

Even a simple program could take you hours


No one writes perfect programs

2nd Year High Level Programming in C,  H. Yin, 01/02. 10

Você também pode gostar