ABOUT C PROGRAMMING LANGUAGE

ABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from ...
Author: Betty Wilson
2 downloads 2 Views 1MB Size
ABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined Programming Language ) was developed with the purpose of creating a language that was capable of both high level, machine independent programming and would still allow the programmer to control the behavior of individual bits of information. The one major drawback of CPL was that it was too large for use in many applications. In 1967, BCPL ( Basic CPL ) was created as a scaled down version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell Labs, took this process further by developing the B language. B was a scaled down version of BCPL written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C. C's power and flexibility soon became apparent. Because of this, the Unix operating system which was originally written in assembly language, was almost immediately re-written in C ( only the assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C spread throughout many colleges and universities because of it's close ties to Unix and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems. In response to this in 1983, the American National Standards Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as ANSI Standard C. The standardization process took six years. The ANSI C standard was finally adopted in December 1989, with the first copies becoming available in early 1990. The standard was also adopted by ISO (International Standards Organization), and the resulting standard was typically referred to as ANSI/ISO Standard C, or simply ANSI/ISO C. Today C is in widespread use with a rich standard library of functions. Significant Language Features C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. It allows low level access to information and commands while still retaining the portability and syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs. C's power and fast program execution come from it's ability to access low level commands, similar to assembly language, but with high level syntax.

1

It's flexibility comes from the many ways the programmer has to accomplish the same tasks. C includes bitwise operators along with powerful pointer manipulation capabilities. C imposes few constraints on the programmer. The main area this shows up is in C's lack of type checking. This can be a powerful advantage to an experienced programmer but a dangerous disadvantage to a novice. Another strong point of C is it's use of modularity. Sections of code can be stored in libraries for re-use in future programs. This concept of modularity also helps with C's portability and execution speed. The core C language leaves out many features included in the core of other languages. These functions are instead stored in the C Standard Library where they can be called on when needed.. An example of this concept would be C's lack of built in I/O capabilities. I/O functions tend to slow down program execution and also be machine independent when running optimally. For these reasons, they are stored in a library separately from the C language and only included when necessary. C is often called a middle-level computer language. This does not mean that C is less powerful, harder to use, or less developed than a high-level language such as Pascal; nor does it imply that C is similar to, or presents the problems associated with, assembly language. The definition of C as a middle-level language means that it combines elements of high-level languages with the functionalism of assembly language. As a middle-level language, C allows the manipulation of bits, bytes, and addresses—the basic elements with which the computer functions. Despite this fact, C code is surprisingly portable. Portability means that it is possible to adapt software written for one type of computer to another. For example, if a program written for one type of CPU can be moved easily to another, that program is portable. All high-level programming languages support the concept of data types. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common data types are integer, character, and real. Although C has several basic built-in data types, it is not a strongly typed language like Pascal or Ada. In fact, C will allow almost all type conversions. For example, character and integer types may be freely intermixed in most expressions. Traditionally C performs no run-time error checking such as array-boundary checking or argument-type compatibility checking. These checks are the responsibility of the programmer. A special feature of C is that it allows the direct manipulation of bits, bytes, words, and pointers. This makes it well suited for system-level programming, where these operations are common. Another important aspect of C is that it has only 32 keywords (5 more were added by C99, but these are not supported by C++), which are the commands that make up the C language. This is far fewer than most other languages. THE FOUNDATION OF C++

2

Standard Library This is a summary of the library defined by the ANSI standard. The standard library is not part of the C language proper, but an environment that supports standard C will provide the function declarations and type and macro definitions of this library. The functions, types and macros of the standard library are declared in standard headers: A header can be accessed by #include Headers may be included in any order and any number of times. A header must be included outside of any external declaration or definition and before any use of anything it declares. A header need not be a source file. External identifiers that begin with an underscore are reserved for use by the library, as are all other identifiers that begin with an underscore and an upper-case letter or another underscore.

Input and Output: The input and output functions, types, and macros defined in represent nearly one third of the library. . When a program begins execution, the three streams stdin, stdout, and stderr are already open.

