Sie sind auf Seite 1von 9

UNIVERSITY OF TECHNOLOGY, JAMAICA

SCHOOL OF COMPUTING & INFORMATION TECHNOLOGY


Programming 1

Lecture # 1: Programming Concepts

System Development Life Cycle (SDLC)


- Is a series of well-defined steps that should be followed when a system is created or changed.
- Represents the big picture of what happens during system creation or modification.

The System Development Life Cycle is comprised of 6 steps, namely:

1. Analyze the current system


2. Define the new system requirements
3. Design the new system
4. Develop the new system
5. Implement the new system
6. Evaluate the new system

The Program Development Cycle (PDC)


- The fourth step of the SDLC (Development of the new system) is comprised of a series of well-
defined steps called the Program Development Cycle.
- A programmer carries out the steps in the PDC.

The steps are outlined as follows:


1. Review the input, processing, output and storage requirements (IPOS)
2. Develop the logic for the program
3. Write the program using a programming language
4. Test and debug the program
5. Complete the program documentation

What is a Program?
- A program is an organized list of instructions that, when executed, causes the computer to
behave in a predetermined manner. Without programs, computers are useless.

What is Programming?
Programming is the process of instructing the computer to accomplish a particular task. It is done
with the help of a programming language. When the program is executed, the instructions will be
converted into machine language, which is the only language that the computer understands.

Writing and Executing Programs in C


C is considered to be a high-level language. These languages were developed so that one single
statement could be written to accomplish substantial tasks and in so doing speed up the
programming process. For the computer to understand these languages a translator program
called a compiler converts them into machine language.

C programs go through 6 phases to be executed:


(1) Edit
(2) Pre-Process
(3) Compile
(4) Link
(5) Load
(6) Execute

1
Identifiers

Manipulation of data is a basic feature of a computer’s abilities. This data must be present in the
memory (RAM) of the computer for operations to be done on it. The computer accesses this data
via memory addresses. Identifiers are required to keep track of these memory addresses
(receptacles, data containers). Identifiers allow us humans to give these ‘data containers’ more
meaningful names. This makes the task of manipulation of data more manageable.
Memory Address Perspectives:
Computer sees - AH010 D4327
2007 We see - YEAR

Computer sees - AH041 C4439


“Tom” We see - FNAME

Random Access Memory (RAM)

Internally the computer sees a HEXIDECIMAL label representing the memory location, we see
familiar titles / labels such as YEAR, FNAME, AGE, which we are able to put into some
context.

Variables
 are identifiers whose value can be changed within a program
 have the following attributes
