Sie sind auf Seite 1von 11

Introduction to C

CHAPTER 6 INTRODUCTION TO C
Objectives
History of C Features of C Structure of a C program Constants Variables Data types

6.1History of C C was evolved from ALGOL, BCPL (Basic Combined Programming) and B by Dennis Ritchie at Bell Laboratories in 1972. C uses many concepts from these languages and added the concept of data types and other powerful features. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost entirely in C. Today, C is running under a variety of operating system and hardware platforms. 6.2 Features of C It is a robust language whose rich set of built-in functions and operators can be used to write any complex program. The C compiler combines the capabilities of an assembly language with the features of a high-level language and therefore it is well suited for writing both system software and business packages. Programs written in C are efficient and fast. This is due to its variety of data types and powerful operators. It is many times faster than BASIC. C is highly portable. This means that C programs written for one computer can be run on another with little or no modifications. Portability is important if we plan to use a new computer with a different operating system. C language is well suited for structured programming, thus requiring the user to think of a problem in terms of function modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes a program debugging, testing and maintenance easier. Another important feature of C is its ability to extend itself. C library supports a collection of functions.

Introduction to C 6.3 Structure of a C program A C program would look like, Header file Section main() { declaration part; execution part; } C supports several library functions. Library functions are grouped category wise and stored in different files known as header files. If we want to access the functions stored in the library, it is necessary to tell the compiler about the files to be accessed. This is achieved by using the preprocessor directive #include as follows: #include <filename> filename is the name of the library file that contains the required function definition. Every C program must have one main() function. This contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable parts end with a semicolon. 6.3.1 A Sample Program main() { /*--------- Beginning of the program--------*/ printf(This is a sample program); /*--------- End of the program--------*/ } This program will produce the Output: This is a sample program The program has a main() function and the execution begins at this line. The main() is a special function used by the C system to tell the computer where the program starts. Every program must have exactly one main function. If we use more than one main function, the compiler cannot tell which one marks the beginning of the program. The empty pair of parentheses immediately following main indicates that the function main has no arguments.

Introduction to C The opening brace { indicates the beginning of the function main and the closing brace } indicates the end of the function. All the statements between these two braces form the function body. These statements terminated by a semicolon (;). Comment lines The lines beginning with /* and ending with */ are known as Comment lines. These are used in a program to enhance its readability and understanding. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. printf(This is a sample program); printf is a predefined standard C function for printing output. Predefined means that it is a function that is written, compiled and linked together with the program. This concept is explained in the next chapter. Executing a C program An operating system is a program that controls the entire operation of a computer system. All input/output operations are channeled through the operating system. The operating system, which is an interface between the hardware and the user, handles the execution of user programs. C programs runs under both UNIX and MS-DOS operating systems. UNIX System Once we load the UNIX operating system into the memory, the computer is ready to receive program. The program must be entered into a file. The files are created with the help of the text editor, either ed or vi. The command for calling the editor and creating the file is ed filename When the editing is over, the file is saved on disk. It can be referenced any time later by its file name. The program is entered into the file is known as the source program. Compiling and Linking If the source program has been created in a file then it is ready for compilation. The compilation command is, cc filename The compiled program is called the executable object code and is stored automatically in another file called a.out. The command for executing the program is a.out

Introduction to C 6.4 C Character set The characters in C are grouped into the following categories: 1. Letters : Uppercase AZ and Lowercase a.z 2. Digits : All decimal digits 09 3. Special characters :.,;:?!|/!$-_%\@#^&*()+{}[]() 4. White spaces C is case sensitive. That means the lowercase and uppercase letters are different not same. 6.5 C Tokens The smallest individual units in a C program are known as C tokens.

CTokens

Keywords

Constants

Strings

Operators

Identifiers

Special Symbols

6.5.1 Keywords All keywords have fixed meanings and these meanings cannot be changed. C keywords -----------------------------------------------------------------------------------------------auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while -----------------------------------------------------------------------------------------------6.5.2 Identifiers Identifiers refer to the names of variables, functions and arrays. These are user-defined names and consist of a sequence of letters and digits.

Introduction to C Rules for Identifiers: 1. First character must be an alphabet or underscore. 2. Must consist of only letters, digits or underscore. 3. Cannot use a keyword. 4. Must not contain white space. 6.5.3 Constants A constant is a quantity whose value cannot change during the program execution. CONSTANTS

Numeric

Character

Integer constants

Real constants

Single character

String constants

6.5.3.1 Integer constants An integer constant refers to a sequence of digits. There are 3 types of integer constants namely, decimal, octal and hexadecimal integer. Decimal integers consist of a set of digits, 0 through 9, preceded by an optional or + sign. For example, 123 425 +78 Octal integers constant consists of any combination of digits from the set 0 through 7, with a leading 0. Some examples of octal integers are: 037 0 0435 0551 A sequence of digits preceded by 0x or 0X is considered as Hexadecimal integer. They may also include alphabets A through F or a through f. 0X2 0x9F 0Xbed 6.5.3.2 Real constants Numbers containing fractional parts like 17.893 represents the numbers. Such numbers are called Real or Floating Point constants. For example, 0.00082 -2.78 +6.302

