Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Fe1008 02

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

History of C

FE1008 Computing C was designed by Dennis


Ritchie of the Bell Laboratories in
the early 1970s for writing
systems software for the UNIX
Chapter 2 OS.

An Overview of C
Why is it called C?
It was created from B!
B was created from BCPL.

2-1 2-2

ANSI C C’s Descendents & Relatives:


In 1989, the American National Standards • C++ a superset of C
Institute (ANSI) approved a standard for C
known as ANSI C, or Standard C (known as C with Object-Oriented extensions
C89). It was also accepted as an ISO standard
and is known as ANSI/ISO C.
• Java (from Sun Microsystems)
(Coffee Brand) Very popular language
New standard: C99
Uses a lot of C/C++ syntax
ANSI C is a mature, important, general purpose Internet & platform-independent programming
language that is widely available.
• C# for Microsoft’s .NET platform
We use ANSI C (the C89 Standard) in this
course.
2-3 2-4
Variables, Identifiers & Keywords C89 Keywords
Variable – a named data storage location in auto break case char const
RAM.
continue default do double else
Identifier – name of a variable.
Keywords – predefined words with special enum extern float for goto
meanings, e.g. int, void, float if int long register return
Keyword definitions cannot be changed.
short signed sizeof static struct

switch typedef union unsigned void


Full list for C89 (a total of 32 words) is given
on the next slide. volatile while

Note: Not all keywords will be covered in this


2-5 course. 2-6

Rules for naming identifiers: Constants


• It can contain letters, digits, and the C has several types of constants:
underscore character (_).
• Integer constants: -25, 1000
• It must start with a letter or the underscore. • Floating-point constants:
3.14159265, -1.5E-2, 1.5e-2
• It is case sensitive.
• Character constants which are enclosed
• C keywords cannot be used. within a pair of single quotation marks:
'A', '1', '$'
Valid names: sum, number_1, exam_mark • String constants which are enclosed within
Invalid names: 1st, matric#, exam mark, a pair of double quotation marks:
float "This is a string constant."
Always choose meaningful names.
2-7 2-8
Expressions & Statements Program 2.1
An expression consists of variables, constants, /* This C program will print a message
and operators (such as +, -, *, /, etc) written on the computer screen. */
according to the syntax of the C language. #include <stdio.h>
int main(void)
{ printf("This is my first program.\n");
In C, every expression has a value of a certain
printf("Programming is easy.");
type that can be assigned to a variable. Some
return 0;
examples of C expressions:
}
a+b, x+y*z/w, cos(x)
Screen Output:
C statements can be formed from expressions:
e.g. y = a+b*cos(x);
2-9 2-10

Dissection: Dissection (continued):


#include <stdio.h> int main(void)
stdio.h = standard input-output header file • Starting point for program execution.

• A part of all C development environments. • One and only one main() function.

• Provides information on I/O operations (such • The parentheses after main enclose a definition
of what data is to be provided to main() when it
as printf here). starts executing. The word void means that no
• # sign : preprocessor directive. Tells the data needs to be provided to main().
preprocessor to do something before compiling. What is a C function?
• #include <stdio.h> tells preprocessor to • A collection of statements for doing a specific task.
insert the contents of the file stdio.h into our • A central concept of C programming.
program before compilation. 2-11 2-12
Dissection (continued): Dissection (continued):
int main(void)
/* This is a comment */
• A mathematical function has at least one
argument (the independent variable) whereas • This is for inserting comments.
a C function may have 0 or more arguments. • Computer will ignore all the comment
• void means the function has no argument. statements.

• A function may also return a value to its caller. • It is important to insert comments at suitable
places in the program to explain the purpose.
• Here main() returns an integer value to the This is part of program documentation.
operating system.
• int and void are C keywords.
2-13 2-14

Dissection (continued): Dissection (continued):

\n -- newline character. Moves screen cursor to


printf("This is my first program.\n");
beginning of next line.

• printf() is a function with arguments. Suppose it is not used in printf():

• It sends the string constant: printf("This is my first program. ");

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

to the screen. Output:


This is my first program. Programming is easy.
• It depends on stdio.h to work.

