Beruflich Dokumente
Kultur Dokumente
Introduction to Programming C Character Set Instructions Operators Data types Console based I/O Functions Preprocessor Directives Control Statements
2.0
Introduction
There are many programming languages used currently. One of the most popular programming language is C. C is a structured programming language. Dennis M Ritchie first developed the C language in 1972 at AT&T Bell labs primarily as a system programming language.
2.1
Objective
The objective of this lesson provides a detailed description about C programming language and its concepts in detail. The content of this lesson starts with introduction to programming language and ends with control structures.
2.2
2.2.1
Content
Introduction to Programming As a programming language, C is rather like Pascal or FORTRAN. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures. Of the three languages, C allows the most precise control of input and output. C is also rather terser than FORTRAN or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand. Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. The following example will illustrate a simple C program. This program which will print out the message This is a C program #include <stdio.h> main() { Page 16
Page 17
Page 18
Operators One reason for the power of C is its wide range of useful operators. An operator is a function which is applied to values to give a result. You should be familiar with operators such as +, -, /. Arithmetic operators are the most common. Other operators are used for comparison of values, combination of logical states, and manipulation of individual binary digits. In C operators can be classified into various categories based on their utility and action. A list of operator types is given below: Arithmetic operators + * / % Addition Subtraction Multiplication Division modulo division
Relational operators < > <= >= == != less than greater than less than or equal to greater than or equal to equal to not equal to
Logical operators && || ! & ! logical AND logical OR logical NOT bitwise AND bitwise OR Page 19
Bitwise operators
Increment and decrement operators ++<variable name> --<variable name> Other operators Sizeof 2.2.4 Data types The C language supports the following basic data types char int float double a single byte that can hold one character an integer a single precision floating point number a double precision floating point number
The precision refers to the number of significant digits after the decimal point. In addition, applying qualifiers to the above data types yield additional data types. A qualifier alters the characteristics of the data type, such as sign or size. The qualifiers that alter the size are short and long. These qualifiers are applicable to integers, and yield two more data types short int long int integer represented by a lesser number of bits (16) integer represented by a greater number of bits (32)
The sign qualifiers are signed and unsigned. signed short int unsigned short int signed int unsigned int signed long int unsigned long int 2.2.5 Console based I/O Character Input / Output is the lowest level of input and output. It provides very precise control, but is usually too fiddly to be useful. Most computers perform buffering Page 20
Page 21
It is also possible to insert numbers into the control string to control field widths for values to be displayed. For example %6d would print a decimal value in a field 6 space wide; %8.2f would print a real value in a field 8 space wide with room to show 2 decimal places. Display is left justified by default, but can be right justified by putting a - before the format information, for example %-6d, a decimal integer right justified in a 6 space field. scanf scanf allows formatted reading of data from the keyboard. Like printf it has a control string, followed by the list of items to be read. However scanf wants to know the address of the items to be read, since it is a function which will change that value. Therefore the names of variables are preceded by the & sign. Character strings are an exception to this. Since a string is already a character pointer, we give the names of string variables unmodified by a leading &. Control string entries which match values to be read are preceeded by the percentage sign in a similar way to their printf equivalents. 2.2.6 Functions Almost all programming languages have some equivalent of the function. You may have met them under the alternative names subroutine or procedure. Some languages distinguish between functions which return variables and those which don't. C assumes that every function will return a value. If the programmer wants a return value, this is achieved using the return statement. If no return value is required, none should be used when calling the function. Here is a function which raises a double to the power of an unsigned, and returns the result. double power(double val, unsigned pow) { double ret_val = 1.0; unsigned i; for(i = 0; i < pow; i++) ret_val *= val; return(ret_val); } The function follows a simple algorithm, multiplying the value by itself pow times. A for loop is used to control the number of multiplications, and variable ret_val stores the value to be returned. Careful programming has ensured that the boundary condition is correct too. ie
Page 22
Page 23
Control structure is used to control the sequence of the program flow. They are of two categories namely: Selection Loops
Selection In this case a statement is executed based on whether a condition is true or false. Following statements are used in selective execution of statements. a. The if Statement
The if statement is used for decision-making. It executes a statement based on the result of evaluation of an expression. The general form of the simple if statement is if (expression) statement; where statement may consist of a single statement or a set of statements. If the if expression evaluates to true, the statement or block following the if is executed. For example: #include<stdio.h> main() { int a=10,b=10; if (b= =a) printf( the 2 values are equal); } Output: the 2 values are equal In the above code since the value of a and b are the same, the expression in the if is true and hence the statement following the if expression is executed. b. if else The ifelse statement is used for decision-making. It executes a statement based on the result of evaluation of an expression. The general form of the if ..else statement is if (expression) statement 1; else statement 2;
Page 25
This is another common programming construct adapted from the initial if statement. The general form of this is: if (expression) statement; else if (expression) statement; else if (expression) statement; .. .. else statement; This construct is also known as the if-else-if ladder or if-else-if staircase. Though the above indentation is easily understandable with one or two ifs, it confuses as the number of if increases. This is because it gets deeply indented and so, the if-else-if is generally indented as:
Page 26
Page 27
where switch, case, break and default are the keywords and statement sequence can be simple statement or a compound statement which need not be enclosed in parentheses. The expression following switch must be enclosed in parentheses and the body of the switch must be enclosed within the curly braces. The datatype of the expression given and the datatype of the case constants given should be compatible. As suggested by the name, case labels can be only integer or character constant or constant expressions, which do not contain any variable names. Case labels must all be different. In the switch statement, the expression is evaluated and the value is compared with the case labels in the given order. If a label matches with the value of the expression, the statement mentioned will be executed. The break statement ensures immediate exit from the switch statement. If a break is not used in a certain case, the statements in the following case are also executed irrespective of whether that case value is satisfied or not. This execution will continue till a break is encountered. Therefore, break is said to be one of the most important statement while using a switch. The statements against default will be executed, if none of the other cases are satisfied. The default statement is optional. If it is not present and the value of the expression does not match with any of the cases, then no action will be taken. The order of the case labels and default is immaterial. /* switch Statement */ #include<stdio.h> #include<conio.h> Page 28
Page 30
The while statement is used to carry out looping operations, in which a group of statements is executed repeatedly, until some condition has been satisfied. The general form of while statement is while (expression ) { statement } The statement will be executed repeatedly, as long as the expression is true. This statement can be simple or compound, though it is usually a compound statement. It must include some feature that eventually alters the value of the expression, thus providing a stopping condition for the loop. #include <stdio.h> main() /* display the integers 0 through 9 */ { int digit = 0; while (digit <= 9) { printf("%d\n",digit); ++digit; } } Output: 0 1 2 3 4 5 6 7 8 9 Initially, digit is assigned a value 0. The whileloop then displays the current value of digit, increase its value by 1 and then repeats the cycle, until the value of digit exceeds 9. The net effect is that the body of the loop will be repeated 10 times, resulting in 10 consecutive lines of output. Each line will contain a successive integer value, beginning with 0 and ending with 9.
Page 31
Operators C supports a rich set of operators. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation. Operators are used in programs to manipulate data and variables. Control Statements C language possesses such decision making capabilities and supports the following statements known as control or decision making statements.
2.4
Intext Questions
1. 2. 3. 4. 5. List out the popular features of C. What are the different types of qualifiers? What are the components of a format specifier in a printf statement? In what ways does a switch statement is differ from if statement? Explain the differences between a break statement and continue statement with examples.
2.5
Summary
A variable is an entity that has value and is known to the program by a name. In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function. Every variable has a name and a value. The name identifies the variable, the value stores data. There is a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. Local variables are declared within the body of a function, and can only be used within that function.
Page 33
2.6
Terminal Exercises
1. 2. 3. 4. 5. What are the various compilers available for C and the operating systems they run on? The maximum length of a variable in C is _______________. Character constants should be enclosed between _______________. The operator && is an example for ___ operator. The associativity of ! Operator is _______________.
2.7
Supplementary Materials
1. Byron Gottfried, Programming with C, Second Edition, TMH, 1998. 2. Deitel & Deitel, C How to program, Pearson Education Ltd, 2001.
Page 34
2.9
2.11 Keywords
Stdio.h Scanf if break int printf main else-if continue c preprocessor.
Page 35