Вы находитесь на странице: 1из 6

UNIVERSITY OF TECHNOLOGY, JAMAICA

SCHOOL OF COMPUTING & INFORMATION TECHNOLOGY Programming 1 General Elements of a C Program 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.
1

Semicolon, slash, statement terminator Every instruction must terminate with a semicolon (;). Without the semicolon C will concatenate the various lines of the program. 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. // 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.

ii.

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. #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.

ii.

#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) (2) (3) (4) (5) int integer: a whole number, eg. 10 (2 bytes long) float floating point value: a number with a fractional part, eg. 10.3 (4 bytes long) double a double-precision floating point (8 bytes long) char a single character, eg. b (2 bytes long) void valueless special purpose type (see Lecture 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 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: Floating points: Characters & strings: Scan set: Miscellaneous: d, i, o, u, x, X, l, h e, E, f, g, G, l, L c, s [scan characters], (input only) 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. 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: + Space # 0 Left justify Always displays sign Displays space if there is no sign Use alternate form of specifier 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 %#x %#f or %#e %#g Adds a leading zero to the octal value Adds a leading 0x to the hexadecimal value Ensures decimal point is printed Displays trailing zeros

Eg. printf(%#0\n, 1427); 02623 printf(%#x\n, 1427); 0x593 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: \ \ \? \\ \a \b \f \n \r \t \v Eg. Outputs single quote () Outputs double quotes () Outputs question mark Outputs back slash Causes an audible bell or visual alert Move cursor back 7 positions on current line Moves cursor to the start of next logical page Moves cursor to the beginning of next line Moves cursor to the current line Moves cursor to the next horizontal tab position Moves cursor to the next vertical tab position printf(\n); new line

See the program on the next page for an example of a simple C program, incorporating the above:

/* This program will prompt the user to enter two numbers then determines and outputs the sum of those numbers. Written by: Lisa Shaw Date: January 16, 2010 */ #include <stdio.h> #include <conio.h> main() { int num1, num2, sum; printf("Enter the first number: "); scanf("%d", &num1); //prompts the user for the first number printf("Enter the first number: "); scanf("%d", &num2); // prompts the user for the second number /*adds the two numbers to produce the sum */ sum = num1 + num2; printf("The sum is %d", sum); getch(); return 0;

Вам также может понравиться