Successfully reported this slideshow.
Upcoming SlideShare
×
1 of 25

# Notes of c programming 1st unit BCA I SEM

154

Share

Notes of c programming by mansi 1st unit
BCA I SEM

See all

See all

### Notes of c programming 1st unit BCA I SEM

1. 1. Subject: C and Data Structures C LANGUAGE CONTENTS CHAPTER - I  Basic structure of C program  C tokens  Data types and sizes  Declaration of variables  Assigning values  Operators  Type conversions,  Expressions and evaluation  Input-Output statements CHAPTER - II  If and switch statement,  While  Do-While  For statement .CHAPTER – III  One dimensional & two dimensional arrays  Strings and String handling functions  Functions, Recursive functions, Storage classes, and Scope rules CHAPTER - IV  Pointers, Pointers and Arrays, Pointers and function arguments,  Pointers to functions.  Structures  Unions CHAPTER – V  Console & File I/O PREPARED BY : Mansi Tyagi ..
2. 2. Subject: C and Data Structures UNIT-I Introduction Now a days computers are playing very vital role in each and every field of problem solving. The communication medium between a computer and a human being is a typical 'language' i.e.. Humans are able to communicate with the computer system in some form of language. There are basically three types of languages viz.. Machine Understandable Language. Assembly Level Language and High Level Language. There are number of high level languages developed in the past three decades like FORTRAN, Pascal and Basic, C Language etc. Clearly, no other language has had so much of influence in the computing as 'C'-language. Evolution of 'C'- as a programming language has made application development very easy. ALGORITHM An algorithm is a method of representing the step-by-step procedure for solving a problem. An algorithm is useful for finding the right answer to a problem or to a difficult problem by breaking the problem into simple cases. An algorithm must possess the following properties: i) Finiteness : An algorithm should terminate in a finite number of steps. ii) Definiteness : Each step of the algorithm must be precisely stated. iii) Effectiveness : Each step must be effective, in the sense that it should be easily convertible into program statement and can be performed exactly in a finite amount of time. iv) Generality : The algorithm should be complete in itself so that it can be used to solve all problems of a given type for any input data. v) Input/Output : Each algorithm must take zero, one or more quantities as input data and yield one or more output values. Flow chart PREPARED BY : Mansi Tyagi ..
3. 3. Subject: C and Data Structures Flow chart is diagrammatic representation of an algorithm. It is built using different types of boxes of symbols. The operation to be performed is written in the box. All symbols are interconnected by arrows to indicate the flow of information and processing. Following are the standard symbols used in drawing flowcharts. (see in next page) Oval Terminal Start/stop/begin/end symbol Parallelogram Input/Output Making data available for processing (input) or recording of the processed information(output) Rectangle Process Any processing to be performed. An assignment operation normally represented by this symbol Diamond Decision Decision or switching type of operations that determines which of the alternative paths is to be followed. Circle Connecter Used for connecting different parts of flow chart. Arrow Flow Joins two symbols and also represents executions flow. Bracket with broken line Annotation Descriptive comments or explanations Double sided rectangle Predefined process Modules or subroutines given elsewhere PREPARED BY : Mansi Tyagi ..
4. 4. Subject: C and Data Structures Introduction to C: C is a programming language developed at AT& T’s Bell Laboratories of USA in 1972.It was designed and written by Dennis Ritchie. C has the features of both BASIC and PASCAL. As a middle language, C allows the manipulation of bits, bytes and addresses the basic elements with which computer functions. Importance of C 1) It is a robust language, whose rich set of built-in functions and operators can be used to write any complex program. 2) Programs written in C are efficient and fast. This is due to its variety of data types and powerful operators. 3) C’s code is very portable, in the sense that it is easy to adapt software written for one type of computer or operating system to another type. 4) C has very small key words (only 32). Its strength lies in its built-in functions. These built-in functions can be used for developing programs. 5) C language is well suited for structured programming, thus requiring the user to think of a problem in terms of functions (or) blocks. A proper collection of these functions would make a complete program. This modular structure makes program debugging, testing and maintenance easier. 6) Another important feature of C is its ability to extend itself. Basically a C program is a collection of functions that are supported by the C library. We can add our own functions to the C library. With the availability of a large number of functions, the programming task becomes simple. PREPARED BY : Mansi Tyagi ..
5. 5. Subject: C and Data Structures Simple ‘C’ Program: Before discussing any features of C, we shall look at some sample C program and analyze and understand how they work. Ex 1: C program to print a message. main() { Printf(“welcome to GITAM”) } Explanation: i) main(): i) The ‘main()’ is a special function used by the C system to tell the computer where the program starts. ii) Every program must have exactly one main function. iii) Opening brace ‘{‘ and closing brace ‘}’ are the delimiters of any function. iv) All the statements between these two braces are called as function body. v) The lines beginning with /* and ending with */ are known as comment lines. These lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. ii) printf() function: printf is a predefined, standard C function for printing output. ‘Predefined’ means that it is a function that has already been written and compiled, and linked together with our program at the time of linking. The printf function causes everything between the starting and the ending quotation marks to be printed out. In the above example, the out put will be welcome to RGMCET PREPARED BY : Mansi Tyagi ..
6. 6. Subject: C and Data Structures • Every statement in C should end with a semicolon(;) mark. Format of a simple C program: main()-------------------- function name {--------------------------- starting of the program ------- ---------------- program statements ------- }--------------------------- ending of the program Program development steps: The following steps are used in sequence for developing an efficient program: • Specifying the problem statement • Designing an algorithm • Coding • Debugging • Testing and validating • Documentation and maintenance Program execution steps: • Creating the program (or) typing the program. • Compiling the program (short-cut key- Alt+F9) • Linking the program with functions that are needed from the C library. • Running the program (short-cut key-- Ctrl +F9) PREPARED BY : Mansi Tyagi ..
7. 7. Subject: C and Data Structures ‘C’ LANGUAGE OBJECTIVES C is a general purpose structured programming language that is powerful, efficient and compact. C combines the features of high level language. Programming in C has recently become more interesting. C language provides the various operators to evaluate various expressions. C also provides decision making and branching statements. It also introduces us the concepts of arrays, structures, pointers and strings. Also provides how to mange files. Also gives the idea of data structures in which the topics stacks, queues, linked lists, sorting and searching are involved. PREPARED BY : Mansi Tyagi ..
8. 8. Subject: C and Data Structures Program development steps: There are two broad categories of programmer, the successful and not so- successful. The second category people to their keyboards and begin coding i.e. the actual writing of instructions. It is the mark of professional and successful programmers that this is one of the last stages they undertake. There are many more important steps to consider first. 1. Understand the problem: Unless the problem is clearly understood. You cannot even begin to solve it. This seems like a truism until you appreciate that a program specification seldom gives all the fact required by the programmer. The professional programmer is a pessimist, because from past experience there is always some importance information which is omitted. This needs to be identified first. 2. Examine the data: Programs are written to work on data. Unless one knows exactly how the data is organized, what it ‘looks’ like, etc., the program which processes it cannot be written. This fact becomes clearer the more one writes programs, but it is a fact all too frequently overlooked by the novice. 3. Plan the output: The output should be planned next. Not only does this help to ensure that nothing is omitted from the program, but helps to get a clear picture of what the program is trying to achieve and whether the programmer does understand the problem. 4. Designing the solution (Designing the algorithm) : There are many ways of beginning solution, so much so that entire books are devoted this subject alone. Computer scientists frequently say that programming is like any engineering task in that the program has to be designed and constructed in much the same way as any engineering project. A motorway is not built by starting at point A and steadfastly pushing on to point X. rather, months are spent in planning; charts designed; sub tasks identified as well as those which cannot begin until others have been completed; broad designs are developed and later more detailed designs constructed. It is only after a long planning period and most effective order of the subtasks is agreed upon PREPARED BY : Mansi Tyagi ..
9. 9. Subject: C and Data Structures that the construction crews actually begin work. Programming requires this same pains taking processes, with the end result standing or falling by the amount of care and attention invested in the planning stage. 5. Selecting test data: How can one ensure that once a program is eventually working the results it produces are ‘correct’? The answer is simple commonsense. Try the program out on some data to which the answers have been worked out in advance. If they match, the program should be all right. Selecting effective test data is a serious exercise and the more significant the program, the more care needs to the taken in the selection. 6. The actual coding (Implementation): At this stage, one can begin to code the detailed program designs into program instructions of a given language. If all the previous steps have been completed with due diligence, this coding should be almost ‘automatic’. The chances are high that a fairly successful program will result first time around. Although it may still contain bugs, these should be fewer and relatively easy to identify and correct. 7. Testing: The program can be tested with the test data, results checked and any errors amended. When all is correct the program can be released and set to work on live data. PREPARED BY : Mansi Tyagi ..
10. 10. Subject: C and Data Structures History & Evolution of ‘C’ & Basic structure of C program: Computer languages are classified into generations. Machine language, assembly language and high level languages are called the first, second and third generation languages respectively. That high level languages were designed precisely to address these problems provided high level control structures, input/output facilities, hardware independents and so on. The development of a self contained set of instructions which enable a computer to perform a specific task is programming. There are a variety of programming languages such BASIC, COBAL, FORTRAN, PASCAL. As computers gain more power for less money very sophisticated high level languages are developed, making programming a creative non specialist task. And one such language developed was ‘C’. ‘C’ seems a strange name for a programming language, but is one of the most popular computer languages today. ‘C’ was originally developed in the 1970’s by Dennis Ritchie at Bell telephone laboratories INC. ‘C’ was an offspring of the BCPL (Basic Combined Programming Language) called B. The C language is often described as a middle level language, because it combines the best features of high level languages with the control and flexibility of assembly language. Features and applications of C languages: 1. ‘C’ is general purpose structured programming language. 2. ‘C’ is powerful, efficient, compact and flexible. 3. ‘C’ is highly portable. 4. ‘C’ is a robust language whose rich set of built in function and operators can be used to write any program. 5. ‘C’ is a well suited for writing systems software as well as application programming. 6. ‘C’ has the ability to extend itself. We can continuously add our own functions to the existing ‘C’ library functions. PREPARED BY : Mansi Tyagi ..
11. 11. Subject: C and Data Structures 7. ‘C’ programs can be run on any of the different computer with little or no alteration. 8. ‘C’ is widely available commercial ‘C’ compilers are available on most personal computers, mini and main frames. 9. ‘C’ language allows reference to a memory location with the help of pointer which holds the address of the memory location. 10. ‘C’ language allows dynamic allocation of memory i.e. a program can request the operating system to allocate/release memory. 11. ‘C’ language allows manipulations of data at the lowest level i.e. bit level manipulation. This feature is extensively useful in writing system software programs. 12. ‘C’ is a case sensitive language. Basic structure of C program: A ‘C’ program can be viewed as a group of building blocks called functions. A function is a sub-routine that may include one or more statements designed to perform a specific task. To write a ‘C’ program we first create functions and then put them together. A ‘C’ program may contain a one or more sections as given below. Main function section //Must { Declaration part Executable part. } PREPARED BY : Mansi Tyagi .. Documentation Section //optional Link section //optional Defining section //optional Global declaration section //optional
12. 12. Subject: C and Data Structures Sub program section //optional Function 1 Function 2 Function n 1) The documentations section consists of comment lines giving the name of the program ,the author and other details which the programmer would like to use later. these comments beginning with the two Characters * and ending with the characters*. 2) The link section provides to the compiler to link functions from the system library 3) The definition section defines all symbolic constants. There are some variables that are used in one or more functions, such variables are called global variables and are declared in the global declaration section that is outside of all the functions. 4) Every C program must have one main () function section. This section can contain two parts; they are Declaration part and Execution part. • The declaration part declares all the variables used in the executable part. • There is at least one statement in the executable part. • These two parts can appear between the opening and closing braces. The program execution begins at the opening braces and ends at the closing braces. The closing brace of the function section is the logical end of the program. • All statements in the declaration and executable parts end with a semicolon. • The sub program section contains all the user defined functions that are called in the main () function. User defined functions are generally placed immediately after the main function. . PREPARED BY : Mansi Tyagi ..
13. 13. Subject: C and Data Structures Simple ‘C’ Program: /*Simple C Program */ main() { /*prints the string */ printf(“welcome to C worldn”); } • The first and fourth lines are commented lines. These are used in a program to enhance its readability and understanding .the line beginning with * and ending with* are known as comment lines. Comment lines are not executable statements and anything between *and *is ignored by the compiler. These comment lines can be inserted wherever we want, it cannot be nested i.e. cannot have comments inside comments. • The second line informs the system that the name of the program is main() and the execution begins at this line. The main () is a special function by the C system to tell the computer where the program starts. Every program must have exactly one main function. If we use more than one main function cannot know where the program begins. • The opening brace “{“ in the third line marks the beginning of the function main and the closing brace”}” in the last line indicates the end of the function . the statements between these two braces • The function body contains two statements, one of them is printf line is an executable statement. It is a predefined standard C function. The printf function to be printed out everything which appears in between quotations marks, here the output will be ”welcome to C world”. PREPARED BY : Mansi Tyagi ..
14. 14. Subject: C and Data Structures C Tokens The smallest individual units are called tokens. C programs are written using these tokens and the syntax of the language. The C has six types of tokens as shown below: 1. key word 2. identifiers 3. constants 4. operators 5. strings Character set: The characters that can be used to form the words, numbers and expressions depend upon the computer on which the program is run. The characters in C are grouped into four categories. 1. letters 2. digits 3. special characters 4. white spaces With these characters are combined to form data types, constants, variables and key words PREPARED BY : Mansi Tyagi ..
15. 15. Subject: C and Data Structures 1) Key words and identifiers: In ‘C’ every word is classified into either a key word or an identifier. All key word have fixed meaning cannot be changed. Keywords serve as a basic building block for program statements. All the keywords must be written in lower case. Keywords are the tokens used in C program which have predefined meaning and these meanings cannot be changed by the programmer. There are 32 keywords. They are also called as Reserved words. We cannot use them for any other purpose. Standard key words: auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for Signed void default goto sizeof volatile do if static while 2) Identifiers: Identifiers refer to the names of the variable, function and arrays. These are user defined names and consists of sequence of letters and digits. Rules for giving name to an identifier: 1. Identifiers can consist of letters and digits, must begin with in the alphabets or underscore, should not contain white space. 2. Both upper case and lower case are permitted although an upper is not equal to the corresponding lower case letter. 3. It cannot be a keyword. 4. An identifier can be of any length while most compilers of ‘C’ recognize only the first eight characters. PREPARED BY : Mansi Tyagi ..
16. 16. Subject: C and Data Structures 3) Constants and variables: The alphabets, numbers and special symbols are properly combines to form a constants and variables. Let us see what are constants and variables in C. Constants: Constants are fixed values that do not change during the execution of program. Several types of constants are: Constants Numeric Character Integer Float single character constant String constant Octal Hexadecimal Decimal For example in the equations 5x+2y=45 since 5, 2 and 45 cannot change , these are called constants, where as the quantity X&Y can vary or change hence these are called variables . Numeric constants: i) Integer constants: It refers to a sequence of digits, it has to fallow the below rules: 1. Integer constants must have at least one digit 2. It must not have a decimal point 3. It could be either positive or negative 4. If no sign precedes an integer constant it is assumed to be positive 5. No commas, blank space are allowed. 6. The allowable range for integer constants is -32768 to +32767 (16-bit machine) PREPARED BY : Mansi Tyagi ..
17. 17. Subject: C and Data Structures integer constants can be specified in decimal, octal, or hexa decimal notation. i) A decimal integer constant: It consists of sequence of one or more decimal digit 0 through 9 preceded by an optional – (or) + sign.The first digit of the sequence cannot be 0 unless the decimal integer constant is 0. Ex: 0 276 3412 31467 -7123 Note: Embedded spaces, commas, and non-digit characters are not permitted between digits. Ex: 12 727 23,879 are illegal numbers. \$1772 ii) An Octal Integer constant: It consists of any combination of digits from the set 0 through 7,with a leading 0. Ex: 012 07134 07777 iii) A hexa Decimal integer constants: It consists of the digit 0, followed by one of the letter x (or) X, followed by a sequence of one more hexadecimal digits 0 through 9 or letter a through f (or) A through F represent the numbers 10 through 15. Ex: 0X1F Note: we rarely use octal and hexa decimal numbers in programming. Real Constant: A real constant are sequence of digits with a decimal point(fractional part) like 45.382.Such numbers are called real(or floating point) constants. Rules for constructing Real Constants: 1. A Real constant must have least one digit. 2. It must have a decimal point. 3. It could be either positive or negative. 4. Default sign is positive. PREPARED BY : Mansi Tyagi ..
18. 18. Subject: C and Data Structures 5. No commons, black space are not allowed. Ex: 1.0 1. 0.712 34.576 -7.123 These numbers are shown in decimal notation, having a whole number fallowed by a decimal point. It is possible to omit digits before the decimal point or digits after the decimal point. Ex: 215. .39 -.92 +5. are valid real numbers. The real numbers may also be expressed in exponential (or, scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation.(e2 means multiply by 10 The general form: • The mantissa is either a real number expressed in decimal notation or an integer. • The exponent is an integer number with an optional + or – sign. • The letter e separating the mantissa and the exponent can be written in either lowercase or uppercase The scientific notation is often used to express numbers that are either very small or very large. Ex: 7500000000 may be written as 7.5e9 or 75e8. Similarly, -0.000000368 is equivalent to -3.68E-7. (Coefficient) e (integer) = (coefficient) * 10(integer) PREPARED BY : Mansi Tyagi .. mantissa e exponent
19. 19. Subject: C and Data Structures Character constant: Single character constants: Rules for constructing character constants: 1. A character constant is a single alphabet, a single digit or a single special symbol enclosed with in a pair of single inverted commas. Both the inverted commas should point to the left. For example ‘A’ is not valid character constant where as ‘A’ is valid. 2. The maximum length of a character constant can be one character constant. 3. character constants have integer values known as ASCII values. 4. The valid range of a character constant -128 to127. it appears surprising that the character constant should have a numeric range. Character and integer constant are often used interchangeably. For example ‘A’ and 65 are one and the something, since when we say ‘A’ it is replaced by ASCII value, which is 65. Example; ‘0’ ‘A’ ‘F’ ‘Y’ String constant: A string constant is a sequence of characters enclosed with in a pair of double inverted commas. The characters may be letters, numbers, special characters and blank space …… Ex: ”hello” “1999” “5+4+6” “good bye” Backslash character constants: C supports some special backslash character constants that are used in output functions. Each one of them represents one character, although they consist of two characters. These character combinations are known as escape sequences. Constant Meaning ‘a’ ‘b’ ‘n’ ‘’ ‘” ‘v’ Alert(bell) backspace new line back slash double quotation PREPARED BY : Mansi Tyagi ..
20. 20. Subject: C and Data Structures vertical tab etc… Variables: A variable is a data name which can be used to store a data value and a variable may take different values at different times, during execution. For example, in the equation 5X+2Y = 45 since 5,2 and 45 cannot change, these are called constants, where as the quantities X &Y can vary or change hence these are called variables. Rules for constructing variable names: 1. A variable name is any combination of alphabets, digits and the underscore character. ANSI standard recognizes a length of 31 characters. However, the length should not be normally more than 8 characters, since only the first 8 characters are treated as significant by many compilers. 2. The first character in the variable name must be an alphabet. 3. No commas or blank spaces allowed. 4. No special symbol other than an underscore can be used Ex: bas_pay , net_salary , month etc. 5. Uppercase and lowercase are significant. That is, the variable Amount is not the same as amount or AMOUNT. 6. Variables name should not be a keyword. Data types: Each data type has predetermined memory requirement and an associated range of legal values. Every programming language has its own data types. Storage representations and machine instructions to handle constants differ from machine to machine. ANSI C supports four classes of data types. 1. primary (or fundamental) data types PREPARED BY : Mansi Tyagi ..
21. 21. Subject: C and Data Structures 2. user defined data types 3. derived data types 4. Empty data set. 1. Primary data types: All C compilers support four fundamental data types, namely integer(int), character(char),floating point(float), and double-precision point(double).various data types and their terminology used to describe them are given in below fig.,. Primary data types Integer floating point character Signed unsigned float double long double singed unsigned int short int long int int short int long int Integers: C provides three different types of integers they are int, short int and long int. the difference between these three integers is the number of bytes. The variables of these types occupy and subsequently the range of values. A short int occupies 2 bytes, an int occupies 2 bytes and the long int occupies 4 bytes. Type Bytes required Range Short int 2 -32768 to 32767 (-215 to 215 - 1) int 2 -32768 to 32767 (-215 to 215 - 1) long int 4 -2147483848 to 2147483847 unsigned short int 2 0 to 65535 unsigned int 2 0 to 65535 PREPARED BY : Mansi Tyagi ..
22. 22. Subject: C and Data Structures unsigned long int 4 0 to 4294967295 Float: Like integers floats are divided into three types. They are float, double and long double. The difference between these three floats are the number of bytes, the variable of these types occupy and subsequently the range of values. A float occupies 4 bytes, a double occupies 8 bytes and the long double occupies 10 bytes. Type Description Size Range Float Single precession 4 3.4E-38 to 3.4E+38 Double Double precession 8 1.7E-308 to 1.7E+308 Long double Extended precession 10 3.4E-4932 to 3.4E+4932 Characters: A char is a data type which can store an element of machine character set. A single character can be defined as a character (char) type data. Characters are usually stored in 8 bits (1 byte) of internal storage. The character set is usually the ASCII. These are two types, they are signed and unsigned characters. The differences between these two types are the range of values. Both will occupy one byte. Type Bytes required Range Signed char 1 -128 to 127 Unsigned char 1 0 to 255 Declaration of variables: This instruction is used to declare the type of variable used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is usually written at the beginning of the C program. Syntax: Data_type var1,var2 … var n; Ex: int I, count; Float price, salary; Char c; PREPARED BY : Mansi Tyagi ..
23. 23. Subject: C and Data Structures Scope of variables: scope of variables implies to the availability with in a program. Variables have two types of scopes: local and global. A variable with a global scope is accessible to all statements in a program but the one with local scope in restricted to be accessed by only certain selected statements in the program, in which it is defined. Global variables are declared outside all functions where as local variables are defined inside a function. User-defined data type: The users can define an identifier that represent an existing data type by a feature known as “type definition”. The user defined data type identifier can later be used to declare variables. General form: where type refers to an existing data type and identifier refers to the new name given to the data type. Ex: typedef int Sno; typedef float salary; Here Sno symbolizes int and salary symbolizes float. These can be used to declare variables as follows. Sno c1,c2; salary e1,e2; Note: The main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program. PREPARED BY : Mansi Tyagi .. typedef type identifier;
24. 24. Subject: C and Data Structures Another user defined data type is enumerated data type provided by ANSI . General form: enum identifier {value 1, value 2, ……, value n}; The identifier is a user defined enumerated data type which can be used to declare variables that can have one of the values enclosed within the braces. After that we can declare variables to be of this new type. enum identifier v1, v2, ….vn; the enumerated variables v1, v2, …..vn can only have one of the value 1, value 2, …… value n. Ex 1: enum month {january, february, ….december}; enum month month_st, month_end; (or) enum month {january, february, …., December} month_st, month_end; Here the declaration and definition of enumerated variables can be combined in one statement. Ex 2: enum day{Monday,Tuesday……Sunday}; enum day week_st,week_end; week_st=Monday; week_end=Friday; if(week_st==Tuesday) week_end=Saturday; The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants. That is, the enumeration constant Monday is assigned with 0, Tuesday is assigned with 1 and so on. However, the automatic assignments can be overridden by assigning values explicitly to the enumeration constants. PREPARED BY : Mansi Tyagi ..
25. 25. Subject: C and Data Structures For example, enum day{Monday=1,Tuesday, ……., Saturday}; here, the constant Monday is assigned the value 1.The remaining constants are assigned values that increases successively by 1. Derived data types There are some derived data types which are supported by C such as arrays, functions, structures, and pointers. Empty data set It is also known as void data types. It indicates that no other data types has been used with the given identifier. PREPARED BY : Mansi Tyagi ..