File Operations The following functions deal with operations on files. fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include: "r" open text file for reading "w" create text file for writing; discard previous contents if any "a" append; open or create text file for writing at end of file "r+" open text file for update (i.e., reading and writing) "w+" create text file for update, discard previous contents if any "a+" append; open or create text file for update, writing at end freopen opens the file with the specified mode and associates the stream with it. It

3

returns stream, or NULL if an error occurs. freopen is normally used to change the files associated with stdin, stdout, or stderr. int fflush(FILE *stream) On an output stream, fflush causes any buffered but unwritten data to be written; on an input stream, the effect is undefined. int fclose(FILE *stream) fclose flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise. int remove(const char *filename) remove removes the named file, so that a subsequent attempt to open it will fail. It returns non-zero if the attempt fails. int rename(const char *oldname, const char *newname) rename changes the name of a file; it returns non-zero if the attempt fails.

Formatted Output The printf functions provide formatted output conversion. int fprintf(FILE *stream, const char *format, ...) fprintf converts and writes output to stream under the control of format.

Formatted Input The scanf function deals with formatted input conversion. int fscanf(FILE *stream, const char *format, ...) fscanf reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer.

Character Input and Output Functions fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of file or error occurs. fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0' fputc writes the character c (converted to an unsigend char) on stream. It returns the character written, or EOF for error. 4

fputs writes the string s (which need not contain \n) on stream; it returns nonnegative, or EOF for an error. getc is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once.

Direct Input and Output Functions fread reads from stream into the array ptr at most nobj objects of size size. fread returns the number of objects read; this may be less than the number requested. feof and ferror must be used to determine status. fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the number of objects written, which is less than nobj on error.

File Positioning Functions fseek sets the file position for stream; a subsequent read or write will access data beginning at the new position. ftell returns the current file position for stream, or -1 on error. void rewind(FILE *stream) rewind(fp) is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp). fgetpos records the current position in stream in *ptr, for subsequent use by fsetpos.

Character Class Tests: The header declares functions for testing characters. For each function, the argument list is an int, whose value must be EOF or representable as an unsigned char, and the return value is an int. isalnum(c) isalpha(c) or isdigit(c) is true isalpha(c) isupper(c) or islower(c) is true iscntrl(c) control character isdigit(c) decimal digit

5

isgraph(c) printing character except space islower(c) lower-case letter isprint(c) printing character including space ispunct(c) printing character except space or letter or digit isspace(c) space, formfeed, newline, carriage return, tab, vertical tab isupper(c) upper-case letter isxdigit(c) hexadecimal digit In addition, there are two functions that convert the case of letters: int tolower(c) convert c to lower case int toupper(c) convert c to upper case If c is an upper-case letter, tolower(c) returns the corresponding lower-case letter, toupper(c) returns the corresponding upper-case letter; otherwise it returns c.

String Functions: These are the groups of string functions defined in the header . char *strcpy(s,ct) copy string ct to string s, including '\0'; return s. char *strcat(s,ct) concatenate string ct to end of string s; return s. int strcmp(cs,ct) compare string cs to string ct, return 0. log10(x) base 10 logarithm log10(x), x>0. pow(x,y) xy. A domain error occurs if x=0 and y < 17

Logical negation (NOT) Bitwise 1’s complement Unary plus Unary minus Pre or post increment Pre or post decrement Address Indirection Size of operant in bytes Dereference Dereference Multiply Divide Modulus Binary Plus Binary Minus Shift Left Shift Right Less than Less than or equal to

Associativity L → R Left to Right R → Right Left

L→R L→R L→R L→R L→R

L ->

>= 8

Equality

9 10 11 12 14 15

Bitwise AAND Bitwise XOR Bitwise OR Logical AND Conditional Assignment

16

Comma

Greater than Greater than or equal to Equal to Not Equal to Bitwise AND Bitwise XOR Bitwise OR Logical AND Ternary Operator Assignment Assign product Assign reminder Assign quotient Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift Evaluate

== != & ^ | && ?: = *= %= /= += -= &= ^= |= = ,

L→R L→R L→R L→R L→R R→L R→L

L→R

