? PROGRAMMING FUNDAMENTALS USING “C” Subject: PROGRAMMING FUNDAMENTALS USING “C” Credits: 4 SYLLABUS Introduction to „C‟ Language Structures of ‘C’ Programming. Constants and Variables, C Tokens, Operators, Types of operators, Precedence and Associativity, Expression , Statement and types of statements Built-in Operators and function Console based I/O and related built-in I/O function, Concept of header files, Preprocessor directives, Decision Control structures, The if Statement, Use of Logical Operators, The else if Clause. Loop Control structures Nesting of loops , Case Control Structure, using Switch Introduction to problem solving, Problem solving techniques (Trial & Error, Brain storming, Divide & Conquer), Steps in problem solving (Define Problem, Analyze Problem, Explore Solution), Algorithms and Flowcharts (Definitions, Symbols), Characteristics of an algorithm Simple Arithmetic Problems Addition / Multiplication of integers, Functions, Basic types of function, Declaration and definition, Function call, Types of function, Introduction to Pointers, Pointer Notation, Recursion. Storage Class Automatic Storage Class , Register Storage Class, Static Storage Class, External Storage Class Suggested Readings: 1. Mastering C by Venugopal, Prasad – TMH 2. Complete reference with C Tata McGraw Hill 3. C – programming E.Balagurusamy Tata McGray Hill 4. How to solve it by Computer : Dromey, PHI 5. Schaums outline of Theory and Problems of programming with C : Gottfried 6. The C programming language : Kerninghan and Ritchie 7. Programming in ANSI C : Ramkumar Agarwal 8. Mastering C by Venugopal, Prasad – TMH 9. Let Us C by Kanetkar P R O G R A M M I N G F U N PROGRAMMING FUNDAMENTALS USING ‘C’ D A M E N T A L S U S I COURSE OVERVIEW N G ‘ C ’ The computing world has undergone a revolution since the Although we have noted the places where the language has publication of The C Programming Language in 1978. Big evolved, we have chosen to write exclusively in the new form. computers are much bigger, and personal computers have For the most part, this makes no significant difference; the capabilities that rival mainframes of a decade ago. During this most visible change is the new form of function declaration and time, C has changed too, although only modestly, and it has definition. Modern compilers already support most features of spread far beyond its origins as the language of the UNIX the standard. operating system. C is not a big language, and it is not well served by a big book. The growing popularity of C, the changes in the language over We have improved the exposition of critical features, such as the years, and the creation of compilers by groups not involved pointers, that are central to C programming. We have refined the in its design, combined to demonstrate a need for a more original examples, and have added new examples in several precise and more contemporary definition of the language than chapters. For instance, the treatment of complicated declarations the first edition of this book provided. In 1983, the American is augmented by programs that convert declarations into words National Standards Institute (ANSI) established a committee and vice versa. As before, all examples have been tested directly, whose goal was to produce “an unambiguous and machine- which is in machine-readable form. independent definition of the language C”, while still retaining As we said in the preface to the C “wears well as one’s experi- its spirit. The result is the ANSI standard for C. ence with it grows”. With a decade more experience, we still feel It provides a new form of function declaration that permits that way. We hope that this book will help you learn C and use cross-checking of definition with use. It specifies a standard it well. library, with an extensive set of functions for performing input and output, memory management, string manipulation, and similar tasks. It makes precise the behavior of features that were not spelled out in the original definition, and at the same time states explicitly which aspects of the language remain machine- dependent. i P R O G R PROGRAMMING FUNDAMENTALS USING ‘C’ A M M I N G CONTENT F U N . Lesson No. Topic Page No. D A M E N Lesson 1 Concepts of Data storage within a computer program 1 AT L S Lesson 2 Concept of variable, constant and preprocessor U S directive statements. 4 IN G Lesson 3 Elements of Language : Expressions, Statements, Operators 10 ‘ C ’ Lesson 4 Binary & Relational Operators 13 Lesson 5 Branching Constructs 15 Lesson 6 Precedence of Operators 19 Lesson 7 Controlling Program Execution 23 Lesson 8 While & Do While Loop 30 Lesson 9 Break Statement 33 Lesson 10 Switch Statement 38 Lesson 11 Functions 43 Lesson 12 Writing a Function 47 Lesson 13 Function Prototype & Recursive Function 51 Lesson 14 Introduction to Arrays 55 Lesson 15 Naming and Declaring Arrays 58 Lesson 16 Types of I/O & Console I/O Functions 63 Lesson 17 Escape Sequences 66 Lesson 18 Formatted output conversion specifiers 70 Lesson 19 Character Input &Character Output 73 Lesson 20 Stream I/O 76 Lesson 21 Scope of Veriables 80 Lesson 22 Scope of Function Parameters 84 Lesson 23 Input and Output Redirection 88 Lesson 24 Command Line Arguments 92 Lesson 25 Introduction to Structures and Unions 94 Lesson 26 Arrays of Structures 99 Lesson 27 Introduction to typedef & Macro 104 Lesson 28 Details of Unions 107 Lesson 29 Introductions to Bits & Its Operators 112 Lesson 30 Dynamic Memory Allocation 114 Lesson 31 Functions of Dynamic Memory Allocation 118 Lesson 32 Verification and Validation 122 iii P R O G R A PROGRAMMING FUNDAMENTALS USING ‘C’ M M I N G CONTENT F U N D Lesson No. Topic Page No. A M Lesson 33 Testing strategies 126 E N T Lesson 34 Error Handling Functions 130 A L S Lesson 35 Types of Errors 134 U S I N G ‘ C ’ iv P R O G LESSON 1 R A M CONCEPTS OF DATA STORAGE WITHIN A COMPUTER PROGRAM M I N G Objectives One typewritten page Approximately 3,000 F U The RAM in your computer is organized sequentially, one byte N • Know how the computer memory is organized. D following another. Each byte of memory has a unique address A • Know about the memory space required to store data M by which it is identified—an address that also distinguishes it E • Know what a variable is? And the different types of variables from all other bytes in memory. Addresses are assigned to N T Computer programs usually work with different types of data memory locations in order, starting at zero and increasing to the AL and need a way to store the values being used. These values can system limit. For now, you don’t need to worry about ad- S U be numbers or characters. C has two ways of storing number dresses; it’s all handled automatically by the C compiler. S I N values—variables and constants—with many options for each. What is your computer’s RAM used for? It has several uses, but G A variable is a data storage location that has a value that can only data storage need concern you as a programmer. Data is the ‘ C change during program execution. In contrast, a constant has a information with which your C program works. Whether your ’ fixed value that can’t change. program is maintaining an address list, monitoring the stock Today you will learn: market, keeping a household budget, or tracking the price of hog bellies, the information (names, stock prices, expense • How to create variable names in C amounts, or hog futures) is kept in your computer’s RAM • The use of different types of numeric variables while the program is running. • The differences and similarities between character and Now that you understand a little about the nuts and bolts of numeric values memory storage, you can get back to C programming and how • How to declare and initialize numeric variables C uses memory to store information. • C’s two types of numeric constants Variables • Before you get to variables, however, you need to know a A variable is a named data storage location in your computer’s little about the operation of your computer’s memory. memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there. Computer Memory If you already know how a computer’s memory operates, you Variable Names can skip this section. If you’re not sure, however, read on. This To use variables in your C programs, you must know how to information will help you better understand certain aspects of C create variable names. In C, variable names must adhere to the programming. following rules: A computer uses random-access memory (RAM) to store • The name can contain letters, digits, and the underscore information while it’s operating. RAM is located in integrated character (_). circuits, or chips, inside your computer. RAM is volatile, which • The first character of the name must be a letter. The means that it is erased and replaced with new information as underscore is also a legal first character, but its use is not often as needed. Being volatile also means that RAM “remem- recommended. bers” only while the computer is turned on and loses its • Case matters (that is, upper- and lowercase letters). Thus, the information when you turn the computer off. names count and Count refer to two different variables. Each computer has a certain amount of RAM installed. The • C keywords can’t be used as variable names. A keyword is a amount of RAM in a system is usually specified in kilobytes word that is part of the C language. (A complete list of 33 C (KB) or megabytes (MB), such as 512KB, 640KB, 2MB, 4MB, or keywords can be found in Appendix B, “Reserved Words.”) 8MB. One kilobyte of memory consists of 1,024 bytes. Thus, a system with 640KB of memory actually has 640 * 1,024, or The following list contains some examples of legal and illegal C 65,536, bytes of RAM. One megabyte is 1,024 kilobytes. A variable names: machine with 4MB of RAM would have 4,096KB or 4,194,304 Variable Name Legality bytes of RAM. Percent Legal The byte is the fundamental unit of computer data storage. y2x5__fg7h Legal Memory space required to store data. annual_profit Legal Data Bytes Required _1990_tax Legal but not advised The letter x 1 savings#account Illegal: Contains the illegal character # The number 500 2 double Illegal: Is a C keyword The number 241.105 4 9winter Illegal: First character is a digit The phrase Teach Yourself C 17 1 P Because C is case-sensitive, the names percent, PERCENT, and • Integer variables come in two flavors: signed integer variables R O Percent would be considered three different variables. C can hold positive or negative values, whereas unsigned G R programmers commonly use only lowercase letters in variable integer variables can hold only positive values (and 0). A M names, although this isn’t required. • Floating-point variables hold values that have a fractional M Using all-uppercase letters is usually reserved for the names of part (that is, real numbers). I N G constants. Within each of these categories are two or more specific variable F For many compilers, a C variable name can be up to 31 charac- types. These are summarized in the table given below. It also U N ters long. (It can actually be longer than that, but the compiler shows the amount of memory, in bytes, required to hold a D A looks at only the first 31 characters of the name.) With this single variable of each type when you use a microcomputer with M flexibility, you can create variable names that reflect the data 16-bit architecture. E N being stored. For example, a program that calculates loan T Table. C’s numeric data types. A payments could store the value of the prime interest rate in a L S variable named interest rate. The variable name helps make its Variable Type Keyword Bytes Required Range U S usage clear. You could also have created a variable named x or Character char 1 -128 to 127 I NG even Johnny Carson; it doesn’t matter to the C compiler. The Integer int 2 -32768 to 32767 ‘C use of the variable, however, wouldn’t be nearly as clear to Short integer short 2 -32768 to 32767 ’ someone else looking at the source code. Although it might Long integer long 4 -7,483,648 take a little more time to type descriptive variable names, the improvements in program clarity make it worthwhile. to2,147,438,647 Many naming conventions are used for variable names created Unsigned unsigned 1 0 to 255 from multiple words. character char You’ve seen one style: Unsigned unsigned 2 0 to 65535 integer int interest_rate. Using an underscore to separate words in a variable name makes it easy to interpret. The second style is Unsigned unsigned 2 0 to 65535 called camel notation. Instead of using spaces, the first letter of short integer short each word is capitalized. Instead of interest_rate, the variable Unsigned unsigned 4 0 to 4,294, would be named InterestRate. Camel notation is gaining long integer long 967,295 popularity, because it’s easier to type a capital letter than an Single- Float 4 1.2E-38 underscore. We use the underscore in this book because it’s precision to3.4E381 easier for most people to read. You should decide which style floating-point you want to adopt. Double- Double 8 2.2E-308 • DO use variable names that are descriptive. precision f to1.8E3082 • DO adopt and stick with a style for naming your variables. loating-point • DON’T start your variable names with an underscore 1. Approximate range; precision = 7 digits unnecessarily. 2. Approximate range; precision = 19 digits. • DON’T name your variables with all capital letters Approximate range means the highest and lowest values a given unnecessarily. variable can hold. (Space limitations prohibit listing exact ranges Numeric Variable Types for the values of these variables.) Precision means the accuracy with which the variable is stored. C provides several different types of numeric variables. You (For example, if you evaluate 1/3, the answer is 0.33333... with need different types of variables because different numeric 3s going to infinity. A variable with a precision of 7 stores seven values have varying memory storage requirements and differ in 3s.) the ease with which certain mathematical operations can be performed on them. Looking at Table, you might notice that the variable types int and short are identical. Why are two different types necessary? Small integers (for example, 1, 199, and -8) require less memory The int and short variable types are indeed identical on 16-bit to store, and your computer can perform mathematical IBM PC-compatible systems, but they might be different on operations (addition, multiplication, and so on) with such other types of hardware. On a VAX system, a short and an int numbers very quickly. In contrast, large integers and floating- aren’t the same size. Instead, a short is 2 bytes, whereas an int is point values (123,000,000 or 0.000000871256, for example) 4. Remember that C is a flexible, portable language, so it require more storage space and more time for mathematical provides different keywords for the two types. If you’re operations. By using the appropriate variable types, you ensure working on a PC, you can use int and short interchangeably. that your program runs as efficiently as possible. No special keyword is needed to make an integer variable C’s numeric variables fall into the following two main catego- signed; integer variables are signed by default. You can, how- ries: ever, include the signed keyword if you wish. The keywords • Integer variables hold values that have no fractional part (that is, whole numbers only). 2 shown in Table are used in variable declarations, which are P R discussed in the next section. O G There are five things you can count on: R A • The size of a char is one byte. M M • The size of a short is less than or equal to the size of an int. IN G • The size of an int is less than or equal to the size of a long. L F • The size of an unsigned is equal to the size of an int. UN D The size of a float is less than or equal to the size of a double. A M Notes E N T A L S U S I N G ‘ C ’ 3 P R O G R LESSON 2 A M CONCEPT OF VARIABLE, CONSTANT AND PREPROCESSOR DIRECTIVE STATEMENTS M I N G F Objectives 8. Define a constant called GST with a value of .125 U ND • Know how to declare a variable. #define GST 0.125 A M • Know how to initialize a variable. The typedef Keyword EN • Know what a constant is? And the different types of The typedef keyword is used to create a new name for an T A constants. existing data type. In effect, typedef creates a synonym. For L S • Know about the pre-processor directive statements. example, the statement U S Variable Declarations typedef int integer; I N G Before you can use a variable in a C program, it must be creates integer as a synonym for int. You then can use integer to ‘C declared. A variable declaration tells the compiler the name and define variables of type int, as in this example: ’ type of a variable and optionally initializes the variable to a integer count; specific value. If your program attempts to use a variable that Note that typedef doesn’t create a new data type; it only lets you hasn’t been declared, the compiler generates an error message. A use a different name for a predefined data type. variable declaration has the following form: The most common use of typedef concerns aggregate data typename varname; types, “Structures.” typename specifies the variable type and must be one of the An aggregate data type consists of a combination of data types keywords listed in Table varname is the variable name, which presented in this lesson. must follow the rules mentioned earlier. Initializing Numeric Variables You can declare multiple variables of the same type on one line When you declare a variable, you instruct the compiler to set by separating the variable names with commas: aside storage space for the variable. However, the value stored in int count, number, start; /* three integer variables */ that space—the value of the variable—isn’t defined. It might be float percent, total; /* two float variables */ zero, or it might be some random “garbage” value. Before When we learn about “Understanding Variable Scope,” you’ll using a variable, you should always initialize it to a known learn that the location of variable declarations in the source code value. You can do this independently of the variable declaration is important, because it affects the ways in which your program by using an assignment statement, as in this example: can use the variables. For now, you can place all the variable int count; /* Set aside storage space for count */ declarations together just before the start of the main() count = 0; /* Store 0 in count */ function. Note that this statement uses the equal sign (=), which is C’s Excercise assignment operator. The one in programming is not the same 1. Declare an integer called sum as the equal sign in algebra. If you write x = 12in an algebraic int sum; statement, you are stating a fact: 2. Declare a character called letter “x equals 12.” char letter; In C, however, it means something quite different: “Assign the value 12 to the variable named x.” 3. Define a constant called TRUE which has a value of 1 You can also initialize a variable when it’s declared. To do so, #define TRUE 1 follow the variable name in the declaration statement with an 4. Declare a variable called money which can be used to hold equal sign and the desired initial value: currency int count = 0; float money; double percent = 0.01, taxrate = 28.5; 5. Declare a variable called arctan which will hold scientific Be careful not to initialize a variable with a value outside the notation values (+e) allowed range. Here are two examples of out-of-range double arctan; initializations: 6. Declare an integer variable called total and initialise it to zero. int weight = 100000; int total; unsigned int value = -2500; total = 0; The C compiler doesn’t catch such errors. Your program might 7. Declare a variable called loop, which can hold an integer value. compile and link, but you might get unexpected results when int loop; the program is run. 4 • DO understand the number of bytes that variable types take 1.23E2 1.23 times 10 to the 2nd power, or 123 P R for your computer. 4.08e6 4.08 times 10 to the 6th power, or 4,080,000 O G • DO use typedef to make your programs more readable. 0.85e-4 0.85 times 10 to the -4th power, or 0.000085 RA • DO initialize variables when you declare them whenever A constant written without a decimal point is represented by MM possible. the compiler as an integer number. Integer constants can be IN • DON’T use a variable that hasn’t been initialized. Results written in three different notations: G F can be unpredictable. A constant starting with any digit other than 0 is interpreted as a U N • DON’T use a float or double variable if you’re only storing decimal integer (that is, the standard base-10 number system). D A integers. Although they will work, using them is inefficient. Decimal constants can contain the digits 0 through 9 and a M • DON’T try to put numbers into variable types that are too leading minus or plus sign. (Without a leading minus or plus, a EN small to hold them. constant is assumed to be positive.) AT • DON’T put negative numbers into variables with an • A constant starting with the digit 0 is interpreted as an octal LS unsigned type. integer (the base-8 number system). Octal constants can US contain the digits 0 through 7 and a leading minus or plus IN Now let us what are constants in C. Don’t worry they are the G same, as they are known by their name. You know it as sign. ‘ C something, which has fixed value, and it is the same here. • A constant starting with 0x or 0X is interpreted as a ’ hexadecimal constant (the base-16 number system). Constants • Hexadecimal constants can contain the digits 0 through 9, Like a variable, a constant is a data storage location used by your the letters A through F, and a leading minus or plus sign. program. Unlike a variable, the value stored in a constant can’t be changed during program execution. C has two types of Now let us see what a symbolic constant is? constants, each with its own specific uses. Symbolic Constants Literal Constants A symbolic constant is a constant that is represented by a name (symbol) in your program. Like a literal constant, a symbolic A literal constant is a value that is typed directly into the source constant can’t change. Whenever you need the constant’s value code wherever it is needed. Here are two examples: in your program, you use its name as you would use a variable int count = 20; name. The actual value of the symbolic constant needs to be float tax_rate = 0.28; entered only once, when it is first defined. The 20 and the 0.28 are literal constants. The preceding state- Symbolic constants have two significant advantages over literal ments store these values in the variables count and tax_rate. constants, as the following example shows. Note that one of these constants contains a decimal point, • Suppose that you’re writing a program that performs a whereas the other does not. The presence or absence of the variety of geometrical calculations. The program frequently decimal point distinguishes floating-point constants from needs the value ,, (3.14159) for its calculations. (You might integer constants. recall from geometry class that ,, is the ratio of a circle’s A literal constant written with a decimal point is a floating-point circumference to its diameter.) For example, to calculate the constant and is represented by the C compiler as a double- circumference and area of a circle with a known radius, you precision number. Floating-point constants can be written in could write standard decimal notation, as shown in these examples: Circumference = 3.14159 * (2 * radius); 123.456 Area = 3.14159 * (radius)*(radius); 0.019 The asterisk (*) is C’s multiplication operator. Thus, the first of 100. these statements means Note that the third constant, 100., is written with a decimal “Multiply 2 times the value stored in the variable radius, and point even though it’s an integer (that is, it has no fractional then multiply the result by 3.14159. Finally, assign the result to part). The decimal point causes the C compiler to treat the the variable named circumference.” constant as a double-precision value. If, however, you define a symbolic constant with the name PI Without the decimal point, it is treated as an integer constant. and the value 3.14, you could write Floating-point constants also can be written in scientific circumference = PI * (2 * radius); notation. You might recall from high school mathematics that area = PI * (radius)*(radius); scientific notation represents a number as a decimal part multiplied by 10 to a positive or negative power. The resulting code is clearer. Rather than puzzling over what the value 3.14 is for, you can see immediately that the constant PI is Scientific notation is particularly useful for representing being used. extremely large and extremely small values. In C, scientific notation is written as a decimal number followed immediately • The second advantage of symbolic constants becomes by an E or e and the exponent: apparent when you need to change a constant. Continuing with the preceding example, you might decide that for greater 5
Description: