US03MACSC01-UNIT 1.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Introduction to Translator and Editor Translator: Computer can understand only one language, i.e. Machine Language. Therefore, before executing a program writt...
US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Introduction to Translator and Editor Translator: Computer can understand only one language, i.e. Machine Language. Therefore, before executing a program written in a high-level language or in an assembly language, it is necessary to translate them into machine language. This will do by translator. A translator is a program that converts the high level language program or assembly program into machine level language program. Examples of translator are: Assembler, Compiler, and Interpreter. Assembler: The assembly language code cannot be executed by a machine directly as it is not in a binary form. An Assembler is translator that converts an assembly language program (source Program) into machine language program (object program). A translator program that translates an assembly code into the computer's machine code is called an Assembler. Assembly Machine program program Assembler source object program program Compiler: The high level language program cannot be executed by a machine directly as it is not in a binary form. A compiler is translator that converts high level language program into machine language program. US03MACSC01 UNIT-1 Page 1 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language The program written in high level language is called as source program and a low level language such as an assembly language or machine language is called object program. High-level Machine Program Program Compiler source object program Program As shown in the above figure the input to the compiler is a source program written in a high-level language and its output is an object program, which consists of equivalent machine language instructions. Note that the source program and the object program are the same program- but are at different stages of development. Compilers are very large program, which reside permanently on secondary storage device, or may be on separate device and whenever required they are copied into the main memory for execution. The compiler can translate only those source programs, which have been written in the language for which the compiler is meant. For e.g. a 'C' compiler is only capable of translating source programs, which have been written in 'C' language. Therefore each machine requires a separate compiler for each high-level language that it supports. Interpreter: An interpreter translates and executes the source code line by line.It process an internal form of the source program and data at the same time. That is interpretation of the internal source form occurs at run time and no object code/program is generated. Following figure shows the process. This approach is generally slower than compilation because each line is translated during execution. Data Source Interpreter Results Program US03MACSC01 UNIT-1 Page 2 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Difference Between Compiler and Interpreter. Compiler Interpreter A compiler will take a full program An interpreter compiles and executes a and compile it. program line by line. A compiler converts source program An interpreter will convert and execute a into object program and execution is program at the same time. carried out in the last. A compiler will list the errors in last. An interpreter will check for error in each instruction, and immediately print the error messages and terminates the execution, if any error is found. Compilers are good for a very large an interpreter is good for small and short program. program. Source program is required only Source program is required every time. once, that is when it is compiled for the first time. Example: C, C++ Example: FOXPRO, BASIC Editor: Editor is a special program, which allows user for creations and modifications of the simple text files. Editors are used to create a file. Normally a text files. The file may be a programming code or any other text based like report, index etc. One can modify the created file afterwards also using the editor. Editors are used to create a text file, means computer programs editing the source code of programming language that does not include any graphics where as in Word processor we can include text and graphics both. Compilation of programs in some programming language is provided by some of the Editors, where as such facility is not given by any Word processor. Word processors are basically used to create a various kinds of documents not for writing programs. Characteristics of Editor: Normally each editor has a menu bar, which contains menu(s), each menu will have item(s). Most of the editors provide the facility of working with more than one file, using windowing technology. US03MACSC01 UNIT-1 Page 3 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Menu bar is always at top of the screen. The highlighted/underlined key in menu item shows the shortcut to perform the operation. Some menu items will have direct short cut keys, i.e. without invoking the menu one can execute the command. To go to any menu, normally a highlighted/underlined key of the menu with 'alt' key is used. All most all editors provide a facility of copying and pasting of text. Find and replace, printing. Turbo C Editor: Borland International Inc. develops this editor with inbuilt compilation feature. This editor will compile C as well as C++ programs. The debugging feature is also provided. It has inline assembler feature also, with which can write on 8086/8087- assembler code directly. A rich help on C/C++ functions is provided. The Turbo C++ offers everything you need to write, edit, compile, link, run, manage and debug C/C++ programs. The menu bar at the top of the screen is the gateway of the menus. To go to the menu bar, there are three different ways; 1. Press F10 key OR 2. Press Alt + ch, Where ch is the first character of the menu options OR 3. Click anywhere on menu bar (If mouse facility is available). Once you open this editor, it has following menu Options: File Menu: The File menu provides commands for creating new files, opening existing files, saving files, changes directories, printing files, shelling to DOS & quitting Turbo C++. Edit Menu: The edit menu provides commands to cut, copy and paste text in edit windows. You can also undo changes and reverse the changes you have just undone. Search Menu: The Search menu provides commands to search for text, function declarations and error locations in your files. Run Menu: The Run menu provides commands to run your program and to start and end debugging sessions. Compile Menu: The Compile menu provides commands to compile the program in the active edit window, or to make or build your project.. Debug Menu: The Debug menu provides commands to control all the features of the integrated debugger. US03MACSC01 UNIT-1 Page 4 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Project Menu: The Project menu contains all the project management commands to do the following Create or open a project Add or delete files from your project Set options for a file in the project View included files for a specific file in the project, etc. Options Menu: The Options menu contains for viewing and changing various default setting in Turbo C++. Windows Menu: The Options menu contains window management commands. Help Menu: This Help menu provides access to the online help system. Why ‘C’ Language? In early of 1960 there were many languages available but they were used for some specific purpose. For example COBOL was used for commercial application and FORTRAN was used for some scientific and engineering application. So at this stage people were searching some language which can fulfill the need of all type of application. So, there was an invention of different language has taken place. The C language becomes very popular due to its robustness rich set of built in function and operators that can be used to write any complex program.. SR YEAR LANGUAGE DEVELOPER REMARKS NO. 1 1960 ALGOL INTERNATIONAL COMMITTEE TOO GENERAL, TOO ABSTRACT 2 1963 CPL CAMBRIDGE UNIVERSITY 3 1967 BPCL MARTIN RICHARDS & CAMBRIDGE UNIVERSITY 4 1970 B KEN THOMPSON AT BELL LABORATORY 5 1972 C DENIS RITHCHIE AT BELL MODULAR, LABORATORIES GENERAL, History of C C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs, and used to re-implement the Unix operating system. US03MACSC01 UNIT-1 Page 5 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems. C has been standardized by the American National Standards Institute (ANSI) since 1989 (see ANSI C) and subsequently by the International Organization for Standardization (ISO). C is an imperative procedural language. It was designed to be compiled using a relatively straight-forward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. FEATURES OF C LANGUAGE: There are several reasons why many computer professionals feel that C is at the top of the list: 1. FLEXIBLILITY: C is a powerful and flexible language. C is used for projects as diverse as operating system, word processor, graphics, spreadsheets and even compilers for other language. C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available. 2. PORTABILITY: C is a portable language. Portable means that a C program written for one computer system can be run on another system with little or no modification. Portability is enhanced by the ANSI standard by C the set of rules for C compilers. 3. COMPACTNESS: C is a language of few words, containing only a handful terms, called keywords, which serve as the base on which the languages functionality is built. You might think that a language with more keyword would be more powerful. This isn’t true. As you will find that it can be programmed to do any task. 4. REUSABILITY: C is modular, C code can and should be written in routine called functions. These functions can be reused in other applications or programs. By passing pieces of information to the function, you can create useful, reusable code. US03MACSC01 UNIT-1 Page 6 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Importance of C: It is robust language whose rich setup of built in functions and operator can be used to write any complex program. Program written in C are efficient due to several variety of data types and powerful operators. The C compiler combines the capabilities of an assembly language with the feature of high level language. Therefore it is well suited for writing both system software and business package. There are only 32 keywords; several standard functions are available which can be used for developing program. C is portable language; this means that C programs written for one computer system can be run on another system, with little or no modification. C language is well suited for structured programming, this requires user to think of a problems in terms of function or modules or block. A collection of these modules make a program debugging and testing easier. C language has its ability to extend itself. A c program is basically a collection of functions that are supported by the C library. We can continuously add our own functions to the library with the availability of the large number of functions. In India and abroad mostly people use C programming language because it is easy to learn and understand. C AS MIDDLE LEVEL LANGUAGE All programming languages can be divided into two categories: Problem oriented languages or high languages: Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These languages have been designed to give a better programming efficiency, faster program development. Generally these languages have better programming capability but they are less capable to deal with hardware or Hardware related programming. US03MACSC01 UNIT-1 Page 7 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Machine oriented languages or Low Level Languages: Examples of languages falling in this category are Assembly language and Machine Language. These languages have been designed to give a better machine efficiency i.e. faster program execution. Generally these languages have better hardware programming capability but it is very difficult and tedious to do create complex application like and business application or some commercial application C as Middle Level Language: C stands in between these two categories. That’s why it is called a Middle Level Language, since it was designed to have both; a relatively good programming efficiency (as compared to Machine Oriented Language) and a relatively good machine efficiency (as compared to Problem Oriented Language). Basic Structure of C program: Documentation section Link section Definition section Global declaration section Main() function section Declaration Part; Executable Part; subprogram section f1() { … } f2() {...} …. fn() { … } The documentation section consists of a set of comment lines, giving the name program, author and other details. Comment can be written using two method : Single line comment by using // (double slash) Multiline comment using. Anything written between are treated as comment. US03MACSC01 UNIT-1 Page 8 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language The link section provides instruction to the compiler to link functions from the system library. This section contains a list of header files. #include e.g. #include for standard Input/Output header file #include for console input/output etc. The definition section defines all symbolic constants. e.g. #define MAX 100 Global declaration consists of global variables. Global variables are variables that are used in more than one function and are declared outside all the functions. Every C program must have one main function section. This section contains two parts: 1. Declaration part 2. 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 bracers ‘ { ‘and ends at the closing braces ' } '. The closing brace of the main function is the logical end of the program. All the statements in the declaration and other logic always ends with semicolon '; '. The subprogram section contains all the user-defined functions that are called in the main function. The function body of user-defined functions can appear in any order. All sections are optional except the main function. Problem Analysis: In computer science, program analysis is the process of automatically analyzing the behaviour of computer programs regarding a property such as correctness, robustness, safety and liveness. Program analysis focuses on two major areas: program optimization and program correctness. The first focuses on improving the program’s performance while reducing the resource usage while the latter focuses on ensuring that the program does what it is supposed to do. US03MACSC01 UNIT-1 Page 9 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Program analysis can be performed without executing the program (static program analysis), during runtime (dynamic program analysis) or in a combination of both. KEYWORDS : There are words with specific meaning and these meanings cannot be changed to ‘C’ language system. They are known as keywords of ‘C’ language. Keyword must not be used as variable names. There are 32 keywords in ‘C’ language. Which are as under: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Data Types: C language is rich in its data types. It supports four classes of data types. Primary (or fundamental) data types User defined data types Derived data types Primary Data Types (Fundamental Data Types): All C compilers support five fundamental data types, namely integer (int), character (char), floating point (float), double precision floating point (double) and void. The extended data types of integer are long int and that of double is long double. Integer type: Integers are whole numbers with a range of values supported by a particular machine. C language has three classes of integer storage, namely short integer, integer and long integer, in both signed and unsigned forms. US03MACSC01 UNIT-1 Page 10 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language The use of qualifier signed on integers is optional because the default declaration assumes a signed number. int: int or signed int requires 16 bits for storage of number. 1 bit is used for sign while rest 15 bits are used to store magnitude of the numbers. Therefore, for a 16 bit machine the range of signed int or int number is -32,768 to 32,767. Following table shows the data types and their range: Type Bits (size) Range Format int or signed int 16 -32,768 to 32767 %d unsigned int 16 0 to 65535 %u short int or 8 -128 to 127 %d/%h signed short int unsigned short int 8 0 to 255 %u, %h long int or 32 -2,147,483,648 to %ld signed long int 2,147,483,647 unsigned long int 32 0 to 4,294,967,295 %ld, %u Floating Point Data Types: Floating point (or real) numbers are stored in 32 bits with 6 digits of precision. This means, A=3.1 will be displayed as 3.100000 This data type is defined by keyword float. When the accuracy provided by a float number is not sufficient, the type double can be used to define the number. A double data type number uses 64 bits, giving a precision of 14 digits. These are known as double precision numbers. Following table shows the data types and their range: Type Size (bits) Range Format specified Float 32 3.4E-38 to 3.4E+38 %f Double 64 1.7E-308 to 1.7E+308 %f long double 80 3.4E-4932 to 3.4E+4932 %lf US03MACSC01 UNIT-1 Page 11 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Character Data Type: A single character can be defined as a character (char) type data. Characters are stored in 8 bits of internal storage. The size and range of character or signed character data type of 16 bit machine is 8 bits and -128 to 127, while the range of unsigned character is 0 to 255. The character data type is formatted by %c. Operators and Expressions: An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of the mathematical or logical expressions. Following are the different types of operators available in C language: 1. Arithmetic operators (+, - ,*, /, %) 2. Relational operators (=, ==, !=) 3. Logical operators (&&, ||, !) 4. Assignment operator (=) 5. Increment and decrement operators (++, --) 6. Conditional operator (? :) 7. Comma operator 1. Arithmetic operators: The C language provides all the basic arithmetic operators. The unary minus (-) operator, in effect, multiplies its single operand by (-1), which means -5 = (-1) * 5. Following are the operators and their meanings: Operator Meaning + Addition / unary plus - Subtraction / unary minus * Multiplication / Division % Modulo For example: Z = X + Y US03MACSC01 UNIT-1 Page 12 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language In above given example X, Y and Z are the operands and =, + are the operators. An expression is a combination or sequence of operands as well as operators. The C does not have an operator for exponentiation (x y). But there exists a built in function pow(x,y) in math.h, which returns xy. I. Integer Arithmetic: When both the operands in a single arithmetic expression such as a+b are integers, the expression is called an integer expression, and the operation is called integer arithmetic. Integer arithmetic always results an integer value. Eg.: a = 14, b = 4 Then a – b = 10 a + b = 18 a * b = 56 a / b = 3 (decimal part truncated) a % b = 2 (remainder of division) During integer division, if both the operands are of the same sign, the result is truncated towards 0. If one of them is negative, the direction of truncation is implementation dependent. Eg.: 6/7 = 0 -6/-7 = 0 But -6/7 may be 0 or -1 (machine dependent) During modulo division, the sign of the result is always the sign of the first operand (the dividend). Eg.: -14%3 = -2 -14%-3 = -2 14%-3 = 2 II. Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values either in decimal or exponential notation, where floating point values are rounded to the number of significant digits permissible. For example: if x, y and z are floats the we will have x = 6.0/7.0 = 0.857143 y = 1.0/3.0 = 0.333333 z = 2.0/3.0 = 0.666667 The operator % cannot be used with floating point data or real operands. US03MACSC01 UNIT-1 Page 13 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language III. Mixed-Mode Arithmetic: When one of the operands is real and other is integer, the expression is called mixed mode arithmetic expression. If either operand is of real type, then only real operation is performed and the result is always a real number.. For example: 15/10.0 = 1.5 Where as 15/10 = 1 2. Relational operator: A relational operator is used to make comparisons between two expressions. C supports six relational operators. Following are the operators and their meanings: Operator Meaning < Less than Greater than >= Greater than or equal to == Equal to != Not equal to The general form is: arithmetic expression1 relational operator arithmetic expression2 Following are some examples: 5 = 0 False 10 < 7+5 True Suppose a = 5, b = 10, c = 7, d = 8 a + b == c + d In above example the arithmetic expressions will be evaluated first and then the results will be compared. That is, arithmetic operators have a higher priority over relational operators. US03MACSC01 UNIT-1 Page 14 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language 3. Logical Operators: (&& , || , ! ) These operators are useful in combining one or more conditions. C has following three logical operators: Operator Meaning && Logical AND (true only if all conditions are true, otherwise false) || Logical OR (false only if all conditions are false, otherwise true) ! Logical NOT (true, if expression is false and vice-versa) Following are some examples: Logical AND: a = 5, b = 10, c = 7, d = 8 Then a < b && c < d True a < b && d < c False a < b && c != 8 True a > b && c = 8 False Logical OR: a = 5, b = 10, x = 10 Then a < b || x =10 True a > b || x != 10 False a > b || x ==10 True a < b || x != 10 True Logical NOT: The condition !(Ab) evaluates true. 4. Assignment Operator: Assignment operators are used to assign the result of an expression to a variable. The general form is: variable = expression; In addition, C has a set of ‘shorthand’ assignment operators of the form V op = exp; where V is a variable, exp is an expression and op is a C binary arithmetic. The operator op is known as the shorthand operator. V op = exp; is equivalent to V = V op(exp); Example1: A = A + 1 means variable = expression is same as A+=1 means V op = exp. US03MACSC01 UNIT-1 Page 15 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Similarly, Variable = expression V op = exp a = a-1 a-=1 b = b+1 b+=1 x = x + (y + 2) x+= (y + 2) a=a*b a*=b a = a/n + 1 a/=n + 1 a = a/b a/=b a=a%b a%=b a=a*a a*=a The use of shorthand assignment operators has three advantages: What appears on the left-hand side need not be repeated and therefore it becomes easier to write. The statement is more efficient. The statement is more concise and easier to read. 5. Increment and Decrement Operators: C has two very useful operators; the increment (++) and decrement operators (--). Increment operator: (++ unary operator) The increment operator (++) adds 1 to the operand. It is a unary operator. The general for is: ++variable; or variable++; ++m or m++ is equivalent to m = m+1 or m+=1. While ++m and m++ mean the same thing when they form statement independently; they can be used in expressions on the right-hand side of an assignment statement as following using prefix or postfix: A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. Eg: m = 5; y = ++m; In above case first m will be incremented by 1 so m = 6 and then after value of m (say 6) is assign to y. So the values of y and m would be 6. A postfix operator first assigns the value of the variable on left and then the value of the operand is incremented. US03MACSC01 UNIT-1 Page 16 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language Eg: m = 5; y = m++; In above case first value of m (say 5) is assign to y and then after m will be incremented by 1 so m = 6. So the value of y is 5 and m is 6. Decrement operator: (-- unary operator) It decreases the value of a variable by 1. It can be postfix or prefix. The general form is: --variable; or variable--; A prefix operator first subtract 1 from the operand a then the result is assigned to the variable x. Eg: int a = 5; x = - - a; Value of x and a is 4. A postfix operator it first assigns the value of the variable on the left hand and then the value of operand is decremented. Eg: int a = 5; x = a- -; Value of x is 5 and a is 4. 6. Conditional Operator: (? :) It is also known as Ternary Operator. The general form of ternary operator is exp 1 ? exp2 : exp3 ; Where exp1, exp2, exp3 are expressions. The operator ? : Works as follow: : exp1 is evaluated first. If it is non-zero (true), then the expression exp2 is evaluated and becomes the value of the expression. If it is zero (false), then the expression exp3 is evaluated and becomes the value of the expression. Example: A = 10; B = 15; X = (A>B)? A: B; In this example, X will be assigned the value of B. This can be achieved using the if...else statements as follows. if ( A > B) X=A; else X = B; US03MACSC01 UNIT-1 Page 17 of 32 US03MACSC01- Fundamentals of Computer Programming Using C UNIT – 1 Basics of C Language 7. Comma Operator: The comma operators are use primarily in conjunction with the for statement. This operator permits two different expressions to appear in situation where only one expression would ordinarily be used. For example, it is possible to write for(expression 1a, expression 1b; expression2; expression3) Where expression 1a and 1b are the two expressions, separated by the comma operator, where only one expression would normally appear. These two expressions would typically initialize two separate indices that would be used simultaneously within for loop. Similarly, a for statement might make use of the comma operator in the following manner. for(expression 1a; expression2;expression3a, expression3b) Here expression 3a and expression 3b separated by the comma operator, appear in place of the usual single expression. In this application the two separate expressions would typically be used to alter the two different indices used simultaneously within the loop. For example, one index might count forward while the other counts backward. In for loops. for(n=1,m=10; n' (greater than) and '