47
2-1 FE1008 Computing Chapter 2 An Overview of C

FE1008-02(1)

Embed Size (px)

DESCRIPTION

n

Citation preview

2-1

FE1008 Computing

Chapter 2 An Overview of C

2-2

C was designed by Dennis Ritchie of the Bell Laboratories in the early 1970s for writing systems software for the UNIX OS.

History of C

Why is it called C?

It was created from B!

B was created from BCPL

which is designed by Martin Richards (Cambridge) in 1967.

2-3

ANSI C

In 1989, the American National Standards Institute (ANSI) approved a standard for C known as ANSI C, or Standard C (known as C89). It was also accepted as an ISO standard and is known as ANSI/ISO C. New standard: C11 ANSI C is a mature, important, general purpose language that is widely available. We use ANSI C (the C89 Standard) in this course.

2-4

C’s Descendents & Relatives:

• C++ a superset of C

C with Object-Oriented extensions

• Java (from Sun Microsystems) (Coffee Brand) Very popular language

Uses a lot of C/C++ syntax

Internet & platform-independent programming

• C# for Microsoft’s .NET platform

2-5

Variables, Identifiers & Keywords

Variable – a named data storage location in RAM. Identifier – name of a variable. Keywords – predefined words with special meanings, e.g. int, void, float Keyword definitions cannot be changed. Full list for C89 (a total of 32 words) is given on the next slide.

2-6

C89 Keywords

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

Note: Not all keywords will be covered in this course.

2-7

Rules for naming identifiers: • It can contain letters, digits, and the underscore character (_). • It must start with a letter or the underscore.

• It is case sensitive.

• C keywords cannot be used.

Valid names: sum, number_1, exam_mark Invalid names: 1st, matric#, exam mark, float

Always choose meaningful names.

2-8

Constants

C has several types of constants: • Integer constants: -25, 1000 • Floating-point constants: 3.14159265, -1.5E-2, 1.5e-2 • Character constants which are enclosed within a pair of single quotation marks: 'A', '1', '$' • String constants which are enclosed within a pair of double quotation marks:

"This is a string constant."

2-9

Expressions & Statements

An expression consists of variables, constants, and operators (such as +, -, *, /, etc) written according to the syntax of the C language. In C, every expression has a value of a certain type that can be assigned to a variable. Some examples of C expressions: a+b, x+y*z/w, cos(x)

C statements can be formed from expressions: e.g. y = a+b*cos(x);

2-10

Program 2.1 /* This C program will print a message on the computer screen. */ #include <stdio.h> int main(void) { printf("This is my first program.\n"); printf("Programming is easy."); return 0; }

Screen Output:

2-11

Dissection:

#include <stdio.h>

stdio.h = standard input-output header file

• A part of all C development environments.

• Provides information on I/O operations (such as printf here).

• # sign : preprocessor directive. Tells the preprocessor to do something before compiling.

• #include <stdio.h> tells preprocessor to insert the contents of the file stdio.h into our program before compilation.

preprocessor is a program that processes its input data to produce output that is used as input to another program.

2-12

Dissection (continued):

int main(void)

• Starting point for program execution. • One and only one main() function.

• The parentheses after main enclose a definition of what data is to be provided to main() when it starts executing. The word void means that no data needs to be provided to main().

What is a C function?

• A collection of statements for doing a specific task. • A central concept of C programming.

2-13

Dissection (continued):

int main(void)

• A mathematical function has at least one argument (the independent variable) whereas a C function may have 0 or more arguments.

• void means the function has no argument.

• A function may also return a value to its caller.

• Here main() returns an integer value to the operating system.

• int and void are C keywords.

2-14

Dissection (continued):

/* This is a comment */

• This is for inserting comments.

• Computer will ignore all the comment statements.

• It is important to insert comments at suitable places in the program to explain the purpose. This is part of program documentation.

2-15

Dissection (continued):

printf("This is my first program.\n");

• printf() is a function with arguments.

• It sends the string constant:

This is my first program.

to the screen.

• It depends on stdio.h to work.

2-16

Dissection (continued):

\n -- newline character. Moves screen cursor to beginning of next line.

Suppose it is not used in printf():

printf("This is my first program. ");

printf("Programming is easy.");

Output: This is my first program. Programming is easy.

2-17