VALUES TO VARIABLES In C, there are two different methods through which a variable can be assigned values. They are, 1. Through assignment statements. 2. Using built-in functions.

ASSIGNMENT STATEMENTS Assignment statements are the simple means by which variables are assigned values. The syntax is given below. variable-name=expression; Consider the below assignment statement. a=b*c; Here, the product of ‘b’, and ’c’ is calculated and it is stored in ‘a’.

18

USING BUILT-IN FUNCTIONS. Built-in functions like ‘scanf’, ‘gets’, ‘getch’, ‘getchar’, ‘getc’ are used to assign values to variables. The functions ‘gets’, ‘getch’, ‘getchar’, ‘getc’ can be used to assign value to one variable and ‘scanf’ can be used to assign values to more than one variables. Syntaxes are given below. scanf: scanf(“control-strings”, &variable-names); In the syntax of scanf statement, control strings denote the data types of the variable-names. Using scanf, any number of variables can be assigned values. getc(), getch(), getchar(), gets(): These functions are used to assign value to only one variable at a time. The syntaxes of all these are the same except the function name. Syntax: variable-name = function-name();

The ‘getc’ function reads a character from a file pointer. Consider the following example. c = getc(fp2); This statement reads the character from the file pointer, ‘fp2’ and assigns that value to ‘c’. The ‘getch’ and ‘getchar’ functions assign values from the keyboard to a variable. The ‘getch’ function assigns the value and immediately transfers the control to the next line of the program. But ‘getchar’ function waits for a key press to pass the control. The ‘gets’ function assign a string value to a variable. Some examples are given below. a = getch(); b = gets(); c = getchar(); Here the variables ‘a’ and ‘c’ should be character variables and ‘b’ should be a character array.

19

IF_ELSE This lesson will show you how to: • • •

Use an if statement Use an else statement Use an else if statement

If Statement

The if statement is used to conditionally execute a block of code based on whether a test condition is true. If the condition is true the block of code is executed, otherwise it is skipped. SYNTAX if (condition) {

true_statements

;

}

OR if (condition)

true_statement

;

OR if (condition) {

true_statements

;

false_statements

;

} else { }

PROGRAM FLOW 1. First, the boolean expression condition is evaluated. 2. If condition evaluates to true, the true_statement(s) are executed. 3. If condition evaluates to false and an else clause exists, the false_statement(s) are executed. 4. Flow exits the if-else structure.

20

EXAMPLE #include int main(void) { int number = 75; int mark; printf("Your examination mark\n"); printf("Enter your score, please\n"); scanf("%d",&mark); if (mark >= number) { printf("Incredible, you passed with a merit\n"); } return 0; } The "==" is called a relational operator. Relational operators, ==, !=, >, >=, 8 || x < 1) 15: { 16: printf("Only values from 1 to 8 are acceptable!"); 17: } 18: else 19: { 20: f = factorial(x); 21: printf("%u factorial equals %u\n", x, f); 22: } 23: 24: return 0; 25: } 26: 27: unsigned int factorial(unsigned int a) 28: { 29: if (a == 1) 30: return 1; 31: else 32: { 33: a *= factorial(a-1); 34: return a; 35: } 36: } Out Put:Enter an integer value between 1 and 8: 6 6 factorial equals 720

46

ANALYSIS: The first half of this program is like many of the other programs you have worked with so far. It starts with comments on lines 1 and 2. On line 4, the appropriate header file is included for the input/output routines. Line 6 declares a couple of unsigned integer values. Line 7 is a function prototype for the factorial function. Notice that it takes an unsigned int as its parameter and returns an unsigned int. Lines 9 through 25 are the main() function. Lines 11 and 12 print a message asking for a value from 1 to 8 and then accept an entered value. Lines 14 through 22 show an interesting if statement. Because a value greater than 8 causes a problem, this if statement checks the value. If it's greater than 8, an error message is printed; otherwise, the program figures the factorial on line 20 and prints the result on line 21. When you know there could be a problem, such as a limit on the size of a number, add code to detect the problem and prevent it. The recursive function, factorial(), is located on lines 27 through 36. The value passed is assigned to a. On line 29, the value of a is checked. If it's 1, the program returns the value of 1. If the value isn't 1, a is set equal to itself times the value of factorial(a-1). The program calls the factorial function again, but this time the value of a is (a1). If (a-1) isn't equal to 1, factorial() is called again with ((a-1)-1), which is the same as (a-2). This process continues until the if statement on line 29 is true. If the value of the factorial is 3, the factorial is evaluated to the following: 3 * (3-1) * ((3-1)-1)