2-15 2-16
Dissection (continued): Program 2.2

/* This program adds two integers. */


; The semi-colon indicates the end of a C
#include <stdio.h>
statement.
return 0; int main(void)
This means main() returns the value 0 to the { int number1, number2, sum;
caller (the Operating System in this case). The number1 = 20;
return value is not used in this course. Treat the number2 = 30;
statement as a requirement under ANSI/ISO C. sum = number1 + number2;
printf("The sum of %d and %d is %d.",
{ } marks the beginning and end of a block of
number1, number2, sum);
statements (in this case, the function body).
return 0;
2-17
} 2-18

Declaration of Variables
The line: number1=20; number2 = 30; sum=number1
+number2;
int number1, number2, sum;
is called a declaration statement.
20 30 50
The purpose is to ask the computer to reserve
3 memory locations to store values. These number1 number2
locations are called number1, number2,
sum
sum and they will be used to store integer printf("The sum of %d and %d is %d.",
numbers (numbers without a fractional part, number1, number2, sum);
or without a decimal point). The statement
declares 3 integer variables. Output:
2-19 The sum of 20 and 30 is 50. 2-20
Conversion/Format Specifiers Program 2.3
printf("The sum of %d and %d is %d.", /* Calculate volume of a cylinder */
number1, number2, sum); #include <stdio.h>

When displaying output, we need to tell the int main(void)