Dissection (continued):

; The semi-colon indicates the end of a C statement.

return 0; This means main() returns the value 0 to the caller (the Operating System in this case). The return value is not used in this course. Treat the statement as a requirement under ANSI/ISO C.

{ } marks the beginning and end of a block of statements (in this case, the function body).

2-18

Program 2.2

/* This program adds two integers. */ #include <stdio.h> int main(void) { int number1, number2, sum; number1 = 20; number2 = 30; sum = number1 + number2; printf("The sum of %d and %d is %d.", number1, number2, sum); return 0; }

2-19

Declaration of Variables

The line: int number1, number2, sum; is called a declaration statement. The purpose is to ask the computer to reserve 3 memory locations to store values. These locations are called number1, number2, sum and they will be used to store integer numbers (numbers without a fractional part, or without a decimal point). The statement declares 3 integer variables.

2-20

number1

20

number1=20; number2 = 30;

number2

30

sum=number1+number2;

sum

50

printf("The sum of %d and %d is %d.", number1, number2, sum);

Output:

The sum of 20 and 30 is 50.

2-21

Conversion/Format Specifiers

printf("The sum of %d and %d is %d.", number1, number2, sum);

When displaying output, we need to tell the computer what and how to output. Since we are outputting integers, we use the conversion or format specifier %d which is also described as a placeholder. Each integer value requires one %d and each value will be displayed at the corresponding location of the placeholder in the order specified.

2-22

Program 2.3

/* Calculate volume of a cylinder */ #include <stdio.h> int main(void) { float radius, height, volume; printf("This program computes the volume of a cylinder.\n\n"); printf("Input the radius => "); scanf("%f", &radius);

2-23

Program 2.3 (Continued):

printf("Input the height => "); scanf("%f", &height); /* Compute the volume. */ volume = 3.14159*radius*radius*height; printf("The volume is %f.", volume); return 0; }

2-24

3 new items:

(1) float radius, height, volume;

The keyword float is for declaring variables which take floating-point values (numbers with a decimal point). Conversion specifier is %f.

(2) scanf("%f", &radius);

scanf() is for capturing user input.

Note the ampersand (&)character in front of radius.

2-25

(3) The asterisk (*) * denotes multiplication.

Screen Output:

This program computes the volume of a cylinder.

Input the radius => 1.5 Input the height => 5 The volume is 35.342888.

Default: 6 decimal places.

2-26

Program 2.4

/* Solution of a*x*x + b*x + c = 0 */ #include <stdio.h> #include <math.h> int main(void) { double a, b, c, root1, root2; printf("Input the coefficient a => "); scanf("%lf", &a); printf("Input the coefficient b => "); scanf("%lf", &b); printf("Input the coefficient c => "); scanf("%lf", &c);

2-27

Program 2.4 (Continued)