Introduction to C a real number may also be expressed in exponential notation. For example, the number 12389.765 represented as 1.2389765e4 in exponential notation. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation. The exponent is an integer number with an optional + of -. Eg: 0.654e7 12E-4 -1.5e-1 The letter e may be uppercase or lowercase letter. 6.5.3.3 Single character constants A single character within single quotes ( ) is called a Character constant. For example, 5 V The character may be anything from these character sets. 6.5.3.4 String constants A sequence of characters enclosed within double quotes ( ) is called String constant. Example: Hello A+B This is a text 6.6 Variables A Variable is a quantity, which may change its value during the execution of the program. It is a storage location where you can store a value. The name of the variables must follow the rules of identifiers. Valid variable names are: Mark mark average John distance height In the above examples, Mark and mark are different variable names. The variable names should not contain special characters. The first character should be an alphabet. 6.7 Data types C language supports three types of data types. 1. Primary (or fundamental) data types 2. Derived data types

Introduction to C 3. User-defined data types

C supports five fundamental data types, namely integer (int), floating point (float), character (char), double-precision floating point (double) and void. Data Type Range of values Char Int Float Double -128 to 127 -32,768 to 32,767 3.4e-38 to 3.4e+38 1.7e-308 to 1.7e+308

6.7.1 Integer types Integers are whole numbers with a range of values. The size of an integer that can be stored depends on the computer. C has 5 classes of integer storages. They are: short int int long int signed int unsigned int

Type
char or signed char unsigned char Int or signed int Unsigned int short int or signed short int unsigned short int long int or signed long int 8 16 16 16 8 8 32

Size
-128 to 127 0 to 255

Range

-32,768 to 32,767 0 to 65535 -128 to 127 0 to 255 -2,147,483,648 to 2,147,483,647

Introduction to C unsigned long int Float Double long double 32 32 64 80 0 to 4,294,967,295 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308 3.4E-4932 to 1.1E+4932

6.7.2 Floating Point Types Floating point types are used to store floating point numbers. 6.7.3 Character Types Character types are used to store characters. 6.8 Declaration of variables The general format for declaring the variables is: datatype v1,v2,..vn; v1,v2,,vn are variable names. The commas separate these variables. This statement is terminated by semicolon; for example, int count; int no,total; double ratio; 6.9 Defining symbolic constant #define symbolic-name value of constant Example: #define PI 4.14 #define STRENGTH 100 Symbolic names are written in CAPITALS to visually distinguish from the normal variable names. #define statements must not end with a semicolon. 6.10 Declaring a variable as constant We can declare the variable as constant with the qualifier const. For example, const int size=60; const is a new keyword. 6.11 Using enumerations

Introduction to C The third technique to declare constants is called Enumeration. An enumeration defines a set of constants. In C an enumerator is of type int. The enumeration is still useful to define a set of constants instead of using multiple #defines. The general format is: enum identifier { value1, value2, . . . . , value n}; The identifier is a user-defined enumerated data type, which can be used to declare variables that can have one of the values enclosed in the braces. The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants. That is, value 1 is assigned 0, value2 is assigned 1, and so on. Example: enum SEASONS {WINTER, SPRING, SUMMER, AUTUMN}; Here, WINTER = 0, SPRING = 1, SUMMER = 2, AUTUMN = 3. Another example, enum COLOR { RED, BLUE, GREEN}; enum COLOR background, foreground; background=RED; foreground=GREEN; Each enumerated constant (sometimes called an enumerator) has an integer value. Unless specified, the first constant has a value of zero. The values increase by one for each additional constant in the enumeration. So, RED equals 0, BLUE equals 1, and GREEN = 2. SQUARE equals 0, RECTANGLE equals 1, TRIANGLE equals 2 and so forth. The values of each constant can also be specified. enum SHAPE {SQUARE=5,RECTANGLE,TRIANGLE=17,CIRCLE,ELLIPSE}; Here, SQUARE equals 5, RECTANGLE equals 6, TRIANGLE equals 17, CIRCLE equals 18 and ELLIPSE equals 19. #include <stdio.h> enum days {monday=1,tuesday,wednesday,thursday,friday,saturday,sunday}; int main() { enum days today = monday; if ((today == saturday) || (today == sunday)) { printf("Weekend\n"); } else { printf("Go to work or school\n"); } return 0; }

Introduction to C There are a few things to note in this example. First, is clearer to use the enumeration than the #defines used in the earlier example. Next, the variable today is of type int, as are all enumerators. Any expression that can be assigned to an int variable can be assigned to "today". The compiler will not catch bound errors as would occur in C++. For instance, the follow assignment, an error, could appear in the program and not be flagged by the compiler. today = 9999; /* Error, today should be between 1 and 7 */ Look at the following examples to understand how to assign values to the constants in enumerations.

Summary
Every C program requires a main ( ) function. The program execution begins at the main. Every statement in a C program must end with a semicolon. A comment can be inserted at anywhere in a program. This increases the readability and understandability of the program. The comment line starts with the symbol /* and */. Identifiers must be start with an alphabet. Dont use keywords as identifiers. Special characters not allowed in identifiers. All variables must be initialized before they are used in the program. A variable is declared as a constant either by using the preprocessor command #define or by declaring it with the qualifier const. No space between # and define. Integer constants, by default, assume int types. Floating-point constants default to double. The character # should be in the first column. Do not give any space between # and define.

Review Questions
State whether true or false 1. 2. 3. 4. 5. Every line in a C program should end with a semicolon. main() is where the program begins its execution. Syntax errors will be detected by the compiler. Declarations can appear anywhere in a program. The scanf function is used to read only one value at a time.

Fill in the blanks 1. ___________ function is used to display the output on the screen. 2. Character constants are enclosed in _________ quotes.

Introduction to C 3. By default, floating-point constants are ________ type.

Das könnte Ihnen auch gefallen