• a logical name which is descriptive and useful (e.g. total_males, count,
StartDate. Poor examples are total_number_of_males_in_school (too
long) and n1 (too short and not useful).
• Names must not contain certain restricted characters/symbols.
Unacceptable names are Gross Pay (no space allowed) and 1Age
(should not begin with a digit). Case is important based on the
programming language being used.
• a data type (real, integer, string, character, boolean, date)
• a size or length

Constants
 are identifiers whose value cannot be changed within the program

Literals (Literal Constants)


 are values expressed as themselves and are taken at face value

EXAMPLE:
Let CIRC  2 * PI * Rad
CIRC is a variable
2 is a literal
PI is a constant
Rad is a variable

Basic Data Types

Real / Numeric - values from the set of real numbers


(eg. -12.348, 0, 199.0, 1654.984034)

Integers - values from the set of whole numbers


(-3075, -2, 0, 23, 94754)

Character - value from a set of symbols which may be


represented on the computer (a single member of
the
ASCII set of characters) enclosed within quotes,

2
i.e. ‘A’, ‘B’, ‘c’, ‘#’, ‘5’, ‘\’, ‘&’
String - a combination of one or more characters enclosed in
quotes, i.e. “123”, “Tony”, “lj*&^#$$”

Operators, operands, Expressions and statements

Operators - the symbols used in processing to manipulate data


Arithmetic: (+,-, / , *, =, %)
Relational (>, <, >=, <>)
Logical (AND, OR, NOT)

Operands - Can be a variable, a constant, or a literal constant.


- What the operator operates on.

Expressions - consists of operators and operands or an identifier by itself


- it evaluates to a value
- the values are drawn from the data types
- arithmetic expressions can be assigned to a variable

Examples:
Age, gross_pay, NetPay (Identifiers)
120, 3.141, “Hello” (literal constants)
Pi * radius * radius, 12 + 5 * 60 / 10 – x (combination of
operands and operators)

Statement - a complete instruction


- by itself it accomplishes a task
- can be derived from expressions
Evaluating expressions
Arithmetic - follows the general rule of mathematical precedence
i.e. ( ) then powers eg. Xy, then * and /, then + and -

Logical - evaluated to either True [T] or False [F]


- the logical operators are used to connect the relational
expressions

The logical operators are used in compound conditions.


Example: IF SalesAmt > 10000 AND SalesPerson = “Sue”
THEN Bonus = AveSales * 2
ELSE Bonus = AveSales * 1.5
ENDIF

3
The C Programming Language

Character Sets
C does not use nor require the use of every character. It uses the following:

A-Z, a-z, 0-9, . : ; ‘ $ “ # % & ! _ {} [] () <> | + - / * =

C Form
C is considered to be a function language, thus all C programs will consist of at least one
function. It uses only 32 key words, which combine with the formal syntax to form the
programming language.

C is case sensitive and all keywords are lower case.

Layout of Programs

The general form of a C program is as follows:

Preprocessor directives

Function prototypes

Global declarations
/* comments */

main()
{

Local variables and function names; //comment


Statements associated to main;
}

f1()
{
Local variables to function_f1;
Statements associated with function_f1;
}

f2()
{
Local variables to function_f2;
Statements associated with function_f2;
}
.
.
.etc.

Parts of a Program

() {}
Use of the bracket set () in conjunction with function name and {} are used to delimit the
C statements that are associated with that function. { must begin the body of every
function and }must end.

Main
This is a must in every C program. It is where the program actually begins.

Semicolon, slash, statement terminator


Every instruction must terminate with a semicolon (;). Without the semicolon C will
concatenate the various lines of the program and …. to understand them – which it will
not be able to do.

4
Comments
This is a note to a programmer that is placed in the source code. It is always ignored by
the compiler. This does not affect the program. Comments are used primarily to
document the meaning and purpose of the source code, so that the programmer can
remember later how it functions and how to use it. They can be placed anywhere except
in the middle of any C keyword, function name or variable name. There are 2 types of
comments:

i. /* … */
This is used for comments extending over more than one line. /* signals the
beginning of the comment and */ indicates the end.

ii. //
This is used for a comment extending over only one line. There is no signal
ending the comment. The comment ends automatically at the end of the line. //
indicates the beginning of the comment.

Basic Preprocessor Directives


Preprocessing occurs before a program is compiled. All preprocessors directives begin
with # and must start in the first column.

The #include

This causes the copy of a specified file to be included in place of the directive. There are
2 forms:

i. #include <filename>
<> indicates that the preprocessor searches for the file on the system disk. It is
used to add the standard library files to a program.

ii. #include “filename”


The double quotes indicate that the currently working directory should be
searched. This is true when the programmer creates his own additional file such
as a header file.

#define
This creates symbolic constants and macros. The format is:

#define <identifier> <replacement text>

When this line appears in a program, all subsequent occurrences of the identifier will be
automatically replaced by the replacement text before the program is compiled.

Standard Library
C has a rich collection of existing functions called the C Standard Library. These
functions are grouped together based on what they do in what are called header files.
These are included in a program using the #include. The most common header files are:

(1) stdio.h – standard input output file; eg. printf, scanf.


(2) conio.h – console versions of common I/O functions eg. getch, cputs.
(3) stdlib.h – general utilities; eg. NULL, malloc

Data Types
There are 5 basic data types:

(1) int – integer: a whole number, eg. 10 (2 bytes long)


(2) float – floating point value: a number with a fractional part, eg. 10.3 (4 bytes long)
(3) double – a double-precision floating point (8 bytes long)
(4) char – a single character, eg. b (2 bytes long)
(5) void – valueless special purpose type (see Lecture 5)

5
Variables

A variable is any valid identifier. An identifier is a combination of characters consisting


of letters, digits and underscore (_), that does not begin with a digit. An identifier can be
any length but only the first 31 characters are required to be recognized by the C
compiler. C is case sensitive so a1 and A1 are different identifiers.

Format

<Data type> <variable names>;


Eg.
int number;
float average;
char letter;

Constant Data Types


Constants refer to fixed values that may not be affected by the program. There are two
types: #define and const. The const qualifier declares “constant variables” instead of
symbolic constants as with #define.

Format
<constant data type> <variable name> = <value>

Eg.
const float PI = 3.14159;
#define PI = 3.14159

Arithmetic in C
The operators used in C are all binary operators as they each have 2 operands. Eg. a+b.

Basic Operators
The basic operators are:

Add +
Subtract -
Multiply *
Divide /

In C the division result depends on the variable declaration. If it is an integer division, an


integer will result. If a float was declared a float will be the result; eg. 7/4 evaluates to
1.75. To account for the fractions in C the modulus operator (%) is used with variables;
i.e. 7%4 evaluates to 3.

Arithmetic using float and int

Operand1 Operator Operand2 Result


* Int Int
Int
Int * Float Float
Float * Int Float
Float * Float Float
Int / Int Int
Float / Int
Float
Int / Float Impossible
Float / Float Float

6
Assignment Operator
The assignment operator (=) places the values found at the right side of it in the variable
found on the left side. For eg. a = 10+2; means that a is holding the value 12.

Basic Input Output Functions


These functions allow for correspondence between programs and users. The input
function makes the program interactive. These are found in stdio.h.

Format Specifiers
These indicate the data type of the variable to be inputted or outputted.

Conversion Specifiers

Integers: d, i, o, u, x, X, l, h
Floating points: e, E, f, g, G, l, L
Characters & strings: c, s
Scan set: [scan characters], (input only)
Miscellaneous: p, n, %

Input Function
C uses many types of input functions of which scanf is the most commonly used.

Format
scanf(<formatting control string>, <other components>);

Variable address of value to be stored.

Indicates the type of data that should be inputted.

Eg. scanf(“%d”, &integer2);

Means an integer is to be placed in the memory location called integer2.

 scanf processes the control string from left to right and each time it reaches a
specifier it tries to interpret what has been typed as a value. If you input multiple
values then these are assumed to be separated by white space – ie. spaces, new line or
tabs. Thus, 3 4 5 or 3
4
5
does the same.
Therefore, for scanf(“%d %d %d”, &a, &b, &c);

 A scan set is a set of characters enclosed in [ ]. The set then scans the inputted
stream looking for those characters that match characters contained in the set.

Eg. scanf(“%[aeiou]”, &z);

Output Function
Precise output formatting is accomplished with printf. Each contains a control string that
consists of conversion specifiers, field widths, precisions and literal characters.

7
Format
printf(<control string>, <other arguments>);

Corresponds to each specification in the control string.


Described output form

Eg. printf(“Today your age is %d”, age);

Field Width and Precision


 The exact size of a field is the field width. If the field is larger than the data being
printed the data will normally be right justified within that field. An integer
representing the field width is inserted between the % and the specifier.

Eg. printf(“%4d”, 1234);

 Precision is the number of digits to appear after the decimal point. When G and g
are used the precision is the maximum numbers of significant digits to be printed. S
gives the maximum number of characters in the string. To use precision, place a (.)
followed by an integer representing the precision between % and the specifier.

Eg. printf(“%.2f”, 123.456);


≡ 123.46

To specify field width and precision another way can be used.

Eg. printf(“%*.*f”,7,2,98.736);
≡ 98.74

Using Flags
Five flags are available:

- Left justify
+ Always displays sign
Space Displays space if there is no sign
# Use alternate form of specifier
0 Pad with leading zeros

To use play immediate to the right of % several flags can be combined.

Eg. printf(“%+d\n%+d\n”, 786,-786);


≡ +786
-786

# has 5 different modifications:

%#0 Adds a leading zero to the octal value


%#x Adds a leading 0x to the hexadecimal value
%#f or %#e Ensures decimal point is printed
%#g Displays trailing zeros

Eg. printf(“%#0\n”, 1427);


≡ 02623

printf(“%#x\n”, 1427);
≡ 0x593

8
Literals and Escape Sequences
There are certain characters that cannot be printed so easily. They must be represented
by escape sequences which is represented by a back slash (\) and a particular escape
character. These are:

\’ Outputs single quote (‘)


\” Outputs double quotes (“)
\? Outputs question mark
\\ Outputs back slash
\a Causes an audible bell or visual alert
\b Move cursor back 7 positions on current line
\f Moves cursor to the start of next logical page
\n Moves cursor to the beginning of next line
\r Moves cursor to the current line
\t Moves cursor to the next horizontal tab position
\v Moves cursor to the next vertical tab position

Eg. printf(“\n”);
≡ new line

Das könnte Ihnen auch gefallen