| C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unixoperating system. | |
| It is a high-level programming language that is able to manipulate the computer at a low level like assembly language. During the last half of the 1980s, C became the language of choice for developing commercial software. | |
| C has also greatly influenced many other popular languages, especially C++, which was originally designed as an enhancement to C. It is the most commonly used programming language for writing system software, though it is also widely used for writing applications.C, and its object-oriented successor C++, are used to write a huge variety of applications and almost all operating systems. | |
Fundamental concept of Problem solving Introduction Firstly we will discuss here Fundamental concept of Problem solving. Then This chapter gives the viewer/reader an overview of C language and tells about the structure of C program and various component of a C program. C language allows us to create custom data types. Problems are the undesirable situations that prevent any software from fully achieving its objectives.When we wish to transform the existing situation into a more desired one, problem occurs, and a need for solving the problem arises. Defining a problem clearly in terms of goals and objectives helps largely in problem solving. There are three related terms that need to be well understood to successfully solve the problem: 1. Mission: It is the broad statement of the purpose of the organization. 2. Goals: It is the general statement of what is to be accomplished. 3. Objectives: It is the statement of measurable results to be achieved in a specified time frame.
| Problem solving strategies | |||
| The most popular method of problem solving is to divide and conquer. This means that the problem has to be divided into smaller problems, each of which must be solved to get the complete solution. | |||
| For instance, if it is required to find the second smallest element in an array, the problem could be divided into two parts viz. | |||
|
|
Program design & implementation There are two types of designing approach: 1. Top down design.2. Bottom up design. Both have been describe together with examples. Any problem can be dealt with two ways, viz. top down or bottom up. A simple example is given here to illustrate the concept.Sorting an array of numbers involves the following two steps: 1. Comparison2. Exchange 1. Top down design: At the top level, an algorithm has to be formulated to carry out sorting. Once the algorithmis confirmed, then the algorithms for comparison and exchange are formulated, before implementation of the entire algorithm. Therefore, in this approach, one begins from the top level without bothering about the minute details for implementation, to start with. 2. Bottom up design: The bottom up approach is just the reverse. The lower level tasks are first carried out and are then integrated to provide the solution. In this method, lower level structures of the program are developed first and then progressively higher level structures are created. Here the algorithms for exchange and comparison will be formulated before formulating the algorithm for the whole problem. In any case, dividing the problem into small tasks and then solving each task provides the solution. If the program development is assumed to be a single task and the program statements are developed in sequence, then it is quite likely that the program may not work. Therefore, either the top down or bottom up methodology has to be adopted for dividing the problem into smaller modules and then solving it. Difference between Top design and Bottom up approach: In the top down methodology, the overall structure is defined before getting into details, but in the bottom up approach, the details are worked out first before defining the overall structure. Implementation A good program is one which contains a main function and the main function calls procedures or sub-programs or functions to carry out specific tasks. The subprograms are dependent on the main program. They do what the main program asks them to do. Each language gives different names to sub-programs. Sub programs are known as functions in C. The quality of program will also get enhanced when the program is made modular as mentioned above with functions. Each function will receive input and may return some output to the called program. By dividing the problem into a number of functions, the problem can be divided and conquered. This facilities focus on small programs and dealing with one problem at a time.
Introduction C is general-purpose, structured programming language, developed by Denis Ritchie in1972 at Bell lab USA. Its instructions consist of terms that resemble algebraic expressions, augmented by certain English keywords such as if, else, for, do and while. In this respect C resembles other high-level structured programming languages such asPascal and FORTRAN. C also contains certain additional features, however, that allow it to be used at a lower level, thus bridging the gap between machine language and the more conventional high-level languages. This flexibility allows C to be used for system programming as well as for applications programming. C is characterized by the ability to write very concise source programs, due in part to the large number of operators included within the language. It has a relatively small instruction set, though actual implementations include extensive library functions which enhance the basic instructions. C compilers are easily available for computers of all sizes, and C interpreters are becoming increasingly common. The compilers are usually compact, and they generate object programs that are small and highly efficient when compared with programs compiled from other high-level languages. The interpreters are less efficient, though they are easier to use when developing a new program. Many programmers begin with an interpreter, and then switch to a compiler once the program has been debugged (i.e., once all of the programming errors have been removed).
How to open C program code window Before opening C on your computer. Please ensure that C compiler has been loaded or not. If not then please load it first and then try any of the following ways to open C which suit your computer setting. 1.Start>>Program >> Turbo c. 2. If turbo C icon is present on your computer desktop then simply click on it. 3. My computer >>c:\>> tc (folder)>> bin (folder) >> tc.exe (icon). 4. Or make sure the path where you have loaded the C on your computer and try to run it from there. After following the above instructions the screen which is given below will appear on your desktop:
Description of C code window 1. =: Interface to external programs. 2. File: File related option such as opening and saving file. 3. Edit: Cut,Copy,Paste operation. 4. Search: Find,Find& Replace operation. 5. Run: Compile and run the file currently loaded in the text editor. And debugging such as setting/clearing trace points can be performed from this menu. 6. Compile: The menu item compiles a source file to an object file or an .exe file. 7. Debug: Provides interactive debugging. Variables can be examined/set/cleared, and we can watch variables change during execution. 8. Project: This menu item controls Borland C++’s handling of large programs that are in multiple source file. 9. Option: Default option are set during installation . The user can change any option at any time through this menu. 10. Windows: Windows operation include zoom, arranging windows on the screen , and closing windows. 11. Help: Borland C++ includes a context sensitive help capability. Select Help or press f1for general Help, Shift f1 for indexed help or Ctrl f1 for context sensitive help.
| Editing File | ||
| To open a new file, first press Alt F then Enter key, File pull down will activated, select newand then press Enter key, the display will be change into a blank screen of text editorhaving file name NONAME00.C, on which you can start entering your code through keyboard. | ||
| To open existing file press Alt F and then Enter, from the activated file pull down menu select Open, A Open Dialoge Box will appear, select desired file name path and pressEnter. | ||
|
|
||
Saving and Running a program Press Alt F, move the cursor to save , press Enter and then type file name with extension.C in given Text Box and press Enter to save the program. Running a program Press Alt R to pull down the Run menu and Enter to begin compilation, A compile window opens and shows progress and output can be viewed in output window and press Alt W to pull down window menu, move the cursor down to output and press Enter. Press Alt W and move the cursor to close to close output window immediately. Exiting Borland C Press Alt X to Exit Borland C and return to Dos Prompt.
The components of C language There are five main component of C language are: 1. The character set: Any alphabet ,digit or special symbol ,used to represent information is denoted by character. The character in C are grouped into four categories.
| 1 | Letters | A…Z and a…z |
| 2 | Digits | 0,1,2,…..9 |
| 3 | Special Symbol | ~,`,!,@,#,$,%,^,&,*,(),.,<,>,?,/,”,:,;,{},[] |
| 4 | White Space | blank space, Carriage return, form feed, newline, horizontal tab |
2. The data types: The power of the programming language depends, among other thing, on the range of different types of data it can handle. 3. Constants: A constant is a fix value that doesn’t change while program execution. 4. Variable: A variable is an entity whose value can change during program execution. 5. Keywords: Keywords are those word which have been assigned specific meaning in C language. Keywords should not be used as variable names to avoid problem. Note: Above given all the term has been discussed in details in next section.
Introduction To communicate with the computer, it is required to pass an appropriate value to the computer from the keyword. The value passed may be of different types, viz. Single character, integer, decimal, string. In each, the memory required is of different size. Such a defined type of value is called data type. C supports several different types of data, each of which may be represented differently within the computersmemory.The memory requirement of each data type will determine the permissible range of values for that data type. C data type can be broadly divided in two categories: (a) Primary data types.(b) Secondary data types. Primary data types Primary data types are independent data types. It’s not derived from other basic or secondary data types. There are five primary data types in C language: 1. Void2. Character3. Integer4. Float5. Double Secondary data types Secondary data types are also called as derived data types. Secondary data types are derived from the basic data types. They are also five in number: 1. Array2. Pointer3. Structure4. Union5. Enum
A sample of C language program Example of C program to calculate area of circle: Explanation of above program : # is the preprocessor directive which commands that the content of file should be included at the time of compilation. <stdio.h> is the header file which contains all input and output functions like scanf(), printf() which are frequently used in c programs. main() is the first function which is executed by a C program. 1. inta,r=5; -> This statement declares 2 variables a and r of type integer and r has been assigned a value of 5. 2. const pi=3.14; -> This statement declares pi as constant and value 3.14 has been assigned to it. 3. a = pi * r *r; -> This statement computes the area of circle and assign it to variable a 4. printf(“%f”,a); -> This statement prints the area of circle using printf function. 5. getch(); -> It is used to get character from user. Note: /* Any thing written within it is consider as comment statements. */ For Animated Presentation(With Voice) Click here
| C character set and keywords | ||
| Introduction | ||
| C language consists of some basic elements which are used to construct simple C statements. | ||
| These elements include the C character set, identifiers, and keywords, data types, constants, variables and arrays, declaration, expressions and statements. | ||
| We will see how these basic elements can be combined to form more comprehensive program components. | ||
|
|
||
C character set and keywords The C character set C uses the uppercase letter A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special characters as building blocks to form basic program elements ( e.g., constants, variables, operators, expressions, etc.). Some of the special characters are listed below:
| + | – | * | ~ | % | / | & | ( | ) | { | } | [ | ] | ? | “ | < | > | ! | ; | : |
Most versions of the language also allow certain other characters, such as @ and $, to be included within strings and comments. C uses certain combinations of these characters, such as \b,\n and \t, to represent special conditions such as backspace, new line, and horizontal tab, respectivelyThese character combinations are known as escape sequences.
| Identifiers | |||||
| Identifiers are names that are given to various program elements, such as variable,functions and arrays. | |||||
| Identifiers consist of letters and digits, in any order, except that the first character must be a letter.; | |||||
| Both upper- and lowercase letters are permitted, though common usage favors the use of lowercase letters for most types of identifiers. Upper- and lowercase letters are not interchangeable. | |||||
| The underscore (_) character can also be included, and is considered to be a letter. An underscore is often used in the middle of an identifier. | |||||
| An identifier may also begin with an underscore, though this is rarely done in practice. | |||||
| The following names are valid identifiers: | |||||
|
|||||
| Identifiers | |||||
| Identifiers are names that are given to various program elements, such as variable,functions and arrays. | |||||
| Identifiers consist of letters and digits, in any order, except that the first character must be a letter.; | |||||
| Both upper- and lowercase letters are permitted, though common usage favors the use of lowercase letters for most types of identifiers. Upper- and lowercase letters are not interchangeable. | |||||
| The underscore (_) character can also be included, and is considered to be a letter. An underscore is often used in the middle of an identifier. | |||||
| An identifier may also begin with an underscore, though this is rarely done in practice. | |||||
| The following names are valid identifiers: | |||||
|
Primary Data Type 1. Void Description:Used to specify empty set containing no values.Storage Space: 0 byte.Format: (void).Range of values: ______. 2. Character (Denoted as “char” in C programming language) Description:A character denotes any alphabet, digit or special symbol used to represent in formation and it is used to store a single character.Storage space: 1 byteFormat: %cRange of Values: ASCII Character Set. 3. Integer (Denoted as “int” in C programming language) Description:Integer type is used to store positive and negative integer.Storage space: 2 bytes.Format: %dRange of values: -32768 to +32767. 4. Float Description:It is used to store real number, with single precision floating point number (precision of 6 digits after decimal points.)Storage space: 4 bytes.Format: %fRange of values: -3.4*1038 to +3.4*1038. 5. Double Description:It stores real numbers with double precision. The use of double doesn’t guarantee to double the number of significant digits in our result, but it improves the accuracy of the arithmetic and reduces the accumulation of rounding errors.Storage Space: 8 bytes.Format: %ldRange of values: -1.7*10308 to +1.7*10308. An example program of using basic data type: Output of the program: Explanation: Numeric data stored is stored in the memory in their binary form, while the character data has to be codified as a unique integer and that code number is stored in the internal storage. The integer equivalents of alphabets are: Lower case: a-z = 97 to 122Upper case: A-Z = 65 to 90 In the above program when the characters are displayed in the integer format the corresponding ASCII code are displayed, similarly when integers are displayed in thecharacter format then equivalent character is displayed.
| Secondary Data Type | |||
| 1. Array: | |||
| It is a collection of data of similar data type. | |||
| e.g. Intnum [5]; | |||
| Reserve a sequence of 5 location of two bytes each for storing integers. | |||
| 2. Pointer: | |||
| Pointer is a variable that stores the address of some other variable. | |||
| e.g. int *i; | |||
| The above statement declares i as pointer to integer data type. | |||
| 3. Structure: | |||
| A structure is a collection of data of different data types under one name. | |||
| e.g. | |||
| Struct employees | |||
| { | |||
| char Name[10]; | |||
| int Age; | |||
| int Salary; | |||
| } | |||
| 4. Union: | |||
| It is a collection of data of different types sharing common memory space. | |||
| e.g. Union item | |||
| { | |||
| int m; | |||
| float x; | |||
| char c; | |||
| } ; | |||
| 5. Enumerated Data types: | |||
| This data types gives us an opportunity to invent your own data type and define what values the variable of this data type can take. | |||
| Example: enum colors | |||
| { | |||
| red, green, blue, cyan | |||
| }; | |||
| colors foreground, background; | |||
| Here the declaration has two parts: | |||
| a) The first part declare the data type and specifies its possible values. | |||
| b) The second part declare variable of this data type. | |||
| Now we can give the values to these variables: | |||
| foreground=red; | |||
| background=blue; | |||
| But remember we can’t use values that aren’t in the original declaration. Thus, the following declaration cause error. | |||
| foreground=yellow; | |||
| Note: Secondary data type has been given in detail later. | |||
|
|
|||
| Introduction | |||
| The defined type of memory area where the value is stored is called variable. | |||
| Variables are the data item whose values may vary during the execution of the program. | |||
| A specific location or the address in the memory is allocated for each variable and the value of that variable is stored in that location. | |||
| These locations may be integer, real or character etc. | |||
|
|
|||
| Rules for constructing variables names | |||
| There are some specific rules for constructing variable names in C language: | |||
| (a) Variable name may be a combination of alphabet digits or underscores and its lengths should not exceed 8 characters, some compilers allow 40 characters also. | |||
| (b) The first character must be an alphabet. | |||
| (c) No comma, blank spaces are allowed in variable name. | |||
| (d) No special symbols except underscore can be used as variable names. | |||
|
|
|||
| Variables | |||
| Variable declaration | |||
| All the variables must be declared before their use. It does two things: | |||
| (a) Tell the compiler what the variable name is. | |||
| (b) Specify what type of data that a variable will hold. | |||
| Syntax of variable declaration: | |||
| data_typevariable_name; | |||
| Example of variable declaration: | |||
| inti,j,k; | |||
| char ch; | |||
|
|
|||
Assigning values to variables To assign values to the variables, assignment operator (=) is used. Syntax of assigning values: variable declaration;Variable_name = value; Example of assigning values: Int i , j;j = 5 ;i = 0 ; It is also possible to assign a value at the time of declaration.e.g.int i = 5; More than one variable can be initialized in one statement using multiple assignment operators. e.g. j = m = 2; There could be an exception while using multiple assignment operators. e.g. int i , j = 2 , k; here the assignment will be i = 0 j=2 and k = garbage value An example program which shows the example of assignments: Output of the Program:
Scope of variables: LOcal& Global Scope of variable means where the variable stands in the program. All variables may not necessary be available to all statements in a program. Variables can have two types of scope: a) Local: When a variable is declared inside the function then such a variable is known as localvariable. A local variable can only be accessed by the function in which it is declared. It cannot be accessed by other function. b) Global: A variable which is declared outside all functions is known as global variable. A variable with a global scope is accessible to all the statements in the program. A globalvariable can be accessed by all the functions.
Introduction There are some values which do not change during the execution of the program. These values are called constants.Constants are of fixed value that remain unchanged during the execution of a program, and are used in assignment of statements. Constants are stored in variables. Syntax of constant declaration: Constdatatypevar_name = value; Example of Constant declaration: Constint a = 5; In C language there are five types of constants which has been described separately
| Character constants | |||
| A character constant consists of a single digit or a single special symbol enclosed within a pair of single inverted commas. The maximum length of a character constant can be 1 character. | |||
| e.g. –> ‘a’, ‘i’ , ‘5’, ‘=’. | |||
| There are some character sequence constants which are used in C to represented special action, these are called C Escape Sequence. | |||
| List of these escape sequence and its tasks are given below: | |||
| \a : audible bell | |||
| \f : form feed | |||
| \r : carriage return | |||
| \v : vertical tab | |||
| \’ : single quote | |||
| \? : question mark | |||
| \HHH: 1 to 3 digit hex value. | |||
| \b : backspace | |||
| \n : newline | |||
| \t : horizontal tab | |||
| \\ : backslash | |||
| \” : double quote. | |||
| 00 : 1 to 3 digit octal value | |||
|
|
|||
| Integer constants | |||
| An integer constant refers to a sequence of digits. It could be either positive or negative. and must have at least one digit. | |||
| It mustn’t have a decimal point. No commas or blank are allowed within an integerconstant. The allowable range for integer constants is -32767 to 32767. | |||
| There are three types of integer constants: | |||
| 1. decimal : | |||
| In decimal notation ,simply we write decimal number. e.g. 24,678 | |||
| 2. octal : | |||
| In octal notation, write(0)immediately before the octal represention,e.g.-076,-076 | |||
| 3. hexadecimal : | |||
| In hexadecimal notation ,the constant is preceded by 0x,e.g.,0x3e,-0x3e. | |||
| Some example of integer constants: | |||
| : 426 | |||
| : +762 | |||
| : -8000 | |||
| : -7605 | |||
|
|
|||
Real constants Real constants are often called Floating Point constants. It has three parts: 1. A sign (+ or -) preceding the number portion (optional). 2. A number portion (representing the base). 3. An exponent portion following the number portion (optional). This starts with E or E followed by an integer. The integer may be preceded by a sign. A real constant must have at least one digit. It must have a decimal point. It could be either positive (default) or negative. No commas and blank are allowed within a real constant. Some example of real constants: : +.72: +72: +7.6E+2: 24.4e-5
| Logical & String constants | ||
| A logical constant can have either of two values either true or false. In C a non-zero value is always treated as true whereas zero is treated as false. | ||
| The logical constants are very useful in evaluating logical expressions and complex condition. | ||
| A group of character enclosed within a pair of double inverted commas (” “) is treated as astring constant. | ||
| some example of string constant: | ||
| : “Hello” | ||
| “Welcome to eBiz” | ||
| “a” | ||
|
|
||
| C instruction set | ||
| Introduction | ||
| In previous section we discuss about various types of C constants, variables and keyword. | ||
| Now in this section we will discuss about how they are grouped to from instructions. | ||
| There are basically four types of instruction in C. which has been described separately. | ||
| 1. Type Declaration Instruction | ||
| 2. Input Output instruction | ||
| 3. Arithmetic Instructions | ||
| 4. Control Instructions | ||
|
|
||
Type Declaration &Input/Output Instructions This type of instruction is used to declare the type of variable being used in the program. Any variable used in the program must be declared before using it in any statement. This instruction is usually written at the beginning of the C program. Example: inta;floatre,ad;char name ,des. Input Output instructions These instructions are used to supply input data to a program and obtain the outputresults from it. Example: printf(), scanf().
| Arithmetic Instructions | |||
| These types of instructions are used to perform arithmetic operations between constantsand variables. | |||
| Some of the arithmetic operators are: +, -, * and /. | |||
| Example: | |||
| int a; | |||
| float b, deta, alpha, gamma, beta; | |||
| a=500; | |||
| b=0.0056; | |||
| deta=alpha*beta/gamma+0.5*2/5; | |||
| There are three types of arithmetic statements: | |||
| 1. Integer mode arithmetic statement: | |||
| In this type of arithmetic statement all operands are either integer variable or integer constant. | |||
| 2. Real mode arithmetic statement: | |||
| In this type of arithmetic statement all operands are either real constant or real variables. | |||
| 3. Mixed mode arithmetic statement: | |||
| In this type of arithmetic statement some of the operands are integer and some of them are real. | |||
|
|
|||
| Control Instructions | |||
| These types of instructions are used for controlling the sequence of execution of various statements in C program. It determines the ‘flow of control’ in a program. | |||
| There are four types of control instructions in C: | |||
| 1. Sequence Control Instructions | |||
| The sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. | |||
| 2. Selection or Decision Control Instructions | |||
| These types of instruction allow the computer to take a decision. | |||
| 3. Case Control Instruction | |||
| These types of instruction determine which instruction is to be executed next. | |||
| 4. Repetition or Loop Control Instruction | |||
| The loop control instruction helps computer to execute a group of statements repeatedly. | |||
|
|
|||
| Introduction | |||
| An operator specifies an operation to be performed. C is rich in operator. Operators join the various variables and constants to from an expression. | |||
| Some operator requires one operand and some require more than one operands. | |||
| An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation in data stored in variables. | |||
| C is extremely rich in operators It has as many as 45 different operators. | |||
|
|
|||
Operators Increment & Decrement operators These types of operators operate on only one operand, therefore these operators are also called Unary operators. These two powerful operators in C are + + (Increment), _ _ (Decrement). Operands must be declared as variables not a constant. These operators may be used either after or before the operand.When they are used before the operand, it is termed as Prefix while when they are used after the operand they are termed as Postfix. In prefix operations the value of operator is incremented or decremented first and then the expression is evaluated. Prefix operators has the effect of Change then use. In postfix operation the expression is evaluated first and then the value of operator is either incremented or decremented. Postfix operators has the effect of Use Then Change. e.g.: b=a++; this is postfix increment expression. In the expression firstly b=1; thena=a+1; will be executed , while in prefix increment expressionb=–a; firstly a =a-1;then b=a; will be executed. An example program clarifies the Postfix and Prefix
operators: Output of the program:
Assignment operator Assignment operators are used to assign the result of an expression to a variable. The most commonly used assignment operator is (=). eg: i=i+10; i=i+10 is an assignment expression which assigns the value of i+10 to i. Expression like i=i+10, i=i-5, i=i*2 etc. can be rewritten using shorthand assignment operators. e.g.: i=i+5 is equivalent to i+=5 i=i*(y+1) is equivalent to i*=(y+1) Operator Precedence: While executing an arithmetic statement which has two or more operators, we may have some problems about how exactly does it get executed. To answer these questions satisfactorily we have to understand the precedence of operators. Precedence defines the sequence in which operators are to be applied on the operands. Operators of same precedence are evaluated from left to right or right to left, depending upon the level. This is known as associativity property of an operator. Summary of precedence of associativity is given below:
| Description | Operator | Associativity |
| Function Expression | ( ) | Left to Right |
| Array Expression | [ ] | Left to Right |
| Structure Operator | -> | Left to Right |
| Structure Operator | . | Left to Right |
| Description | Operator | Associativity |
| Unary minus | – | Right to Left |
| Increment/Decrement | ++/– | Right to Left |
| One’s Compliment | ~ | Right to Left |
| Negation | ! | Right to Left |
| Address of | & | Right to Left |
| Value at address | * | Right to Left |
| Type cast | (type) | Right to Left |
| Size in bytes | sizeof | Right to Left |
| Description | Operator | Associativity |
| Multiplication | * | Left to Right |
| Division | / | Left to Right |
| Modulus | % | Left to Right |
| Addition | + | Left to Right |
| Subtraction | – | Left to Right |
| Description | Operator | Associativity |
| Left Shift | << | Left to Right |
| Right Shift | >> | Left to Right |
| Description | Operator | Associativity |
| Less Than | < | Left to Right |
| Less Than Equal to | <= | Left to Right |
| Greater than | > | Left to Right |
| Greater than Equal to | >= | Left to Right |
| Description | Operator | Associavity |
| Equal to | == | Left to Right |
| Not equal to | != | Left to Right |
| Description | Operator | Associavity |
| Bitwise AND | & | Left to Right |
| Bitwise XOR | ^ | Left to Right |
| Description | Operator | Associavity |
| Bitwise OR | ^ | Left to Right |
| Description | Operator | Associavity |
| Logical AND | && | Left to Right |
| Logical OR | || | Left to Right |
| Description | Operator | Associavity |
| Conditional | ?: | Right to Left |
| Description | Operator | Associavity |
| Assignment | = | Right to Left |
| Assignment | *= /= %= | Right to Left |
| Assignment | += -= &= | Right to Left |
| Assignment | ^= |= | Right to Left |
| Assignment | <<= >>= | Right to Left |
| Description | Operator | Associavity |
| Comma | , | Right to Left |
Type modifier The basic data types may have modifier preceding them to indicate special properties of the object being declared. These modifiers change the meaning of the basic data types to suit the specific needs. These modifiers are unsigned, signed, long and short. It is also possible to give these modifiers in combination, e.g., unsigned long int.eg:-Modifier for char Data Type main(){char ch=291;printf(“%d\t%c\n”,ch,ch);} output:- 35 Here ch has been defined as a char ,and char cannot take a value bigger than +128.That is why assigned value of ch is 291 and is considered to be 35 (291-128-128).
| Data type | Range | Bytes occupied | Format |
| signed char | -128 to +127 | 1 | %c |
| unsigned char | 0 to 255 | 1 | %c |
| short signed int | -32768 to 32767 | 2 | %d |
| short unsigned int | 0 to 65535 | 2 | %u |
| long signed int | -2147483648 to +2147483647 | 4 | %ld |
| long unsigned int | 0 to 4294967295 | 4 | %lu |
| float | -3.4e38 to 3.4e38 | 4 | %f |
| double | -1.7e4932 to +1.7e308 | 8 | %lf |
| long double | -1.7e4932 to 1.7e4932 | 10 | %lf |
Evaluation of expression An expression is a combination of variables, constants and operators arranged according to the syntax of the language. C can handle any complex expression with ease. It is little bit different from algebraic expression.
| Algebraic Expressions | C Expressions |
| axb-cxd | a*b-c*d |
| (m+n)(a+b) | (m+n)*(a+b) |
Evaluation of expression: We can evaluate an expression by using assignment statement. As Variable = Expression. e.g. : Temp = ((f * cos(x)/sin (y))+(g * sin(x)/cos(y))) All relevant variables must be assigned values before the evaluation of the expression. Type conversion in expression: To effectively develop C programs, it would be necessary for you to understand the rules that are used for the implicit conversion of operands. If an expression contains an operation between an int and a float, the int would be automatically promoted to a float before carrying out of operation.
Evaluation of expression An expression is a combination of variables, constants and operators arranged according to the syntax of the language. C can handle any complex expression with ease. It is little bit different from algebraic expression.
| Algebraic Expressions | C Expressions |
| axb-cxd | a*b-c*d |
| (m+n)(a+b) | (m+n)*(a+b) |
Evaluation of expression: We can evaluate an expression by using assignment statement. As Variable = Expression. e.g. : Temp = ((f * cos(x)/sin (y))+(g * sin(x)/cos(y))) All relevant variables must be assigned values before the evaluation of the expression. Type conversion in expression: To effectively develop C programs, it would be necessary for you to understand the rules that are used for the implicit conversion of operands. If an expression contains an operation between an int and a float, the int would be automatically promoted to a float before carrying out of operation.
Introduction Input refers to accepting data while output refers to presenting data. Every program performs three main functions accepting data from user, processing it and producing theoutput. In C language there are several input and output functions. These functions are collectively found in IO.h and such IO function together form a library name stdio.h . User will require all such library function. These library functions are classified into three broad categories: 1. Console I/O functions 2. Disc I/O functions 3. Port I/O functions
Console I/O function Console I/O refers to the operation that occur at the keyboard and the screen of your computer. Console I/O function can also be classified in two parts: 1. Formatted console I/O: Formatted I/O function accepts or present in a particular format. The example of formatted console I/O function is printf( ) and scanf( ). printf It is highly desirable that the output are presented in such a way that they are understandable and are in a form easy to use. The printf() statement provides certain features through which the screen output is effectively controlled.The general form of printf() function is: printf(“Control String “,arg1,arg2….); Control string may contain: 1. character that are simply printed as they are. 2. Conversion specification that begin with a sign. 3. Escape sequence that begin with \ sign. Given below is a list of conversion charcter that can be used with printf() function: 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 preceeded 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. Unformatted console I/O: This function cannot control the format of reading and writing the data. some of the example of this function are getch( ),getche( ),getchar( ),gets( ),putchar( ),putch( )andputs( ). getchar getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of file) is returned instead. It is therefore useful to compare this value against EOF before using it. If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly. As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control – d. Output of the program: putchar putchar puts its character argument on the standard output (usually the screen). The following example program converts any typed input into capital letters. To do this it applies the function toupper from the character conversion library ctype.h to each character in turn. An example program using putchar. Output of the program: gets gets reads a whole line of input into a string until a newline or EOF is encountered. It is critical to ensure that the string is large enough to hold any expected input lines. When allinput is finished, NULL as defined in stdio.h is returned puts puts writes a string to the output, and follows it with a newline character. An example program which uses gets and puts to double space typed input Out put of the program Note: putchar, printf and puts can be freely used together. So can getchar, scanf andgets.
| Disc & Port I/O function | ||
| Function which performs secondary storage devices like floppy disk or hard disk is calleddisk I/O functions. | ||
| Port I/O functions | ||
| This type of functions performs I/O operation among various codes like printer port,mouse port. | ||
|
|
||
Sequence control statements This type of statements insured that the instruction in a program is executed in the same order. In which they appear in the program. An example of sequential Control Statements: Out put of the program Explanation of the program: There are three variable a, b, c is declared as intdatatype the value of a=2, b=3 and the result of the sum is stored in the c variable which is 5.
Decision control & conditional statements Decision control statements and Conditional Statements allow the computer to take decision. And force to work under given condition: Decision control statements: It gives the control to the computer for taking the decisions. Two decisions control instruction which are implemented in C are following: a) The if statements. b) The if-else statements. General form of if statements is:if (condition is true) execute this statement; A structure image of if condition > Here we can add else statement also as follow: elseprintf(“you have enter number greater than 50”);} An example of if-else statement: Out put of the program: Explanation of the program: In the above given program you will be asked to enter any no which is less than 50. Suppose you enter 47 then you will get output, you have entered no. less than 50 value. Otherwise you have entered number greater than 50. A structure image of if else condition >
Case control statements The Case control statements allow the computer to take decision as to be which statements are to be executed next. It is a multi way decision construct facilitate number of alternatives. C has multi way decision statement known as switch statements. It tests the value of a given variable or expression against a list of case value and when a match found a block of statement associated with the case is executed. Syntax of switch statement: switch(expression){case constant_1:statements;case constant_2:statements;case constant_n:statements;default:statements;} Explanation: First in expression parentheses we give the condition.This condition checks to match, one by one with case constant.If value match then its statement will be executed. Otherwise the default statement will appear. A structure image of switch statements> An example program to check whether a given number is even or odd, using switch statements: Out put of the program Explanation of the program: First you will be asked to enter any numberSuppose you enter 7 Now the given condition check, so the modulus is 0 or not. (% operator is use to find out the remainder) if the modulus is 0 then ch=1 otherwise 2, statement will be execute.
Repitition& loop control statements This type of statements helps the computer to execute a group of statements repeatedly. This allows a set of instruction to be performed until a certain condition is reached. There are three types of loops in C: 1. for loop2. while loop3. do-while loop The for loop There are three parts of for loop: a)counterinitialization.b)check conditionc)modification of counter. Syntax:for (variable initialize; check condition; modify counter) {statements 1;———–;———–;statements n;} Explanation: 1. The initialization is usually an assignment that is used to set the loop control variable. 2. The condition is a relational expression that determines when the loop will exit. 3. The modify counter defines how loop control variables will change each time the loop is repeated. These three sections are separated by semicolon (;). The for loop is executed as long as the condition is true. When, the condition becomes false the programe execution will resume on the statement following the block. Advantage of for loop over other loops: All three parts of for loop (i.e. counter initialization, check condition, modification of counter) are implemented on a single line. A structure image of for loop > An example program to print a message 5 times using for loop: Out put of the program Explanation of the program: The o/p will be in the loop 1 time, 2times till 5 times. Something more about for loop: 1. for (p=1,n=2;n<17;n++):- we can assign multiple variable together in for loop. 2. for (n=1,m=50;n<=m;n=n+1,m=m-1):-The increment section may also have more than one part as given. 3. for (i=1,sum=0;i<20&&sum<100;++i):-The test condition may have any compound relation as given. 4. for (x=(m+n)/2;x>0;x=x/2):-It is also permissible to use expressions in the assignment statements of initialization and increment section as given. 5. for (;m!=100;):-we can omitted the initialization and increment section to set up time delay. while loop It is a primitive type looping control because it repeats the loop a fixed no. of time. It is also called entry controlled loop statements. Syntax: while (test_condition){body of loop} Explanation: The test condition is evaluated if the condition is true, the body of loop will be executed. A structure image of while > An example of program to print the number 1 to 10 using while loop: Out put of the program The do-while loop The minor Difference between the working of while and do-while loop is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop As against this, the do-while loop tests the condition after having executed the statement within the loop. syntax: do{body of loop;}while (test condition); A structure image of do-while loop > Explanation: It first executes the body of the loop, and then evaluates the test condition. If the condition is true, the body of loop will executed again and again until the condition becomes false. Example of program using do-while loop: Out put of the program Explanation of the program: First it will print “hello there” then it will go for condition statements.
Some more statements The break Statement We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, passing control to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement a loopwith a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition. An Example program to determine whether a number is prime or not: Out put of the program The continue Statement This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement. In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration (looping). Like a break, continue should be protected by an if statement. You are unlikely to use it very often. An example of program using continue statement: Out put of the program Thegoto Statement C has a goto statement which permits unstructured jumps to be made. It requires a label in order to identify the place where the branch is to be made. A label is any valid variable name,and must be followed by a colon(:). Syntax: gotolabel;………………label:statement; The label can be any where in the program either before or after the goto label; statement. An example program using gotostatement: Out put of the program Explanation of the program Here the program will ask untill you give negative value at the time when you give positive value then instantly it will show you the square root value of the given number. Another use of the goto statement is to transfer the control out of a loop (or nested loops) when certain particular conditions are encountered. Note: We should try to avoid using goto as far as possible because, it is not good for readability of the program or to improve the program execution speed. The exit() function This function is used for terminating the execution of C program. Syntax: exit(int status);
Introduction of Array Whenever there is need to store a group of data of the same type in the memory, arraysare used. Two terms has been described here Array and String. Strings in C are represented by the array only therefore it would be convenient to describestrings separately in the same block but in the different section. Arrays are the contiguous memory location used to store similar data type or in other terms we can say Arrays are a data structure which holds multiple variables of the same data type. Consider the case where a programmer needs to keep track of a number of people within an organization. So far, our initial attempt will be to create a specific variable for each user. This might look like: int name1 = 101;int name2 = 232;int name3 = 231; It becomes increasingly more difficult to keep track of this as the number of variablesincreases. Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the above example using arrays looks like: int names[4];names[0] = 101;names[1] = 232;names[2] = 231;names[3] = 0; We created an array called names, which has space for four integer variables. You may also see that we stored 0 in the last space of the array. This is a common technique used by C programmers to signify the end of an array. An image showing internal stucture and location distribution method of array >
Arrays are defined in the same manner as ordinary variables, except that each arrayname must be accompanied by the size specification. The general form of array declaration is: data_typearray_name[size]; data-type specifies the type of array, size is a positive integer number or symbolic constant that indicates the maximum number of elements that can be stored in the array. Example:float height[50]; This declaration declares an array named height containing 50 elements of type float.
Array Initialization The Element of array are initialized in the same way as the ordinary variables. Example: intnum[6]={2,4,5,35,12,12,67}; An example showing the index and its corresponding data (prices) > An example program of entering data into Array: Out put of the program In this example, using the for loop, the process of asking and receiving the marks is accomplished. When the count has the value 0, the scanf() statement will cause the cvalue to be stored atnum[0]. The process continues until count has the value greater than 5. Reading data from Array In the above program we enter the data into an Array. Now to read value from this array , we will again use for Loop. The below program segment explains the retrieval of the values from the array:
Two Dimensional Array Two dimensional array (2-D array) is also called Matrix General form of 2-D array is: data_typearray_name[row_size][column_size]; Example:int marks [4][2] Different ways of Initialization of a 2-Dimensional Array: int table [2][3]={0,0,0,1,1,1};initialization done by row. int table[2][3]={{0,0,0},{1,1,1}};surrounding the elements of each row by braces. int table[2][3]={{0,0,0,},initialization as matrix. An example program that stores roll number and marks obtained by a student side by side in Matrix: Explanation There are two parts of the program. In the first part a for loop will read the values of rollno. and marks, whereas in the second part another loop will print these values.
String Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character with the value 0. Because C has no built-in facilities for manipulating entire arrays (copying them, comparing them, etc.), it also has very few built-in facilities for manipulating strings. In fact, C’s only truly built-in string-handling is that it allows us to use string constants(also called string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the character. For example, we can declare and define an array of characters, and initialize it with a string constant: char string[] = “Hello, world!”; Two ways to initilize string > In this case, we can leave out the dimension of the array, since the compiler can compute it for us based on the size of the initializer. This is the only case where the compiler sizes a string array for us, however; in other cases, it will be necessary that we decide how big the arrays we use to hold strings. An example program showing the character data type array: Out put of the program In the above example, a character based array named word is declared, and each element of array is assigned a character. The last element is filled with a zero value, to signify the end of the character string (in C, there is no string type, so character based arrays are used to hold strings). A printf statement is then used to print out all elements of the array.
Function Definition Functions are self contained program segments that carry out some specific well defined task. In “C” , we include the header files like stdio, conio, string, etc. These files contain number of library functions which are as follows: printf( ), scanf( ), getchar( ), putchar( ), getche( ), gets( ), puts( ), strlen( ), getch( ), etc. In C it is possible for the function to call themselves. we will see how it can be possible through Recursions. A Function is a self-contained block of statement that perform a coherent task of some kind. Every C program must have a function. One of the function must be main(). Why should we use Function? a) Using function it becomes easier to write programs and keep track of what they are doing b) Length of the program can be reduced by using function. c) Debugging is easier. d) It facilitates top-down modular programming. Classification of Function C function can be classified into two categories: 1. Library function: They are predefined in the standard library of C. We need to include the Library. 2. User-defined function: User defined functions are need to be developed by the user at the time of program writing.
Function Declaration Before defining the function, it is desired to declare the function with its prototype. In function prototype, the return value of function, type, and number of argument are specified. Function declaration is written in following ways: return data_typefunction_name (data_type argument 1, data_type argument 2 …………….data_type argument n){local variable declaration;executable statement 1;executable statement 2…………………………………………………………executable statement n;return(expession);} Note: An empty pair of parenthesis must follow the function name if the function definition does not include any arguments. Example: If it returns a float than command is: float f1(float arg 1, intarg 2); if it returns no value or return a character, then replace float by void or char respectively. If no arguments passed into a function than command is: char fun1 ( ); An example program using a small add function: Out put of the program
Function Declaration Before defining the function, it is desired to declare the function with its prototype. In function prototype, the return value of function, type, and number of argument are specified. Function declaration is written in following ways: return data_typefunction_name (data_type argument 1, data_type argument 2 …………….data_type argument n){local variable declaration;executable statement 1;executable statement 2…………………………………………………………executable statement n;return(expession);} Note: An empty pair of parenthesis must follow the function name if the function definition does not include any arguments. Example: If it returns a float than command is: float f1(float arg 1, intarg 2); if it returns no value or return a character, then replace float by void or char respectively. If no arguments passed into a function than command is: char fun1 ( ); An example program using a small add function: Out put of the program
Recursion Repetitive calling of the same function is called recursion. Recursions are those functions which call itself again and again. Recursive functions can easily become infinite loops. An example program to find out the factorial of any number is the one of the best example of recursion: Out put of the program
Introduction Pointers are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret of C is in its use ofpointers. C uses pointers a lot. Why? It is the only way to express some computations. It produces compact and efficient code. It provides a very powerful tool. C uses pointers explicitly with following: 1. Functions.2. Arrays.3. Structures. (discussed later) Note: Pointers are perhaps the most difficult part of C to understand. C’s implementation is slightly different from other languages. What is a Pointer? A pointer is a variable which can hold the address of a memory location rather than the value at the location. Pointer Notation The actual address of a variable is not known immediately. We can determine the address of the variable using address of operator(&). We have already seen the use of address of operator in the scanf() function. Another pointer operator available in C is “*” called “value of address” operator. It gives the value stored at a particular address. This operator is also known as indirection operator. Pointer Declaration To declare a pointer to a variable: int *pointer; Note: We must associate a pointer to a particular type: You can’t assign the address of ashortint to a long int,
Pointer expression Like other variables pointer variable can also be used in expressions. Arithmetic andcomparison operation can be performed on the pointers. Pointer Arithmetic Example: Addition of a number to a pointer int i=4,*j,* j=&i;j=j+1;j=j+9;k=j+3; Example: Subtraction of number from a pointer int i=4,*j,*k; j=&i;j=j-2;j=j-5;k=j-6; But the following operation are not allowed on pointers: a) multiplication of pointer with a constant b) addition of two pointer c) division of pointer with a constant Pointer Comparison Pointer can be compared using relational operator. Expression such as- p1>p2 p1=p2p1!=p2 are allowed.
Pointer & functions Let us now examine the close relationship between pointers and C’s other major parts. We will start with functions. When C passes arguments to functions it passes them by value. There are many cases when we may want to alter a passed argument in the function and receive the new value back once the function has finished. C uses pointers explicitly to do this. The best way to study this is to look at an example where we must be able to receive changed parameters. Let us try and write a function to swap variables around? The usual function call: swap (a, b) won’t work. Pointers provide the solution: Pass the address of the variables to the functions and access address of function. Thus our function call in our program would look like this: swap (&a, &b) The Code to swap is fairly straightforward: void swap(int *px, int *py){ inttemp;temp = *px;/* contents of pointer */*px = *py;*py = temp;}
Pointer & Array Pointers and arrays are very closely linked in C. Hint: Think of array elements arranged in consecutive memory locations. Consider the following: int a[10], x;int *pa;pa = &a[0]; /* pa pointer to address of a[0] */x = *pa; /* x = contents of pa (a[0] in this case) */ Warning: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things. C however is much more subtle in its link between arrays and pointers. For example we can just type: pa = a;insteadofpa = &a[0]anda[i] can be written as *(a + i).i.e. &a[i] =a + i. We also express pointer addressing like this: pa[i] =*(pa + i). However pointers and arrays are different: A pointer is a variable. We can do pa = a and pa++. An Array is not a variable. a = pa and a++ ARE ILLEGAL This stuff is very important. Make sure you understand it. We will see a lot more of this. We can now understand how arrays are passed to functions. When an array is passed to a function what is actually passed is its initial element location in memory So: strlen(s) strlen(&s[0]) This is why we declare the function: intstrlen(char s[]); An equivalent declaration is: intstrlen(char *s); since char s[] is equivalent to char *s. strlen () is a standard library function that returns the length of a string. Let’s look at how we may write a function: intstrlength(char *s){char *p = s;while (*p != ”);p++;return p-s;} Now let’s write a function to copy a string to another string. strcpy () is a standard library function that does this: void strcopy (char *s, char *t){ while ( (*s++ = *t++) != `’ );} This uses pointers and assignment by value. Note: Uses of Null statements with while. Malloc Library Function Function: Allocates main memorySyntax: void*malloc(size_t size);Prototype in: stdlib.h, alloc.h Remarks: malloc allocates a block of size bytes from the C heap memory. It allows a program to allocate memory explicitly, as it is needed and in the exact amounts needed. Calloc Library Function Function: Allocates main memorySyntax: void*calloc(size_t n size);Prototype in: stdlib.h, alloc.h Remarks: Calloc provides access to the C heap memory . Calloc allocates a block of size n items of x size. The block is cleared to 0.
Pointer & Array Pointers and arrays are very closely linked in C. Hint: Think of array elements arranged in consecutive memory locations. Consider the following: int a[10], x;int *pa;pa = &a[0]; /* pa pointer to address of a[0] */x = *pa; /* x = contents of pa (a[0] in this case) */ Warning: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things. C however is much more subtle in its link between arrays and pointers. For example we can just type: pa = a;insteadofpa = &a[0]anda[i] can be written as *(a + i).i.e. &a[i] =a + i. We also express pointer addressing like this: pa[i] =*(pa + i). However pointers and arrays are different: A pointer is a variable. We can do pa = a and pa++. An Array is not a variable. a = pa and a++ ARE ILLEGAL This stuff is very important. Make sure you understand it. We will see a lot more of this. We can now understand how arrays are passed to functions. When an array is passed to a function what is actually passed is its initial element location in memory So: strlen(s) strlen(&s[0]) This is why we declare the function: intstrlen(char s[]); An equivalent declaration is: intstrlen(char *s); since char s[] is equivalent to char *s. strlen () is a standard library function that returns the length of a string. Let’s look at how we may write a function: intstrlength(char *s){char *p = s;while (*p != ”);p++;return p-s;} Now let’s write a function to copy a string to another string. strcpy () is a standard library function that does this: void strcopy (char *s, char *t){ while ( (*s++ = *t++) != `’ );} This uses pointers and assignment by value. Note: Uses of Null statements with while. Malloc Library Function Function: Allocates main memorySyntax: void*malloc(size_t size);Prototype in: stdlib.h, alloc.h Remarks: malloc allocates a block of size bytes from the C heap memory. It allows a program to allocate memory explicitly, as it is needed and in the exact amounts needed. Calloc Library Function Function: Allocates main memorySyntax: void*calloc(size_t n size);Prototype in: stdlib.h, alloc.h Remarks: Calloc provides access to the C heap memory . Calloc allocates a block of size n items of x size. The block is cleared to 0.
Multi Dimensional Arrays & Pointer We should think of multidimensional arrays in a different way in C: A 2D array is really a 1D array, each of whose elements is itself an array Hence a[n][m] notation. Array elements are stored row by row. When we pass a 2D array to a function we must specify the number of columns and the number of rows is irrelevant. The reason for this is pointers again. C needs to know how many columns in order that it can jump from row to row in memory. Considerint a[5][35] to be passed in a function: We can do: f(int a[][35]) {…..} or even: f(int (*a)[35]) {…..} We need parenthesis (*a) since [] have a higher precedence than * So:int (*a)[35]; /*declares a pointer to an array of 35 int */int *a[35]; /*declares an array of 35 pointers to int */ Now lets look at the (subtle) difference between pointers and arrays. Strings are a common application of this. Consider: char *name[10];char Aname[10][20]; We can legally do name[3][4] and Aname[3][4] in C.
Multi Dimensional Arrays & Pointer We should think of multidimensional arrays in a different way in C: A 2D array is really a 1D array, each of whose elements is itself an array Hence a[n][m] notation. Array elements are stored row by row. When we pass a 2D array to a function we must specify the number of columns and the number of rows is irrelevant. The reason for this is pointers again. C needs to know how many columns in order that it can jump from row to row in memory. Considerint a[5][35] to be passed in a function: We can do: f(int a[][35]) {…..} or even: f(int (*a)[35]) {…..} We need parenthesis (*a) since [] have a higher precedence than * So:int (*a)[35]; /*declares a pointer to an array of 35 int */int *a[35]; /*declares an array of 35 pointers to int */ Now lets look at the (subtle) difference between pointers and arrays. Strings are a common application of this. Consider: char *name[10];char Aname[10][20]; We can legally do name[3][4] and Aname[3][4] in C.
| Pointer & functions | |||
| When an array is passed to a function as an argument , only the address of the first element of the array is passed , but not the actual values of the array elements. | |||
| If x is an array, when we call sort(x), the address of x[0] is passed to the function sort(). | |||
| The function uses this address for manipulating the array elements. | |||
| The address of a variable can be passed as an argument to a function in the normal fashion. | |||
| When address is passed to a function , the parameters receiving the address should be pointers. | |||
| The process of calling a function using pointer to pass the address of variable is known as call by reference. | |||
| The function which is called by reference can change the value of the variable used in the call. | |||
| Example: | |||
| main() | |||
| { | |||
| int x; | |||
| x=20; | |||
| change(&x); | |||
| printf(“%d\n”,x); | |||
| } | |||
| change( int *p) | |||
| { | |||
| *p=*p+10; | |||
| } | |||
| Explanation: When the function change() is called, the address of the variable x, not its value, is passed into the function change(). | |||
| Inside change(), the value at which p points is incremented by 10 , and the changed value is then displayed in the main function. | |||
|
|
|||
| Introduction | |||
| The C language allows us to create custom data types. | |||
| The structure is a custom data type which c combines different data types . | |||
| The structure is a custom data type which combine different data types to form a new user define data type. | |||
| Definition | |||
| A structure is a collection of variable reference under one name providing a convincible means of related information together. | |||
| Format: structtag_name | |||
| { | |||
| data _type member1; | |||
| data_type member2; | |||
| ——————- | |||
| ——————— | |||
| }; | |||
| here a keyboard struct declares a structes to hold the details of field of different data types. | |||
| Example: | |||
| structaddr | |||
| { | |||
| char name [30]; | |||
| char city [15]; | |||
| intpincode ; | |||
| }; | |||
| Creating Structure variable | |||
| structure can be created in two ways: | |||
| 1. declaration using tagname anywhere in the program. | |||
| Example: | |||
| struct book | |||
| { | |||
| char name [30]; | |||
| char author [25]; | |||
| float price; | |||
| }; | |||
| struct book book1 book2 | |||
| 2. it is also allowed to combine structure declaration and variable declaration in one statement. | |||
| Example: | |||
| struct person | |||
| { | |||
| char *name; | |||
| int age; | |||
| char*address; | |||
| }; | |||
| p1,p2,p3 | |||
| while declaring structure variable along with their definition, the use of tag-name is optional. | |||
| Struct | |||
| { | |||
| char *name; | |||
| int age; | |||
| char * address; | |||
| } | |||
| p1,p2,p3 | |||
| Image showing how the given value allocate in structure with the help of an example > | |||
|
|
|||
| Giving values to member | |||
| The link between a member and a variable is established using member operator `.’ to dot operator. | |||
| An example program to define a structure and assign value to members: | |||
| Out put of the program | |||
|
|
|||
| Structure Initialization | |||
| a structure variable can be initialization as any other data type. | |||
| Main() | |||
| { | |||
| static struct | |||
| { | |||
| int weight; | |||
| float height; | |||
| } | |||
| } | |||
| student{560,080,75}; | |||
| This assign the value 60 to student weight and 180.75 student height. there is a one to one correspondents between the members and their initializing values. | |||
| The following statements initialize two structures variables: | |||
| Main() | |||
| Structst_decord | |||
| { | |||
| int weight; | |||
| float height; | |||
| } | |||
| static structst_record student2={53, 170,60} | |||
| } | |||
| another method is to initlialize a structure variable outside the function. | |||
| Structst_record/* No static word*/ | |||
| { | |||
| int weight; | |||
| int height | |||
| } | |||
| student={60,50,75} | |||
| } | |||
| main() | |||
| { | |||
| static structst_record student2={53,170,60} | |||
| } | |||
|
|
|||
| Comparison of structure variables | |||
| Two variables of the same structure type can be compared the same way as ordinary variables. | |||
| operation meaning | |||
| person1=person2*assign perosn2 to person1 | |||
| person1== person2*compare all name of person1 and person2 and return1 | |||
|
|
|||
| Arrays of structures | |||
| The most common use of structures is in arrays of structures. To declare an array of structures, first the structure is defined then an array variable of that structure is declared. | |||
| E.g.: struct class student [100]; | |||
| It defines an array called student which consists of 100 elements of structure named class. | |||
| Ans is stored inside the memory in the same way as a multidimensional array example program. | |||
| To implements on array of structures. | |||
|
|
|||
| Arrays with in structures | |||
| Single as multidimensional arrays of type int as float can be defined as structure members. | |||
| Example: | |||
| struct marks | |||
| { | |||
| int number; | |||
| float subject[3]; | |||
| } | |||
| student [2]; | |||
| Here the member subject contains three elements, subject[0], subject[1] and subject[2]there elements can be accessed using appropriate subscript. | |||
| For instance, the name student [1] student [2]; would refer to the marks obtained in the third subject by the secured student. | |||
|
|
|||
| Structures with in structures | |||
| Structures within a structure means nesting of structures. | |||
| Example: | |||
| struct salary | |||
| { | |||
| char name [20]; | |||
| char department [10]; | |||
| int basic-pay; | |||
| int dearness-allowance; | |||
| inthuse_rent_allowance; | |||
| intcity_allowance; | |||
| } | |||
| employee; | |||
| This structure defines name, department, basic pay and three kinds of allowances. | |||
| All the items related to allowance can be grouped together and declared under a sub-stricture. As shown below, strut salary | |||
| { | |||
| char name []2; | |||
| char department [10]; | |||
| struct; | |||
| } | |||
| int dearness; | |||
| inthouse_rent; | |||
| int city; | |||
| [allowance; | |||
| } | |||
| employee’s; | |||
| The salary structure contains a member named allowance which use is a structures with. | |||
| Three members. Now ; the member compared in the inner structure;, namely, ;dearness,house_rent and city can ;be left to as; | |||
| employee. ;allowance. Dearness | |||
| employee. Allowance. House_rent | |||
| employee allowance. city | |||
| The inner most member in a nested structure can be accessed by chaining all the concerned structure variables (from outermost to inner most) with the member using dot operator. | |||
|
|
|||
| Structures with in structures | |||
| Structures within a structure means nesting of structures. | |||
| Example: | |||
| struct salary | |||
| { | |||
| char name [20]; | |||
| char department [10]; | |||
| int basic-pay; | |||
| int dearness-allowance; | |||
| inthuse_rent_allowance; | |||
| intcity_allowance; | |||
| } | |||
| employee; | |||
| This structure defines name, department, basic pay and three kinds of allowances. | |||
| All the items related to allowance can be grouped together and declared under a sub-stricture. As shown below, strut salary | |||
| { | |||
| char name []2; | |||
| char department [10]; | |||
| struct; | |||
| } | |||
| int dearness; | |||
| inthouse_rent; | |||
| int city; | |||
| [allowance; | |||
| } | |||
| employee’s; | |||
| The salary structure contains a member named allowance which use is a structures with. | |||
| Three members. Now ; the member compared in the inner structure;, namely, ;dearness,house_rent and city can ;be left to as; | |||
| employee. ;allowance. Dearness | |||
| employee. Allowance. House_rent | |||
| employee allowance. city | |||
| The inner most member in a nested structure can be accessed by chaining all the concerned structure variables (from outermost to inner most) with the member using dot operator. | |||
|
|
|||
| Union | |||
| Introduction | |||
| Union are derived data types, the way structure are. Though, unions and structures look alike, and there is a fundamental difference. | |||
| While structure enables you to create a number of different variables stored in difference places in memory, unions enable you to treat the same space as a number of different variables | |||
| Union-Definition and Declaration | |||
| Unions, like structures, contain members whose individual data types may differ from one another. | |||
| However, the members within a union all share the some storage space within the computer’s memory, whereas each member within a structure is assigned its own unique storage area. | |||
| Thus, unions are used to conserve memory. | |||
| They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time. | |||
| Within a union, the bookkeeping required to store members whose data types are different (having different memory requirements) is handled automatically to the compiler. | |||
| However, the user must keep track of what type of information is stored at any given time. | |||
| An attempt to access the wrong type of information will produce meaningless results. In general terms, the composition of a union may be defined as: | |||
| Union tag | |||
| { | |||
| Member 1; | |||
| Member 2; | |||
| ….. | |||
| member n; | |||
| }; | |||
| Where union is required keyword and the other terms have the same meaning as in a structure definition. | |||
| Individual union variables can then be declared as: | |||
| storage-class union tag variable 1, variable 2, . . . , variable n; | |||
| Where storage-class is an optional storage class specified, union is a required keyword, tag is the name that appears in the union definition, and variable 1, variable 2, . . . , variable n are union. | |||
| The two declarations may be combined, just as we did with structures. Thus, we can writeStorage-class union tag | |||
| { | |||
| Member 1; | |||
| Member 2; | |||
| . . . . . | |||
| member n; | |||
| } | |||
| The tag is optional in this type of declaration. | |||
| Notice that the union and structure declarations are external to the program functions, but the structure variable is defined locally within each function. | |||
|
|
|||
| Accessing a union member | |||
| To access a union member, you can use the same syntax that you use for structure members. | |||
| Example: | |||
| code.m, code.x etc. | |||
| During execution, we should make sure that the value of accessing member is currently stored. | |||
|
|
|||
Initialization of Union variable A union variable can be initialized , provided its storage class is either external or static. Only one member of a union can be assigned a value at any one time. The initialization value is assigned to the first member within the union. An example program to demonstrate initialization of union variables:
| Uses of Union | ||
| Union, like structure, contain members whose individual data type may differ to each other. | ||
| But the members that compose a union share the same storage area within the computer’s memory, whereas each member within a structure is assigned its own unique storage area. | ||
| Thus, union are used to conserve memory. | ||
| 1. Unions are useful for application involving multiple members, where value need not to be assigned to all of the members at any one time. | ||
| 2. Unions are useful whenever there is a requirement to access the same memory location in more than one way. etc. | ||
|
|
||
Linked list Before talking about the different mechanism of data structure we will take a short view ofDMA (Dynamic Memory Allocation). DMA: C language requires the number of elements in an array to be specified at compile time. But it is not practically possible with Array. In array we allocate the memory first and then start using it. This may result in failure of a program or wastage of memory space. The concept of dynamic memory allocation can be used to eradicate this problem. In this technique , the allocation of memory is done at run time. C language provides four library function known as memory management function that can be used for allocating and freeing memory during program execution. These are: malloc: allocate memory and return a pointer to the first byte of allocated space. Example: ptr=(cast.type*)malloc(byte_size); calloc: allocates the memory spaces, initialize them to zero and returns pointer to first byte. Example: ptr=(cast_type*)calloc(n.elem_size); free: frees previously allocated space. Example: free(ptr); realloc: modifies the size of previously assigned space Example: ptr=realloc(ptr,newsize); We studied about Array there we can observe one major disadvantage of Array is ,if an array is not filled by value, then memory will be locked up. To overcome this problem we use Linked lists and other data structure mechanism. Linked List are a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Specifically, the programmer writes a struct definition that contains variables holding information about something, and then has a pointer to a struct of its type. Each of these individual struct in the list is known as a node. Think of it like a train. The programmer always stores the first node of the list. This would be the engine of the train. The pointer is the connector between cars of the train. Every time the train add a car, it uses the connectors to add a new car. This is like a programmer using the keyword new to create a pointer to a new struct In memory it is often described as looking like this: ———- ———– Data – >- Data ->———- – ———– Pointer- – – – Pointer———– ———-
| tack | |||
| A stack is a data structure that resembles a stack of trays in a spring loaded bin. | |||
| A tray will be added to the bin on top of the stack. When you add a tray, the previous one on top will go down by one position. | |||
| You can add trays till the first trays reach the bottom of the stack. Similarly, a tray can be removed only from the top of the stack. | |||
| In the computer science item is nothing but a data element or an object. | |||
| Therefore a stack is a list in which items are added, deleted or examined at one only one end. | |||
| The size of the stack is defined by the user before compilation and hence this is a static data structure. | |||
| It adopts LIFO (last in first out ) methodology for storage and retrieval. | |||
|
|
|||
| Queue | |||
| Queue is also a list. Here, the data items are added at one end and removed from the other hand work as first in first out for storage and retrieval. | |||
| Queues are used extensively in operating systems to keep track of user waiting for resources such as CPU, printing etc. | |||
| It adopts FIFO(first in first out )methodology for storage and retrieval. | |||
|
|
|||
Introduction Many applications require that information be written to or read from an auxiliary memory. Such information is stored on the memory device in the form of a data file. Thus files allow us to store information permanently, and to access and alter that information whenever necessary. In C, an extensive set of library; functions is available for creating and processing data files. Unlike other files. However, there are two different types of data files 1. Stream-oriented (or standard) data files: Stream oriented data files are generally easier to work with and are therefore more commonly used. Stream-oriented data files can be subdivided into two categories. The first category are text files, consisting of consecutive characters. There characters can be interpreted as individual data items, or as components of strings or numbers. 2. System-oriented (or low level) data files: System-oriented data files, often referred to as unformatted data files, organizes structures, such as arrays and structures. A separate set of library functions is available for processing stream-oriented data files of this type. These library functions provide single instructions that can transfer entire arrays or structures to or from data files. Note: Library function has been discussed in detail in next section.
File operation There are two distinct ways to perform the file operation in C: 1. Low level I/O operation (it uses UNIX system call therefore we won’t discuss here) 2. High level I/O operation (it uses function in C’s Standard I/O library) List of I/O function with their operation:
| fopen() | creates a new file for use or opens an existing file for use. |
| fclose() | close a file which has been opened for use. |
| getc() | reads a character to a file. |
| putc() | writes a character to a line. |
| fprintf() | writes a set of data values to a file. |
| fscanf() | reads a set of data values from a file. |
| getw() | reads an integer from a file. |
| putw() | writes an integer to a file. |
| feof() | test for an end of file condition. |
Opening & closing a data file When working with a stream-oriented data file, the first step is to establish a buffer area (a holt station for data processing) where information is temporarily stored while being transferred between the computer’s memory and the data file. This buffer area allows information to be read from or written to the data file more readily than would otherwise be possible. The buffer area is established by writing FILE * ptvar; Where FILE (uppercase letter required) is a special structure type that establishes thebuffer area, and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type FILE is defined within a system include file, typically stdio.h. The pointerptvar is often referred to as a stream pointer, or simply a stream. A data file must be opened before it can be created or processed. This associates the file name with the buffer area (i.e., with the stream). It also specifies how the data file will be utilized, i.e., as a read-only file, a write -only file, or a read/write file, in which both operations are permitted. The library function open is used to open a file. This function is typically written as Ptvar =open (file-name, file-type) Where file-name and file-type are strings that represent the name of the data file and the manner in which the data file will be utilized. The name chosen for the file-name must be consistent with the rules for naming files, as determined by the computer’s operating system. The file-type must be one of the strings shown:
| “r” | Open an existing file for reading only. |
| “w” | Open a new file for writing only. If a file with the specified filename currently exists, it will be destroyed and a new file will be created in its place. |
| “a” | Open an existing file for appending. A new file will be created if the file with the specified file-name don’t exists. |
| “r+” | open an existing file for both reading and writing |
| “w+” | Open an existing file for both reading and writing. If a file with the specified file name currently exists, it will be destroyed and a new file created in its place |
| “a+” | Open an existing file for both reading and appending. A new file will be created if the file with the specified file-name does not exists. |
Opening & closing a data file When working with a stream-oriented data file, the first step is to establish a buffer area (a holt station for data processing) where information is temporarily stored while being transferred between the computer’s memory and the data file. This buffer area allows information to be read from or written to the data file more readily than would otherwise be possible. The buffer area is established by writing FILE * ptvar; Where FILE (uppercase letter required) is a special structure type that establishes thebuffer area, and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type FILE is defined within a system include file, typically stdio.h. The pointerptvar is often referred to as a stream pointer, or simply a stream. A data file must be opened before it can be created or processed. This associates the file name with the buffer area (i.e., with the stream). It also specifies how the data file will be utilized, i.e., as a read-only file, a write -only file, or a read/write file, in which both operations are permitted. The library function open is used to open a file. This function is typically written as Ptvar =open (file-name, file-type) Where file-name and file-type are strings that represent the name of the data file and the manner in which the data file will be utilized. The name chosen for the file-name must be consistent with the rules for naming files, as determined by the computer’s operating system. The file-type must be one of the strings shown:
| “r” | Open an existing file for reading only. |
| “w” | Open a new file for writing only. If a file with the specified filename currently exists, it will be destroyed and a new file will be created in its place. |
| “a” | Open an existing file for appending. A new file will be created if the file with the specified file-name don’t exists. |
| “r+” | open an existing file for both reading and writing |
| “w+” | Open an existing file for both reading and writing. If a file with the specified file name currently exists, it will be destroyed and a new file created in its place |
| “a+” | Open an existing file for both reading and appending. A new file will be created if the file with the specified file-name does not exists. |
Processing a data file Most data file applications require that a data file be altered as it is being processed. For example, in an application involving the processing of customer records, it may be desirable to add new records to the file there requirements in turn suggest several different computational strategies. Another approach is to work with two different data files– an old file and a new file. Each record is read from the old file, updated as necessary, and then written to the new file. When all of the records have been updated, the old file is deleted or placed into archival storage and the new file renamed. Hence, the new file become the struck for the next round of updates. Historically, the origin of this method goes back to the early days of computing, when data files were maintained on magnetic tapes. The method is still used, however, because it provides a series of old source. File that can be used to generate a customer history. The most recent source file can also be used to recreate the current file if the current file is damaged or destroyed.
Processing a data file Most data file applications require that a data file be altered as it is being processed. For example, in an application involving the processing of customer records, it may be desirable to add new records to the file there requirements in turn suggest several different computational strategies. Another approach is to work with two different data files– an old file and a new file. Each record is read from the old file, updated as necessary, and then written to the new file. When all of the records have been updated, the old file is deleted or placed into archival storage and the new file renamed. Hence, the new file become the struck for the next round of updates. Historically, the origin of this method goes back to the early days of computing, when data files were maintained on magnetic tapes. The method is still used, however, because it provides a series of old source. File that can be used to generate a customer history. The most recent source file can also be used to recreate the current file if the current file is damaged or destroyed.
| Unformatted data file | |||
| Some applications involve the use of data files to store block of data, where each block consists of a fixed number of contiguous bytes. | |||
| Each block will generally represent a complex data structure, such as a structure or an array. | |||
| For example, a data file may consist of multiple structures having the same composition, or it may contain multiple arrays of the same type and size. | |||
| For such applicators it may be desirable to read the entire block from the data, or write the entire block to the data file, rather than reading or writing the individual components (i.e., structure members of array elements) within each block separately. | |||
| The library functions fread and fwrite are intended to be used in situations of this type. | |||
| There functions are often referred to as unformatted read and write functions. Similarly, data files of this type are often referred to as unformatted data file. | |||
| Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the number of data blocks being transferred, and the stream pointer. | |||
| Thus, a typical fwrite function might be written as: fwrite(&customer, sizeof(record), 1, fpt); | |||
| Where customer is a structure variable of type record, and fpt is the stream pointer associated with a data file that has been opened for output. | |||
| An example program to create an unformatted data file containing customer records: | |||
| Reading file: | |||
| Displaying the contents: | |||
|
|
|||
Introduction The C preprocessor is a tool which filters your source code before it is compiled. The preprocessor allows constants to be named using the # notation. The preprocessor provides several other facilities which will be described here. It is particularly useful for selecting machine dependent pieces of code for different computer types, allowing a single program to be compiled and run on several different computers. The C preprocessor isn’t restricted to use with C programs only. Programmers who use other languages may also find it useful, however it is tuned to recognize features of the C language like comments and strings, so its use may be restricted in other circumstances. Set of commonly used Preprocessor Directives and their Functions:
| #define | defines a macro substitution. |
| #undef | undefined a macro. |
| #include | specifies the files to be include. |
| #ifdef | tests for a macro definition |
| #ifndef | tests whether a macro is not defined. |
| #if | tests a compile-time condition. |
| #endif | specifies the end of #if. |
| #else | specifies alternatives when #if test fails. |
These Preprocessor or directives can be divided into three categories: 1. Macro Substitution Directives2. File Inclusion Directives3. Compiler Control Directives
Macro substitution directives We have already met this facility, in its simplest form it allows us to define textual substitutions using #define statement. The #define statement can be used for more, however, than simply defining symbolic constants. In particular, it can be used to define macros; its, single identifiers that are equivalent to expressions, complete statement or groups of statements. Macros resemble function in this sense. They are defined in an altogether different manner than functions, however, and they are treated differently during the compilation process. Format: #define identifier string e.g.: #define MAXSIZE 256 This will lead to the value 256 being substituted for each occurrence of the word MAXSIZE in the file. Example: Out put of the program This program contains the macro area, which represents the expression length* width. When the program is compiled, the expression length * width will replace the identifier area within the printf statement, so that printf statement will become Printf(“\narea =%d”, length *width); Note that the format string ” \n area =%d” is unaffected by the #define statement. When the program is executed, the values for length and width are entered interactively from the keyboard, and the corresponding value for area is displayed. A typical interactive session is shown below. The user’s responses are underlined, as usual. Length =_3Width =_4Area=12 Macro definitions are customarily placed at the beginning of a file, ahead of the first function definition. The scope of a macro definition extends from its point of definition to the end of the file. However, a macro defined in one file is not recognized within another file. Multilane macros can be defined by placing a backward slash (\) the end of each line except the last. This feature permits a single macro (i.e. a single identifier) to represent a compound statement. Here is another simple c program that contains multilane macro: Out put of the program Macros are sometimes used in place of functions within a program. The use of a macro in place of a function eliminates the time delays associated with function calls. If a program contains many reported function calls, the time savings resulting from the use of macros can become significant. On the other hand, macro substitution will take place whenever a reference to a macro appears within a program. Thus, a program that contains several references to the same macro may become unreasonably long. We therefore face a tradeoff between execution speed and size of the compiled object program. The use of a macro is most advantageous in applications where there are relatively few functions calls but the function is called repeatedly. Using #define to Create Functional Macros #define can also be given arguments which are used in its replacement. The definitions are then called macros. Macros work rather like functions, but with the following minor differences. Since macros are implemented as a textual substitution, there is no effect on program performance (as with functions). Recursive macros are generally not a good idea. Macros don’t care about the type of their arguments. Hence macros are a good choice where we might want to operate on reals, integers or a mixture of the two. Macros are full of traps for the unwary programmer. In particular the textual substitution means that arithmetic expressions are liable to be corrupted by the order of evaluation rules. Here is an example of a macro which won’t work: #define DOUBLE(x) x+x Now if we have a statement a = DOUBLE(b) * c; This will be expanded to a = b+b * c; And since * has a higher priority than +, the compiler will treat it as. a = b + (b * c); The problem can be solved using a more robust definition of DOUBLE #define DOUBLE(x) (x+x) Here the brackets around the definition force the expression to be evaluated before any surrounding operators are applied. This should make the macro more reliable. In general it is better to write a C function than risk using a macro.
| File inclusion | |||
| The preprocessor directive #include is an instruction to read in the entire contents of another file at that point. | |||
| This is generally used to read in header files for library functions. Header files contain details of functions and types used within the library. | |||
| It must be included before the program can make use of the library functions. | |||
| Library header file names are enclosed in angle brackets, <>. These tell the preprocessorto look for the header file in the standard location for library definitions. | |||
| Example: #include | |||
| another use for #include for the programmer is where multi-file programs are being written. | |||
| Certain information is required at the beginning of each program file. This can be put into a file called globals.h and included in each program file. | |||
| Local header file names are usually enclosed by double quotes, ” “. It is conventional to give header files a name which ends in .h to distinguish them from other types of file. | |||
| Our globals.h file would be included by the following line. #include “globals.h” | |||
|
|
|||
| File inclusion | |||
| The preprocessor directive #include is an instruction to read in the entire contents of another file at that point. | |||
| This is generally used to read in header files for library functions. Header files contain details of functions and types used within the library. | |||
| It must be included before the program can make use of the library functions. | |||
| Library header file names are enclosed in angle brackets, <>. These tell the preprocessorto look for the header file in the standard location for library definitions. | |||
| Example: #include | |||
| another use for #include for the programmer is where multi-file programs are being written. | |||
| Certain information is required at the beginning of each program file. This can be put into a file called globals.h and included in each program file. | |||
| Local header file names are usually enclosed by double quotes, ” “. It is conventional to give header files a name which ends in .h to distinguish them from other types of file. | |||
| Our globals.h file would be included by the following line. #include “globals.h” | |||
|
|
|||
| Command line parameter | |||
| You may have been wondering about the empty parentheses in the first line of the main function, i.e. main(). | |||
| The parentheses may contain special arguments that allow parameters to be passed to main from the operating system. | |||
| Most versions of C permit two such arguments, which are traditionally called argc and argv, respectively. | |||
| The first of these, argc, must be an integer variable, while the second, argv, is an array of pointers of characters; i.e., an array of strings. | |||
| Each string in this array will represent a parameter that is passed to main. The value ofargc will indicate the number of parameters passed. | |||
| Example: The following outline indicates how the arguments argc and argv are defined within main. | |||
| Vod main(intargc, char *argv[]) | |||
| { | |||
| ….. | |||
| } | |||
| The first line can be written without the keyword void, i.e., | |||
| main(intargc, char *argv[]) | |||
| A program is normally executed by specifying the name of the program within a menu-driven environment. | |||
| Some compilers also allow a program to be executed by specifying the name of the program (actually, the name of the file containing the compiled object program) at the operating system level. | |||
| The program name is then interpreted as an operating system command. Hence, the line in which its appears is generally referred to as a command line. | |||
| In order to pass one or more parameters to the program when it is executed from the operating system, the parameters must follow the program name on the command line. | |||
| E.g.: Program-name parameter 1 parameter 2 . . . parameter n | |||
| The individual items must be separated from one another either by blank spaces or by tabs. | |||
| Some operating systems permits blank spaces to be included within a parameter provided the entire parameter is enclosed in quotation marks. | |||
| The program name will be stored as the first item in argv, followed by each of the parameters. Hence, if the program name is followed by n parameters. | |||
| There will be (n+1) entries in argv, ranging from argv [0] to argv [n]. Moreover, argc will automatically be assigned the value (n+1). | |||
| Note that the value for argc is not supplied explicitly from the command line. | |||
| An example program which will be executed from a command line: | |||
| Out put of the program | |||
| This program allows an unspecified number of parameters to be entered from the command line. | |||
| When the program is executed, the Count value for argc and the elements of argv will be displayed as separate lines of output. | |||
| Sample red white blue | |||
| then the program will be executed, resulting in the following output. | |||
| argc =4 | |||
| argv [0]=sample.exe | |||
| argv [1]=red | |||
| argv [2]=white | |||
| argv [3]=blue | |||
| The output tells us that four separate items have been entered form the command line. | |||
| The first is the program name, sample. exe, followed by the three parameters., red. White and blue. | |||
| Each item is an element in the array argv. (Name that sample.exe is the name of the object file resulting from the compilation of the source code sample. C.) | |||
| Similarly, if the command line is | |||
| Sample red “white blue” | |||
| The resulting output will be | |||
| argc=3 | |||
| argv [0]=sample.exe | |||
| argv [1]=red | |||
| argv [2]=white blue | |||
| In, this case the string “white blue” will be interpreted as a single parameter, because of the quotation marks. | |||
| Once the parameters have been entered, they can be utilized within the program in any desired manner. | |||
| One particularly common application is to specify the names of data files as command line parameter. | |||
|
|
|||
Introduction The C provides a large number of C functions as libraries. Some of these implement frequently used operations, while others are very specialized in their application. Wise programmers will check whether a library function is available to perform a task before writing their own version. This will reduce program development time. The library functions have been tested, so they are more likely to be correct than any function which the programmer might write. This will save time when debugging the program. For using these files ,certain files are needed to be included in the program which make call to these functions. These files are known as Header files and they contain macro definition ,type definition, and function declarations. These header files usually have an extension .h as stdio.h, ctype.h, string.h, math.h,stdlib.h, stdarg.h, time.h etc.
| Use of library functions | ||||||||||||||||||||||||
| To use a function, ensure that you have made the required #includes in your C file. Then the function can be called as though you had defined it yourself. | ||||||||||||||||||||||||
| It is important to ensure that your arguments have the expected types; otherwise the function will probably produce strange results. | ||||||||||||||||||||||||
| Some libraries require extra options before the compiler can support their use. | ||||||||||||||||||||||||
| For example, to compile a program including functions from the math.h library the command might be cc mathprog.c -o mathprog –lm | ||||||||||||||||||||||||
| The final -lm is an instruction to link the maths library with the program. The manual page for each function will usually inform you if any special compiler flags are required. | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| Some Useful library functions | ||||||||||||||||||||||||
| There is a vast collections of function .Some of them are grouped together and listed below. | ||||||||||||||||||||||||
| String Function: | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
| Mathematical Function: | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
| Date & Time Function: | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
| Utility Function: | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
| Character Class Test Functions: | ||||||||||||||||||||||||