computer what and how to output. Since we {
are outputting integers, we use the float radius, height, volume;
conversion or format specifier %d which is
also described as a placeholder. Each integer printf("This program computes the
value requires one %d and each value will be volume of a cylinder.\n\n");
displayed at the corresponding location of the printf("Input the radius => ");
placeholder in the order specified. scanf("%f", &radius);
2-21 2-22

Program 2.3 (Continued): 3 new items:


(1) float radius, height, volume;
printf("Input the height => ");
scanf("%f", &height); The keyword float is for declaring variables
which take floating-point values (numbers with a
/* Compute the volume. */ decimal point). Conversion specifier is %f.
volume = 3.14159*radius*radius*height;
printf("The volume is %f.", volume);
(2) scanf("%f", &radius);
scanf() is for capturing user input.
return 0;
} Note the ampersand (&)character in front of
radius.
2-23 2-24
(3) The asterisk (*) Program 2.4
* denotes multiplication. /* Solution of a*x*x + b*x + c = 0 */
#include <stdio.h>
Screen Output: #include <math.h>

This program computes the volume of a int main(void)


cylinder. { double a, b, c, root1, root2;
printf("Input the coefficient a => ");
Input the radius => 1.5 scanf("%lf", &a);
Input the height => 5 printf("Input the coefficient b => ");
The volume is 35.342888. scanf("%lf", &b);
printf("Input the coefficient c => ");
Default: 6 decimal places. scanf("%lf", &c);
2-25 2-26

New items
Program 2.4 (Continued)

/* Compute the roots. */ #include <math.h>


root1 = (- b + sqrt(b*b-4*a*c))/(2*a); This is needed for using the sqrt() function.
root2 = (- b - sqrt(b*b-4*a*c))/(2*a);
double a, b, c, root1, root2;
printf("The first root is %8.3f\n",
root1); The double data type is similar to float but it
printf("The second root is %8.3f\n", represents real numbers with higher precision
root2); and a much wider range.
The conversion specifier in scanf() is now
return 0; %lf.
}
2-27 2-28
Suppose we input: Program Statement Layout
a = 2, b = 6, c = 1 It is important that you type your program so
that the structure is clear. Use indentations
Screen Output: (i.e., leave some spaces before the first word
The first root is –0.177 for lines inside a block of statements).
The second root is –2.823
int main(void)
%8.3f gives 3 decimal places and the number { float radius, height, volume;
is output using 8 spaces. Note that this is for
output use; do not write statements such as printf("This program . . .");
printf("Input the radius => ");
scanf("%8.3f", &a);
scanf("%f", &radius);
scanf("%f\n", &a);
2-29 2-30

Single and Multi-Line Comments Note about Program 2.4


/* This is a
multi-line Program 2.4 fails if the user inputs 0 for the
coefficient a.
comment
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-
// This is a single line comment making structure. (See Chapter 6 for a more
(new in C99, supported by Visual C++ v6.0) detailed discussion of if else.)

2-31 2-32
Notes on Prog 2.5
Program 2.5 (quadratic equation)
if (a == 0) /* Is coefficient a zero? Note that the double equal sign is used for
Note the double equal sign */ checking equality of two values. This will be
discussed again in Chapter 6.
{
printf("You input a = 0.\n"); The two pairs of braces are needed for
printf("Only one root: %8.3f", -c/b); enclosing each of the blocks of statements
} belonging to the if and to the else.

else
{ root1 = (-b + sqrt (…))/(2*a);
. . .
} 2-33 2-34

Pseudocode Example 3 (Chapter 1) Program 2.6


/* Distance travelled by a particle falling under
INPUT max_time, interval gravity. Initial velocity = 0 */
SET accel = 9.8, time = 0
PRINT Table Title #include <stdio.h>
WHILE time <= max_time
distance = 0.5*accel*time*time int main(void)
SET time = time + interval {
double time = 0, max_time = 4, interval = 0.5,
OUTPUT time, distance acceleration = 9.8, distance;
END WHILE
printf("Time Elapsed Distance Travelled\n" );
We’ll implement a version of this algorithm printf("--------------------------------\n" );
without user-input in the next example.
2-35 2-36
Program 2.6 Screen Output

while (time <= max_time) Time Elapsed Distance Travelled


----------------------------------
{
0.00 0.00
distance = 0.5*acceleration*time*time;
0.50 1.23
printf("%8.2f %8.2f\n", time, distance);
1.00 4.90
time = time + interval;
1.50 11.03
}
2.00 19.60
return 0;
2.50 30.63
}
3.00 44.10
3.50 60.03
4.00 78.40

2-37 2-38

New Concept: the while loop Exercises


while (time <= max_time) (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
The loop body (The part enclosed within the to be input by the user. The formula is
braces) will be executed as long as the
condition time <= max_time is TRUE. 1
s = ut + at 2
Loops will be discussed in detail in Chapter 7. 2

2-39 2-40
Preprocessor Directives & Macros Preprocessor Directives & Macros
# indicates a preprocessor directive. The PI and GST defined above are also known
Example: #include <stdio.h> as symbolic constants and the names are
usually typed in capital letters.
There is another preprocessor directive:
General Form:
#define that is frequently used to define
constants. It is also said to define a macro. #define macro_name replacement_text

Example: This is purely a text replacement command. The


#define PI 3.14159 preprocessor will replace the macro_name in
#define GST 0.07 our program with the replacement text. If we
use the symbolic constant PI, Program 2.3 is
2-41
modified to the form: 2-42

Program 2.3 (Using a macro) Preprocessor Directives & Macros

#include <stdio.h> Advantages:


#define PI 3.14159 (1) Macros may make programs easier to
int main(void) understand because a name (PI, GST) is
{ . . . easier to understand than a number.
/* Compute the volume. */
volume = PI*radius*radius*height;
(2) If there is a need to change the value, we
Note: During preprocessing, the computer will replace need only change the #define statement.
all occurrences of PI (except in comments and quoted This is advantageous if the same constant is
strings) with 3.14159. Hence the statement for the used many times in a program.
calculation of volume will be changed by the
preprocessor to:
volume = 3.14159*radius*radius*height;
2-43 2-44
Parameterized Macros Parameterized Macros
Macros can have parameters. Why are there so many parentheses (brackets)?
General Form: #define CIRCLE_AREA(r) (3.14159*(r)*(r))
#define macro_name(parameters) replacement_text

This is to guard against mistakes when the


Example:
parameter r is to be replaced by an expression
#define CIRCLE_AREA(r) (3.14159*(r)*(r))
such as 2.5+a. Without the parentheses, r*r will
How is it used? We may write:
become 2.5+a*2.5+a which is obviously wrong.
volume = CIRCLE_AREA(2.5)*height;
This statement will become
volume = (3.14159*(2.5)*(2.5))*height;
after preprocessing.

2-45 2-46

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);


2-47

You might also like