DON'T use recursion if there will be several iterations. (An iteration is the repetition of a program statement.) Recursion uses many resources, because the function has to remember where it is. Where the Functions Belong You might be wondering where in your source code you should place your function definitions. For now, they should go in the same source code file as main You can keep your user-defined functions in a separate source-code file, apart from main(). This technique is useful with large programs and when you want to use the same set of functions in more than one program. This technique is discussed on Day 21, "Advanced Compiler Use."

47

Summary A function declaration alludes to a function that is defined elsewhere, and specifies what type of arguments and values are passed to and returned from the function as well. A function definition reserves the memory space and defines what the function does, as well as the number and type of arguments passed to the function. A function can be declared to return any data type, except an array or a function. The return statement used in a function definition returns a single value whose type must be matched with the one declared in the function declaration. A function call is an expression that can be used as a single statement or within other expressions or statements. The void data type is needed in the declaration of a function that takes no argument. To declare a function that takes a variable number of arguments, you have to specify at least the first argument, and use an ellipsis (...) to represent the rest of the arguments passed to the function. va_start(), va_arg(), and va_end(), all included in stdarg.h, are needed in processing a variable number of arguments passed to a function. time(), localtime(), and asctime() are three time functions provided by C. They can be used together to obtain a character string that contains information of local date and time based on the calendar time.

PARAMETR PASSING BETWEEN FUNCTIONS The mechanism used to convey information to the function is called argument or parameter. The format string and the list of variables used inside the parameter in these functions are arguments. These are of two types. 1.Call by value 2.Call by reference.

48

Call by value In this method the value of the actual arguments in the calling functions are copied in to corresponding formal arguments of called function. With this method the changes made to to the formal arguments in called function have no effect on the values of actual arguments in calling function. Consider the following program , /*Sending and receiving values between function*/ main( ) { int a b product; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b); product=calproduct(a,b); printf(“\n %d %d product=%d”,a,b product); /here values of a &b remains unchanged/ } int calproduct( int x , int y) { int d; d=x*y; return (d); } In this program, in main( ) we receive the values of a , b through the keyboard and then output the product of a,b .However the calculation of product is done in a different function called calproduct( ).The variables a ,b are called ‘actual argument’, whereas the variables x,y are called formal arguments. Any number of arguments can be passed to a function being called . However the type, order and number of the actual and formal arguments must always be same. Instead of using different variable names x ,y ,we could have used the same variable names a,b. But the compiler would still treat them as different variables. So if the value of a formal argument is changed in called function, the corresponding changes do not take place in the calling function. A function can return only one value so return(a,b) is invalid statement. There are two methods of declaring the formal arguments . calproduct( x,y) int x,y; Another methode is , calproduct(int x,int y)

49

Call by reference In call by reference method we are passing the address of the data as argument. This means that using these address we would have an access to actual argument and hence we would able to manipulate them. The following program illustrate this fact main( ) { int a=10,b=20; swapr(&a,&b); printf(“\na=%d b = %d”,a,b); } swapr(int *x,int *y) { int t ; t =*x ; *x =*y ; *y=t ; } the output of this program would be a=20 b=10 Function with arrays We can pass array also as a argument to the function. To pass an array to a called function it is sufficient to list name of the array without any subscript and the size of the array as argument. When we deal with array arguments we should remember that if a function changes the values of an array these changes will be made to the original array that passed to the original array that passed to the function /*Program to find smallest number in array*/ #include int smallest(int *arr) ; main ( ) { int arr [10] , i ; clrscr( ); printf(“Enter 10 elements of an array\n”); for(i=0;i