/* Compute the roots. */ root1 = (- b + sqrt(b*b-4*a*c))/(2*a); root2 = (- b - sqrt(b*b-4*a*c))/(2*a); printf("The first root is %8.3f\n“, root1); printf("The second root is %8.3f\n", root2); return 0; }

2-28

New items

#include <math.h> This is needed for using the sqrt() function. double a, b, c, root1, root2; The double data type is similar to float but it represents real numbers with higher precision and a much wider range. The conversion specifier in scanf() is now %lf.

2-29

Suppose we input:

a = 2, b = 6, c = 1

Screen Output:

The first root is –0.177 The second root is –2.823

%8.3f gives 3 decimal places and the number is output using 8 spaces. Note that this is for output use; do not write statements such as

scanf("%8.3f", &a);

scanf("%f\n", &a);

2-30

Program Statement Layout

It is important that you type your program so that the structure is clear. Use indentations (i.e., leave some spaces before the first word for lines inside a block of statements). int main(void) { float radius, height, volume; printf("This program . . ."); printf("Input the radius => "); scanf("%f", &radius);

2-31

Single and Multi-Line Comments

/* This is a multi-line comment */ // This is a single line comment (new in C99, supported by Visual C++ v6.0)

2-32

Note about Program 2.4

Program 2.4 fails if the user inputs 0 for the coefficient a.

We should test the value of a given by the user to see whether it is zero or not.

This is done using the if else decision-making structure. (See Chapter 6 for a more detailed discussion of if else.)

2-33

Program 2.5 (quadratic equation) if (a == 0) /* Is coefficient a zero? Note the double equal sign */

{

printf("You input a = 0.\n");

printf("Only one root: %8.3f", -c/b);

}

else

{ root1 = (-b + sqrt (…))/(2*a);

. . .

}

2-34

Notes on Prog 2.5

Note that the double equal sign is used for checking equality of two values. This will be discussed again in Chapter 6. The two pairs of braces are needed for enclosing each of the blocks of statements belonging to the if and to the else.

2-35

Pseudocode Example 3 (Chapter 1)

INPUT max_time, interval SET accel = 9.8, time = 0 PRINT Table Title WHILE time <= max_time distance = 0.5*accel*time*time SET time = time + interval OUTPUT time, distance END WHILE We’ll implement a version of this algorithm without user-input in the next example.

2-36

Program 2.6 /* Distance travelled by a particle falling under gravity. Initial velocity = 0 */ #include <stdio.h> int main(void) { double time = 0, max_time = 4, interval = 0.5, acceleration = 9.8, distance; printf("Time Elapsed Distance Travelled\n" ); printf("--------------------------------\n" );

2-37

Program 2.6

while (time <= max_time) { distance = 0.5*acceleration*time*time; printf("%8.2f %8.2f\n", time, distance); time = time + interval; } return 0; }

2-38

Screen Output

Time Elapsed Distance Travelled ---------------------------------- 0.00 0.00 0.50 1.23 1.00 4.90 1.50 11.03 2.00 19.60 2.50 30.63 3.00 44.10 3.50 60.03 4.00 78.40

2-39

New Concept: the while loop

while (time <= max_time) { . . . }

The loop body (The part enclosed within the braces) will be executed as long as the condition time <= max_time is TRUE. Loops will be discussed in detail in Chapter 7.

2-40

Exercises

(1) Modify the program so that max_time and interval are both user-input quantities (as specified in the algorithm).

(2) Modify the program assuming that the particle has an initial velocity u which is to be input by the user. The formula is

212

s ut at= +

2-41

Preprocessor Directives & Macros

# indicates a preprocessor directive. Example: #include <stdio.h> There is another preprocessor directive: #define that is frequently used to define constants. It is also said to define a macro.

Example: #define PI 3.14159 #define GST 0.07

2-42

Preprocessor Directives & Macros

The PI and GST defined above are also known as symbolic constants and the names are usually typed in capital letters. General Form: #define macro_name replacement_text This is purely a text replacement command. The preprocessor will replace the macro_name in our program with the replacement text. If we use the symbolic constant PI, Program 2.3 is modified to the form:

2-43

Program 2.3 (Using a macro) #include <stdio.h> #define PI 3.14159 int main(void) { . . . /* Compute the volume. */ volume = PI*radius*radius*height;

Note: During preprocessing, the computer will replace all occurrences of PI (except in comments and quoted strings) with 3.14159. Hence the statement for the calculation of volume will be changed by the preprocessor to: volume = 3.14159*radius*radius*height;

2-44

Preprocessor Directives & Macros

Advantages: (1) Macros may make programs easier to

understand because a name (PI, GST) is easier to understand than a number.

(2) If there is a need to change the value, we

need only change the #define statement. This is advantageous if the same constant is used many times in a program.

2-45

Parameterized Macros

Macros can have parameters. General Form: #define macro_name(parameters) replacement_text

Example: #define CIRCLE_AREA(r) (3.14159*(r)*(r)) How is it used? We may write: volume = CIRCLE_AREA(2.5)*height; This statement will become volume = (3.14159*(2.5)*(2.5))*height; after preprocessing.

2-46

Parameterized Macros Why are there so many parentheses (brackets)? #define CIRCLE_AREA(r) (3.14159*(r)*(r)) This is to guard against mistakes when the parameter r is to be replaced by an expression such as 2.5+a. Without the parentheses, r*r will become 2.5+a*2.5+a which is obviously wrong.

2-47

Parameterized Macros

A macro may have more than one parameter: #define SQUARE(x,y) ((x)*(x)+(y)*(y))

Can this be written in the form below? #define SQUARE(x,y) x*x + y*y

To see that this may be wrong, consider the meaning of the following: diff = SQUARE(3,5) - SQUARE(1,2);