Sei sulla pagina 1di 30

Module 5

PROGRAMMING

APR - 2010 / BLY

~ ~ ~ INDEX ~ ~ ~
TOPIC PROGRAM DEVELOPMENT LIFE CYCLE ........... LANGUAGE ......... FLOW CHART ......... PSEUDOCODE ....... ALGORITHM ....... INTRODUCTION of C ......... KEYWORDS, DATA TYPES VARIABLES ......... HEADER FILES ....... OPERATORS ....... CONDITIONAL STATEMENTS ...... LOOP ........... ARRAY .......... STRING ............ FUNCTION ...... STRUCTURE ........... UNION ......... FILE HANDLING ........ PAGE 02~ 04 04 05 ~ 06 06 ~ 12 12 ~ 15 15 15 ~ 16 16 18 19 ~ 20 20 ~ 22 22 ~ 23 23 ~ 24 24 ~ 25 25 ~ 27 27 ~ 28 28 ~ 29 30

............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ............... ...............

Note: If you find any typing or printing error/s, inform immediately to your branch office.

ADCPM

TECHNIQUES & C

Page - 1

Module 5

PROGRAMMING

APR - 2010 / BLY

PROGRAM DEVELOPMENT LIFE CYCLE Introduction: In the present time, computers are being used different sectors like industry, colleges, reservation, and every section of life. When you work on a computer then you provide some details to the computer that is processed by the computer and a particular output is received. When you want to solve a problem, then you provide a set of instructions to the computer, which is used to complete the task. These set of instructions are called program. When you want to complete any work in computer, you require some program. Programming: Programming can be defined as the development of a program, which directs a computer system to generate the desired results. Programming is a problem solving activity. Computer Programming is the procedure of arrangement a sequence of steps for a computer to follow. Steps in Programming Process: We know that lot of efforts are made in terms of time, money and manpower for the development of useful program. The term useful program means that a program should be effective as well as efficient. A program that does the desired work and achieves the goal is known to be effective. The program does the same work at a faster rate and useless memory space, is known to be an efficient program. A programmer can write an efficient but complex program by using clever techniques to solve a problem. The overall programming process can be subdivided into a number of tasks as follow the steps, which are listed below: 1. Analyze the program 2. Write an algorithm for the problem 3. Test the algorithm and if required, repeat steps (1) and (2) 4. Transform the algorithm into a high-level language program. 5. Test the program. 6. Repeat steps (1) to (5) until a useful program is produced. In the programming process, generally, tasks (1), (2) and (3) are done by a system analyst and (4) and (5) by a programmer. The task (6) is shared between the system analyst and the programmer. Structured Programming Techniques: A programmer can write an efficient but complex program by using clever techniques to solve a problem. Such a program is difficult to understand for the purpose of program maintenance and for this reason; it is very difficult to bring the necessary modification in it at a later stage. The software professional have been trying to find method of creating correct programs, which can be easily maintained and modified. As a result, a methodical approach in the form of structured or modular programming came into picture. In structured programming, the tasks are performed with the help of top down design. Where in a problem is divided into sub-problems. Then each subADCPM

TECHNIQUES & C

Page - 2

Module 5

PROGRAMMING

APR - 2010 / BLY

problem is further divided into sub-sub-problems and so on. This process continues until you reach to a stage when each sub-problem can be easily handled. Thus, a complex program can be built up in a systematic fashion by a series of steps. A sub problem or sub division is also known as a module. A module in itself is a subprogram and can be referenced by its name. A top down structure can be looked upon as tree structure.

Module 1

Module 2 Module 5 Module 6

Module 3

Module 4 Module 7

It is clear that the characteristics of a well-structured modular program are that it consists of a number of modules. Each module is self-contained and performs a single task and can be tested and debugged independently. Computer Programming: Programming is a sequence of predefined steps required for solving a problem with the help of computer. Criteria for a Good Program: Program: A computer is a composite machine, which works according to the input instructions provided to it. The set of instructions that are provided to a computer is known as a program and the development of a program is known as programming. A program can be evaluated on many accounts such as efficiency, flexibility, reliability, Portability etc. 1. Efficiency: Efficiency can be of three types: Programmer effort, machine time and memory space. The programmer efficiency can be obtained by using a high-level language. However, a program written in assembly language is comparatively compact and takes less machine time, and memory space. Therefore, a compromise has to be maintained b/w the programmers effort and execution time. 2. Flexibility: If a program can be used for many purposes then it is known as flexible. CAP (Computer Aided Design) packages can be used for variety of purpose such as Engineering, drafting, architectural design, printed circuit board layout, design etc. These packages can also be use to illustrate graphs and reports. 3. Reliability: It is the ability of a program to perform its function correctly in spite of temporary or permanent change in the characteristics of computer system components. A program having this ability is known as reliable program. 4. Portability: Generally, it is desired that a program written on a certain type of computer system should also run on another type of computer system. Portability is a measure of the case with which a program can be transferred from one environment to another. A program written in
ADCPM

TECHNIQUES & C

Page - 3

Module 5

PROGRAMMING

APR - 2010 / BLY

high-level language is bound to be more portable than an assembly language program (UNIX). 5. Robustness: It is the ability of a program to provide meaningful output for all inputs (correct or incorrect). For correct input, it will give the desired output. For incorrect or erroneous input, the robust program maintains control and gives suitable messages with no run time errors. The robust program keeps on executing for all inputs. LANGUAGE A language is required to communicate with each other. There are several languages like Hindi, English, Chinese, Arabic, etc. used for communication with each other in our daily life. Similarly, to communicate with a Computer a language is required, which is called computer (programming) language. A programming language is a set of words, symbols and codes that enables a programmer to communicate to the computer with a suitable algorithm. These languages are categories in three ways: 1. Machine Level Language: In this language the computer, accept the data (input) in the form of binary numbers, that is 0 and 1. Therefore, it is very difficult to learn and remember these instructions or coding. Therefore assembly languages were developed. 2. Assembly Language: This language is easy in the comprehension of machine language. In this language, a program was created by using the symbol and codes. The manufacturer of computer provides software, along with the hardware, to convert the assembly language into the machine language. However still there is a problem with this language, as remembering of the hardware requirement of the computer. To avoid this problem high-level language was developed. 3. High Level Language: It is the latest language, which is very user friendly and structure language. Some of the high-level languages are C, C++, C#, Java, Visual Basic etc. There is no need to learn and remember codes, symbols, and hardware requirement in developing of the program (software). Advantages of High Level Language: 1. In this language, no need to remember about the hardware parameters. 2. In this language, you can use common English words, which are easy to learn. 3. This language is easier to compile and run the program. Interpreter: An interpreter converts a high-level language into machine level language and simultaneously executes the converted line. An interpreter must also represent in the memory along with the program for its execution. If an error occurs in any line, the line is displayed and interpreter does not proceed unless the error is removed. Compiler: When you compile a program, compiler checks the whole program at once and after that, if any error occurs in the program, it will display all the errors with line number. If no error occurs in the program, compiler will show a message, as: program successfully compiled.
ADCPM

TECHNIQUES & C

Page - 4

Module 5

PROGRAMMING

APR - 2010 / BLY

FLOW CHART Flow chart is a pictorial representation that uses symbols to show the operations and decisions to be followed by a computer in solving a problem. In simple words, you can say that the flow chart is like a road map, which provides a detailed description of the flow of data in the processing. It shows the main stages of a problem, and how they are related? Flow chart is effective and inexpensive analytical tool. With the help of a flow chart programmer can quickly show a series of alternative approach to a problem. Then a group of designer can examine the flow-chart and determine, which solution best suitable for their need. Flow Chart Symbol: The various symbols of a flow chart are 1. Terminal Symbol: START and STOP It is used to indicate a point at which the flow-chart beings or ends. It is an expected procedure to insert the words START or STOP within the terminal symbol.

2. Input and Output Symbol: It is used to represent the logical positioning


of input and output operations. The input operation means, the entry of computer data and output operation means, the display output information.

3. Processing Symbol: This symbol represents some operations


(processing) of the data.

4. Decision Symbol: This Symbol represents logical operations showing a


decision point in a program. The two main components of a decision symbols are a. A question that defines the logical operation. b. The result of the decision (Yes / No).

5. Annotation Symbol: Programmer often wants to write remarks or


comments in a flow chart, which do not affect the processing but clearly a particular point in the flow chart.

6. Flow Symbol: A flow symbol is an arrow that shows the flow of program
logic in a flow chart.
ADCPM

TECHNIQUES & C

Page - 5

Module 5

PROGRAMMING

APR - 2010 / BLY

7. Connector Symbol: it is used to indicate a Junction in a flow chart,


which joins from a part of the flow chart on the same or another page.

Some other pre define useful symbols are a. Predefined Process:

b. Printed Output:

c. Off Page Connector:

Rules for Drawing Flowcharts While drawing a flowchart the following rules should be followed: 1. Use conventional flowchart symbols as shown in Figure. Each symbol should have one exit point except the decision symbol. As far as possible, each symbol should also have one entry point and in the case of decision symbol, it is necessary. 2. The flow of control in the problem can be shown with the help of arrows. However, the flow lines should not cross each other. 3. The processing logic within the flowchart should flow from top to bottom and from left to right. 4. The instructions written within the various flowchart symbols should be independent, according to programming languages. 5. The flow lines coming out of the decision symbol should be properly labeled. 6. If the flowchart becomes large and complex (on same page) then make use of ordinary connector symbols to avoid crossing of flow lines. 7. Every flow chart must have the start and End points. PSEUDOCODE Pseudocode is a sequence of steps used for solving a problem, which is written in simple keywords. It is always better to write a pseudocode before writing a program, which will finish half of your job. Once a pseudocode is ready, it is very easy to generate a program. As the only thing remains is, the conversion of pseudocode to a particular programming language. As C, C++, Java, COBOL, etc. Pseudocode also helps to develop and understand the logic of a program. The following table describes the keyword used in pseudocode.
ADCPM

TECHNIQUES & C

Page - 6

Module 5

PROGRAMMING

APR - 2010 / BLY

Description This keyword indicates the beginning of pseudocode. Starts a set of Instructions. End This keyword indicates the end of pseudocode. Specifies the end of a program. Accept This keyword is used to assign the value in a variable. It is used to accept data from the user. Display This keyword is used to display the output of the program. It is used to display output. If-else This keyword is used to check the conditions. While / for This keyword is used for looping or repletion of jobs. Variables and Constants Data can be categorized in two ways (1) constant Data and (2) Variable. 1. Constant Data: It is the data, which remains unchanged throughout the program. 2. Variable Data: It is the data, which changes its value at run time. As variable cannot be referred to, by is value (it keeps on changing), it has to be given a name for referring. This name is always a single word. Variable name is a name given to memory location whereyou are storing the value. Its value can be changed any time as and when required. For example: Number = 8 Here the word Number is the variable name referring the value 8, which is constant. Data Types The type of data to be stored in a variable is called data type. These are of two types: 1. Numeric 2. Character Numeric: This variable can contain only numbers and decimal values that can be used in arithmetic operations. As 8, 5.28, etc. Character: This variable can contain character, number or special character. Declaring Variable When a variable is used, it is necessary to declare it before using in the program, consider the following initialization: //Variable declaration Numeric N1

Keyword Begin

Store 0 to N1
The variable N is initialized to 0

N1 = 0
ADCPM

TECHNIQUES & C

Page - 7

Module 5

PROGRAMMING

APR - 2010 / BLY

PSEUDOCODE 1.1 Here is the pseudocode and corresponding flow chart to accept two numbers to display the result of their addition. Begin numeric N1, N2, Sum accept N1 accept N2 Sum = N1 + N2 display Sum end // Variable declaration Start Numeric N1, N2, Sum Accept N1 Accept N2 Sum = N1 + N2 Display Sum Stop OPERATORS Operators are the tools used for predefined operations. The operators can be: 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators Arithmetic Operators They are used to perform arithmetic calculations. The symbols used are: (+, -, *, /, %) PSEDOCODE 1.2 The following pseudocode and corresponding flowchart will take two numbers and display the remainder of them. Relational Operator They are used to test the relationship between two variables. The Relational operators are (=, >, <, =, >=, <=) these operators are good tools to compare the values of two operands. It returns the response as TRUE or FALSE. As 0 > 0 // Returns False. Logical Operators They are used to combine expressions containing relational operators. There are three logical operators
ADCPM

TECHNIQUES & C

Page - 8

Module 5

PROGRAMMING

APR - 2010 / BLY

1. AND 2. OR 3. NOT
Sometimes,you require performing an operation on the basis of more than one condition. So using logical operator you can club more than one condition together. AND Operator: In the case of AND operator both the conditions should be satisfied e.g. No1 > 10 and No1 < 20. In this case, the value of no I should be in between 10 and 20. OR Operator: It is used when any one of the condition is to be satisfied. Dept = Sales or Dept = Act NOT Operator: It is evaluated to true if the condition is not met. begin numeric N1,N2,rem accept N1 accept N2 rem = N1 % N2 display rem End Start Numeric N1, N2, rem Accept N1 Accept N2 rem = N1 % N2 Display rem

Stop Conditional Statement There are many situations where you want to take a decision and execute the statement accordingly. To denote conditional statement if conditional construct is used with pseudocode and decision making symbol is used with flow charts. Conditional statement is required when decision can be changed based on any condition. Example: If you want to print, Pass for marks greater than 33 & Fail for otherwise. In such kind of situation if condition will be used. if.. else STATEMENT if <condition> begin [Statement to be executed if condition is true]
ADCPM

TECHNIQUES & C

Page - 9

Module 5

PROGRAMMING

APR - 2010 / BLY

end else begin [Statement to be executed if condition is false] end endif PSEUDOCODE 1.3 The following pseudocode and corresponding flow chart will print the bigger of two numbers using if construct. begin numeric X. Y accept X accept Y if X>Y begin display X end else begin display Y end endif end Start Numeric X, Y Accept X Accept Y

If X>Y Yes Display X

No

Display Y

Stop

Here is X is greater than Y then X will be printed otherwise Y will be printed. In a decision box, only one decision can be taken, but there can be any number of decision boxes in a single flow chart. Iteration (Loop) While executing, the same statement again and again you can use iteration method instead of repeating the code. Iteration methods are also called loops. There are two types of loop: For Statement (If the number of repetition are known in advance). While Statement (If the number of repetition is not known in advance). Using While Loop The repeated portion of a flow chart is called a loop.
ADCPM

TECHNIQUES & C

Page - 10

Module 5

PROGRAMMING

APR - 2010 / BLY

PSEUDOCODE 1.4 The following pseudocode and corresponding flow chart, prints the sum of first ten natural numbers using while loop. begin numeric Sum, N N=1 while(N <= 10) begin Sum = Sum + N N=N+1 end end while display Sum end Start Numeric Sum, N Sum = 0, N = 1 A Sum = Sum + N N=N+1

If N >10 Yes

No

Display Sum

Stop Loop is performed until condition is satisfied. Here the step 4 and 5 are repeated until the variable Num is less than 10. Thus, the variable Num works as a counter. Each time the variable Num is added to the variable sum. The value of Num is increased by 1. Using For Loop From the Flowchart discussed above, it is clear that a loop has: Action(s): N=N+1 Sum = Sum + N Increment counter: N=N+1 Here Num is serving both the function of Action and Counter both. When you know the number of times, the loop is to be continued you can use for loop. Let us take another example to simplify the loop. PSEUDOCODE 1.5 We will accept the Name from the user, which has to be printed 5 times. The pseudocode and flow chart will be as follows:
ADCPM

TECHNIQUES & C

Page - 11

Module 5

PROGRAMMING

APR - 2010 / BLY

Begin char name numeric a a=0 accept name For a = 0 to 5, a = a + 1 begin display name end endfor end

Start Char name Numeric a a=0 Accept name

Display name a=a+1

Yes

If a<5 No Stop

ALGORITHM The set of rules that define how a particular problem can be solved, Logical sequence of steps, which gives solution of a problem, is known as algorithm. The most common approach to define a problem is to summarize its algorithm in English as clearly as possible. An algorithm written in a computer language is called a program. The set of rules that define how a particular problem can be solved in finite sequence of steps is known, as algorithm. The most common approach to define a problem is to summarize its algorithm in English as clearly as possible. An algorithm written in a computer language is called as a program. It becomes programmers duty to precisely define his problem in the form of algorithm i.e. unambiguous steps written in simple English. The desirable features of an algorithm are: Characteristic of Algorithm: There are five basic characteristics. 1. Input: This part of algorithm reads the data by accepting the input of given problem. 2. Process: This part of algorithm does the required computation with the
ADCPM

TECHNIQUES & C

Page - 12

Module 5

PROGRAMMING

APR - 2010 / BLY

help of simple steps.

3. Finiteness: The algorithm must come to an end after a finite number of


steps.

4. Effectiveness: Every step of the algorithm must be accurate and


precise. It should also be executable with in a definite period of time on the target machine. 5. Output: It must produce the desired output as a result. Steps for Algorithm: 1. Each step of the algorithm should be simple. 2. It should be unambiguous in the sense that the logic should be crisp and clear. 3. It should be effective i.e. it must lead to a unique solution of the problem. 4. It must end in a finite number of steps. 5. It should be as efficient as possible. How to Develop an Algorithm In order to develop an algorithm, the problem has to be properly analyzed. The programmer has to understand the problem and come out with a method or logic that can solve the problem. The logic must be simple and adaptable on a computer. The following steps can be suggested for developing an algorithm: 1. Understand the problem. 2. Identify the output of the problem. 3. Identify the inputs required by the problem to achieve the desired output. 4. Design a logic or process that will produce the required output from the given inputs. 5. Test the algorithm for a given set of input data. 6. Repeat steps 1 to 5 until the algorithm produces the desired results. Example 1: Given two memory locations, X and Y, exchange the values assigned to them. Algorithm exchange Step 1. Read the values of X and Y. 2. Save the initial value X in TEMP. 3. Move the initial value of Y into X. 4. Move TEMP. into Y. 5. Display the exchange values of X and Y. 6. Stop Example: Write an algorithm that computes the area of a triangle. Algorithm Step 1. Read base, height; 2. area = 0.5 * base* height 3. Print area 4. Stop Example 1: Write an algorithm that prints bigger of any given two unique numbers.
ADCPM

TECHNIQUES & C

Page - 13

Module 5

PROGRAMMING

APR - 2010 / BLY

Algorithm Step 1. Read Num 1 and Num 2 2. if(Num 1 > Num 2) a. print Num 1 is bigger. b. else print Num 2 is bigger. 3. Stop. Example 2: Write an algorithm that prints biggest of given three unique numbers. Step 1. Read Num 1, Num 2, Num3 2. if(Num 1 > Num 2) a. if(Num 1 > Num 3) Print Num 1 is biggest b. else print Num 3 is biggest 3. else Example 3: Write an algorithm that finds out the largest number from a list of given numbers. Algorithm Step 1. Prompt Enter the size of the list 2. Read Num 3. Prompt Enter a number 4. Read Num. 5. Count =1; 6. Largest = Num; 7. Prompt Enter a number 8. Read Num; 9. Count = Count +1 10. If(Num > Largest) Largest = num; 11. If(Count < N) repeat steps 7 to 10 12. Prompt The largest number is. 13. Print Largest 14. Stop. Example 4: Write an algorithm that reads a list of 50 integer values and prints the total of the list. Algorithm Step 1. SUM = 0; initialize Accumulator 2. C = 0; initialize Counter 3. Read a number in Val; 4. C = C+1; increment Counter 5. SUM = SUM +Val; Accumulate number in SUM 6. Compare C and 50; 7. if C is less than 50 repeat steps 3 to 6; 8. Print SUM 9. STOP
ADCPM

TECHNIQUES & C

Page - 14

Module 5

PROGRAMMING

APR - 2010 / BLY

Example 6: A set of N numbers is given. Write an algorithm to print how many of these numbers are (-) ve, zero, and (+) ve numbers. Algorithm Step 1. Read N; 2. If N <= 0 then perform step 14; 3. POSC = 0; 4. NEGC = 0; 5. ZEROC = 0; 6. C = 0; 7. Read Val; read a value from set 8. C = C+1; increment count 9. If Val < 0 then NEGC = NEGC + 1; Perform step 12; 10. If Val = 0 then ZEROC = ZEROC +1; Perform step12; 11. POSC = POSC +1 12. If C < N then repeat steps 7 to 11 13. Print POSC, NEGC, ZEROC 14. STOP Advantages of the Algorithms 1. It is simple to understand step by solution of the problem. 2. It is easy to debug i.e. errors can be easily pointed out. 3. It is independent of programming languages. 4. It is compatible to computers in the sense that each step of algorithm can be easily coded into its equivalent in high-level language. INTRODUCTION of C C is a high-level structured programming language, which is developed by the Dennis Ritchie in 1972 at Bells Laboratory. It is a successor of B (1970), which was the combination of Algol68 (1960) CPL (1963) and BCPL (1967) Basic Combined Programming Language. C is a general purpose programming language having 27 keywords. This language is used for programming and developing softwares, games and other utilities. It contains integers, floating point, fractional values and characters (letters, digits & punctuations) as data types. It has control structured statements if, if-else, switch for decision and (while, for, do-while) for looping. Character Used in C: Alphabets : a to z : A to Z Numbers : 0 to 9 Special Symbol : . , ; : ! ? < > + - * / % # & = ^ ~ | \ _ ( ) [ ] { } Parenthesis :() Square bracket : [ ] Braces :{} KEYWORDS Keywords are the words that convey a special meaning to the language compiler. These are reserved for special purpose and must not be used as normal
ADCPM

TECHNIQUES & C

Page - 15

Module 5

PROGRAMMING

APR - 2010 / BLY

identifiers names. The original C contains the following keywords: auto default float long static unsigned break do for registers struct while case double goto return switch char else if short typeof continue extern int sizeof union

Data Types in C Data type is the category, which represent type of the value stores in the variable, which is declared in the program. short integer float double value accept char character or string (sentence or word) string long int - %d float - %f char - %c string - %s Basic Data char Data Type with Type Qualifiers Size (Bytes) 1 1 2 2 1 1 4 4 4 8 10 Range -128 to 127 0 to 255 -32768 to32767 0 to 65535 -128 to127 0 to 255 -2147483648 to 2147483647 0 to 4294967295 3.4e-38 to3.4e+38 1.7e-308 to 1.7e+308 3.4e-4932 to 1.1e+4932

char or signed char unsigned char int int or signed int unfloatsigned int short int / signed short int unsigned short int long int / signed long int undsignd long int float float double double long double

VARIABLES Variables represent named storage locations, whose values can be manipulated during program run, for instance, to store name of a student and marks of a student during program run, you require storage locations that too named so that these can be distinguished easily. Variables, called as symbolic variables, serve
ADCPM

TECHNIQUES & C

Page - 16

Module 5

PROGRAMMING

APR - 2010 / BLY

the purpose. The variables are called symbolic variables because these are named. For instance, the following statement declares a variable b of the data type int (integer): int b; There are two values associated with a symbolic variable: 1. It is the data value, stored at some location in memory. This is sometimes referred to as a variables rvalue. 2. It is the location value, which is the address in memory at which its data value is stored. This is sometimes referred to as a variables lvalue. Memory Address Data value of variable Variables name 1001 12 A 1002 1003 14 B 1004 15 C 1005

rvalue of A=12 and lvalue of A=1001 Declaration of variables: The declaration of a variable generally takes: Syntax: type varname; Where type is any data type of C and varname is the name of variable. Initialization of variables: Type varname=value; Example: int a=100; Literals: Literals are data items that never change their value during a program run. C allows several kinds of literals: Integer Constant: Integer constants are whole numbers without any fractional part. The method of writing integer constants has been specified in the following rules. 1. Decimal 2. Octal 3. Hexadecimal Character Constant: A character constant is one character enclosed in single quotes, as in a. Floating Constant: Floating constants are also called real constants. Real constants are numbers having fractional parts. Example: 2.0,1.75. String Literal: Multiple Characters constants are treated as string literals. A string literal is a sequence of characters surrounded by double quotes. Example: abc, my name is raj. Pre-processor: The first line in a program starts with # (hash) sign, followed by include statement and a file name with h (header) extension enclosed within angle bracket (< .h>). This statement is called a pre-processor directive, which instructs the compiler to insert another file into the source file. Each preprocessor is an instruction to the compiler. #include: This pre-processor is used to insert another file in a program. #define: This pre-processor is used to create constant in a program.
ADCPM

TECHNIQUES & C

Page - 17

Module 5

PROGRAMMING

APR - 2010 / BLY

C library contains many files. Some of these need to be linked with the source program during compilation. This is done by the #include<.. .h> statement. HEADER FILES The computer language C contains some statement. It has no built in function to perform input-output, mathematical, string handling and many such other operations. For each of their operations, some built in functions are kept in files, contained in a library. In order to use these functions which are stored in the library, it is necessary to call the required ones for inclusion in the program. The language has no statements which alone can perform those operations. These built in functions which are to be included in the source program are called as Header Files. There are mainly three Header files are used in C. 1. <stdio.h>: Several definitions symbols and values are kept in this file. Using scanf and printf statements, input/output operations can be performed. The <stdio.h> is useful for console input /output operation as it has functions. a. scanf(): Input data can be entered into the computer from a standard input devices with the help of scanf() function. b. printf(): The output data can be return from the computer to you using standard output device with the help of the library function printf(). c. getchar(): A single character variable say x initially declared can be taken as by using getchar(x). char ch; scanf() ch =getchar(); printf() d. putchar(): This is single character output function available in stdio.h. When a value of a character is getchar() entered by using getchar(), that can be displayed by putchar() using putchar() function. For example: gets() char ch; puts() ch =getchar(); putchar(ch); e. gets(): This stdio.h function enable to take a multiple character input as a value for a previously declared character variable, with specific size. For example: char name [25]; gets(names); f. puts(): The character value of an initially declared character variable entered through gets() function, may be displayed on the screen by the puts function of the stdio.h file. For example: char name[25]; gets(names); puts(); 2. <conio.h>: In conio header file mainly two built in functions clrscr(); and getch(); are used. clrscr() function is used to clear the output screen and getch() function is used to hold the output screen until the any digit/character entered by the user. 3. <string.h>: It declares several strings and memory manipulation routines.
ADCPM

TECHNIQUES & C

Page - 18

Module 5

PROGRAMMING

APR - 2010 / BLY

4. <math.h>: The math.h file declares the prototypes of the mathematical and
mathematical error handler functions. For mathematical calculations and various conversions, routines are available in this <math.h> header file. Such as the following : Function pow(x,y) Description Returns the value of x y Raised to the power y i.e. x sqrt(x) Returns the positive Square root of X log(x) Returns natural logarithm of double log X (to the base e) cos(x) Returns consine of the angle double cos X is in radian measure. Example int pow(int3, int2) returns 2 the value 3 i.e. 9. sqrt(6.25) returns 2.5 log(2.2598) 0.815276313 cos(0.2) 0.980066577 returns Return

pow() sqrt() log() sin() cos()

MAIN FUNCTION The word main is very important, and must appear once in each C program. It must exist as the entry point. It is stand alone function, where the counter moves during starting of execution. If it is not present in a program, an error signal is given by the linker. The bracket () form a part of the main function. If this is missing then main may be taken as a variable by the compiler. Main function returns an integer to the operating system that is specified in the return statement. If no return value is specified, some compiler by default assumes a void return. When a void return is required, it is necessary to include return 0 as the last statement or declare main function as void main(). The two curly brackets, generally called braces, are used to define the limits of the program itself. First Program in C: #include<stdio.h> void main() { printf(welcome in C world); } OPERATORS An operator is a symbol or letter use to indicate a specific operation on the variables in a program. For example: In A+B The symbol + is an operator and two data items A and B are called operands. 1. Arithmetic Operators: + Addition Subtraction * Multiplication / Division % Module 2. Logical Operators:
ADCPM

TECHNIQUES & C

Page - 19

Module 5

PROGRAMMING

APR - 2010 / BLY

a. && (AND): If you want to check two or more condition at a time than
you can use && operator. Only if all given conditions are true, then the result will be true. If in all given conditions, any one condition is false than the result will be false. b. II (OR): This operator is used to check two or more condition at a time. When the given all conditions or any one condition is true the result will be true. c. ! (NOT): This operator negates or reverse the value of the expression follows by it. If the expression is true then it converts to false, and vice versa. 3. Relational Operators: > To compare if less than < To compare if greater than >= To compare if greater than or equal to <= To compare if less than or equal to == To compare equality != To compare if not equal to 4. Assignment Operators: = Set equal to += Add assignment operator -= Minus assignment operator *= Multiply assignment operator /= Divide assignment operator %= Module assignment operator 5. Conditional Operators: This operator is a Ternary operator. The conditional operator is allowed on the left side of the expression, it requires three operands. ?: Select Construct (Selective Execution Conditional Statement) : In this case, a selected statement of the program is executed on the basic of a test that is depending upon the state of a particular condition being true or false. In C, if statement is used for selective execution of a program segment. 1. The IF Statement: This statement helps us in the selection of one out of two alternative courses of action. Syntax: if(expression) { statement; } 2. The IF - Else Statement: In this case, you can use if else statement, if condition is true the statement under if condition will execute, otherwise the statement after the else statement will execute. Syntax: if(expression) { statement 1; }
ADCPM

TECHNIQUES & C

Page - 20

Module 5

PROGRAMMING

APR - 2010 / BLY

else { statement 2; } Nested IF Statement (IF - Else IF Statement); The statement sequence of if else may contain another if statement, therefore, if else statement can be nested within one another. Syntax: if(expression) { statement 1; } else if(expression) { statement 2; } else { statement 3; } if(expression) { if(expression) { statement; } else if(expression) { statement; } else { statement; }

or

Switch: If it is required in a program to select one of several different courses of action then the switch statement can be used. It is a multi-branch selection statement, which makes the control to jump to one of the several statements based on the value of an integer variable or expression. It begins with the keyword switch followed by a variable in parentheses which is the switching variable. The reserved word case is used to begin each case entered followed by the value of the variable, then a colon, and the statements to be executed. And the break statement will cause you to jump out of the switch. Once an entry point is found, statements will be executed until a break is found or until the program drops through the bottom of the switch braces. The various case values can be in any order and if a value is not found, the default portion of the switch will be executed. Syntax: switch(expression) { case constant 1: statement 1; break; case constant 2: statement 2; break; : : case constant n: statement n;
ADCPM

TECHNIQUES & C

Page - 21

Module 5

PROGRAMMING

APR - 2010 / BLY

break; default: statement; } LOOP Some problems require that a set of statement should be executed a number of times, each time changing the values of one or more variables so that every execution is different from the previous one. This kind of repetitive execution of a set of statements in a program is known a loop. There are three types of loop are 1. While Loop: It is the loop, in which first initialization the value and check the condition. If condition is true then the statement under while will be executed if condition is false than the loop pointer jump outside the loop and the statement which present after the loop will be executed. Syntax: initialization: while(conditional expression) { statement; : : increment/decrement; } Example: void main() { int I; I = 1; while(I <= 10) { printf(%d\n, l); I++; } getch(); } 2. Do While loop: Do While loop is the exit control loop. In this loop first initialization the value and then execute the statement under do and then increment and decrement condition apply after checking the condition. This loop begins with the reserved word do, followed by a compound statement in braces, then the reserved word while, and finally an expression in parentheses. The statements in the braces are executed repeatedly as long as the expression in parentheses is true. When the expression in parentheses becomes false, execution is terminated, and control passes to the following statement. Syntax:
ADCPM

TECHNIQUES & C

Page - 22

Module 5

PROGRAMMING

APR - 2010 / BLY

initialization; do { statement; updation; (inc/dec) } while(condition expression); Difference between While and Do While Loop a. While loop is an entry control loop and do while is exit control loop. b. While Loop: In while loop if condition is false than the statement under while will not execute. c. Do While Loop: In do while loop, if condition checked firstly, while the statement under do at least one time will be execute. 3. For Loop: Forloop is the simplest loop. The For loop consists of the reserved word for followed by a rather large expression in parentheses. This expression is really composed of three fields separated by semi-colons. In this loop, initialization, conditional expression and updation, all are lying in a single line between parentheses. The first field is an initializing field. Any expressions in this field are executed prior to the first pass through the loop. Several initializing statements can be placed in this field, separated by commas. The second field is the test which is done at the beginning of each loop through the program. It can be any expression which will evaluate to a true or false. The expression contained in the third field is executed each time the loop is executed but it is not executed until after those statements in the main body of the loop are executed. Syntax: for(initialization; conditional expression; updation) { Statement; } Nesting of Loop: The loop is used under other loop is called nesting of loop. Syntax: for() { for() { } } ARRAY An Array is the collection of similar data element. It is used when required more than one values store in a single variable. Syntax: (one-D) <data type> <array name> [size];
ADCPM

TECHNIQUES & C

Page - 23

Module 5

PROGRAMMING

APR - 2010 / BLY

Example: int rollno [20]; In the above example int is defined data type and rollno is the name of array and 20 is the size of array integer type. Its lower limit start from 0 and upper limit is (n-1) or (size-1). We can define array 1 dimensional, 2 dimensional (2D), and multi dimensional. 1 D Array: It is a single row array, in which you can store similar data items. 1. Declaration 1 D Array int rollno [20]; 2. Initialization in Array for(i=0 ; i<n ; i++) { scanf(%d,&a[i]); } 3. Print the Output of the Array and Display Array: for(i=0 ; i<n ; i++) { printf(%d, a[i]); } 2 D Array: It is a 2 dimensional array, in which you can store the data in rows and columns. Syntax: <data type> <array name> [rows] [columns]; Example: int a [3] [3]; 1. Declaration of 2 D Array: int a [3] [3]; 2. Initialization of 2 D Array: for(i=0; i<3; i++) for(j=0; j<3; j++) scanf(%d,&a[i][j]); 3. Display of 2 D Array in Matrix form: for(i=0; i<3; i++) { for(j=0; j<3; j++) { printf(%d,a[i][j]); } printf(\n); } STRING A string is a sequence of character that is as a single data item. Any group of characters is defined between double quotation mark, is a string constant. Example: I am student . 1. Declaration: char <string name> [size]; Example: char name [20];
ADCPM

TECHNIQUES & C

Page - 24

Module 5

PROGRAMMING

APR - 2010 / BLY

2. Initialization: char name [10] = Ramnagar ; Reading String by using Scanf:Example: scanf (%s, name); The familiar input function scanf can be used with %s format specification to read in a string a character here a problem with the scanf it terminates its input on the 1-bit space it finds. Display the string: printf(%s, name); Used getchar and gets: A getchar read a single char but gets read a string without space. These functions are available in header file stdio.h. Input (1) char ch; ch =getchar(); (2) gets(name); String Handling Function:
1. 2. 3. 4. Function strcat() strcmp() strcpy() strlen() Action It can concatenate to string. Comparison to string. It copies one string over another. Find the length of string.

FUNCTION If a program divided into fictional part than each part may be separately coded and later combine into a single unit. These separately coded programs are called sub programs that are much easier to understand debug and test in C. Such sub programs are referred to as functions. In C function are divided into two parts;Library Function And User Define Function : Example: These are predefined function (library function): User Defined Function: In user define function; you need to establish three elements that are related to function. 1. Function Definition: Function definition is an independent program modal that is special written to implements the requirement of the function. 2. Function Call: Function call in order to use, you need to invoke it at a required place in the program this is known as function call the program that the function is referred to as the calling program or calling function. 3. Function Declaration: The calling program should declare any function that is to be used later in the program this is known as the function declaration and function prototype. Definition of Function: Function Definition is also known as Function Implementation: a. Function name. b. Function type.
ADCPM

TECHNIQUES & C

Page - 25

Module 5

PROGRAMMING

APR - 2010 / BLY

c. List of parameter. d. Local variable declaration. e. Function statement. f. Written statement. Syntax: <function type> <function name> (List of parameter) { Local variable declaration; Statement; return statement; } Function prototype: <function type> <function name> (List of parameter); Global Variable: Variable that both a live and active through out of the program are known as external variable these are also known as global variable. Automatic Variable: Automatic variable are declared inside a function in which they are utilize. They are created when the function is called and destroyed automatically when the function is exited, they are also called local and internal variable. Static Variable: These variables are declared with static keyword like. Example: static int n; Register Variable: You can tell the complier that a variable should be in one of the machine register insisted of keeping in the memory were normal variable are store seen a register variable access is much faster than a memory access. Example: register int n; Pointer: A pointer is a derived data type in C. It is built from one of the fundamental data type available in C. Pointers content memory address as their values. Since these memory addresses are the locations in the computer memory where program contain instruction and data are stored pointer can be used to access and manipulate data store in the memory. Declaring a pointer variable: Syntax: <data type> * <ptr name>; Example: int * salary; (or)float * sal; Accessing a variable through its pointer: When you declare a pointer type variable then you can use Example: int quantity, *p; quantity = 125; p =& quantity; address operator AND Operator: And operator is an address operator, which assigned the address of given variable into pointer type variable. Call by Value: In this function, you can pass the parameter as value type or reference type, when you pass the variable without any operator then called call by value parameters.
ADCPM

TECHNIQUES & C

Page - 26

Module 5

PROGRAMMING

APR - 2010 / BLY

Example: find the largest number between two numbers. Using a function large. # include<stdio.h> int large(int a, int b); // function prototype void main() { int n, y, l; printf(enter the value of n, y); scanf(%d%d, &n,&y); Actual parameter l = large(n,y); // function call printf(%d,l); getch(); } int large(int a, int b) //format parameter { if(a > b) return(a); else return(b); } Call by Reference: In this case, you pass the address of the given variable. Actual Parameter: These are the parameters, which pass in the function call. Formal Parameter: These are the parameter, which are used in called function. STRUCTURE: Structure is a derived data type. Structure is a collection of different type of data items. Syntax: struct <struct name> Where struct is a keyword and struct name is any user-defined name. Declaration: struct student { int rollno; char name [20]; float salary; }; Initialization of the variables in main and display. void main() { student stud; printf(enter roll number); scanf(%d, &stud.rollno); printf(enter name); gets(stud.name); printf(enter salary);
ADCPM

TECHNIQUES & C

Page - 27

Module 5

PROGRAMMING

APR - 2010 / BLY

scanf(%f, &stud.salary); printf(display); printf(roll no = %d, stud.rollno.); printf(in name = %s, stud.name); printf(in salary = %f, stud.salary); getch(); } Array of Structure: C permits the use of arrays as structure members you have already used arrays characteristics. Syntax & Example: struct student { int rollno.; float mark; char name; } stud [5]; void main() { int I; for(I = 1; I <= 5 ; I++) { printf(enter the roll no.); scanf(%d &stud [I].rollno.); printf(enter the name); scanf(%s, stud [I].name); printf(enter mark); scanf(%f, &stud[I].mark); } for(I = 1 ; I <= 5 ; I++) { printf(%d, stud [I].rollno.); printf(%s, stud [I].name); printf(%f, stud [I].mark); printf(\n); } getch(); } UNION: Union is a concept borrowed from structure and therefore the follow the same syntax as structure. However, there is the major difference between them in terms of storage. In structures, each member has its own storage location. Whereas all the member of a union use the same location. Although a union may contain many members of different types, it can handle only one member at
ADCPM

TECHNIQUES & C

Page - 28

Module 5

PROGRAMMING

APR - 2010 / BLY

a time. Union can be declared using the keyword union. Syntax: union <name of union> { declaration of var; ______ } object; Example: union item { int m; float n; char y; } object; void main() { printf(enter m); scanf(%d, &object.m); scanf(%f, &object.n); scanf(%c, &object.y); } Jumping Statement: In C, three jumping statements are used: (i) goto (ii) break (iii) continue. Goto: C language supports the goto statement to branch unconditional form one point to another in the program. Go to requires a label in order to identify the place where the branch is be made. A label is any valid variable name, and must be followed by colon. The label is placed immediately before the statement where the control is to be transferred. Syntax: goto label; label: : statement; label: : statement; goto label; forward jump backward jump Break: When you want to jump from loop then you can use break statement conditionally. Syntax: break; It is mainly used in switch. Continue: It is another jumping statement, which is used in C like a break statement. The difference between break and continue is continue skip the conditionally point and after that continue the statement (or) sequence. Syntax: continue;
ADCPM

TECHNIQUES & C

Page - 29

Module 5

PROGRAMMING

APR - 2010 / BLY

FILE HANDLING File: File is a define data type. It is use for store data in a manner in the secondary memory and uses this data every time, anytime when you want. Defining a File (Declaring File): If you want to store the data in a file, located in the secondary memory, you must specify certain thing about the file, to the operating system. They include a. File name: Filename is a string of characters that make up a valid file name for the operating system. Syntax: for declaring a file FILE * fp; b. Data Structure: Data structure of a file is defined as FILE in the library of standard input / output function definition. All file should be declared as type File before they are used. c. Purpose: It is used to store the data for use in future purpose. Opening a file: fp.fopen(filename, mode); The variable fp as a pointer to the data type FILE. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. Mode: Mode specifies the purpose of opening this file mode can be following types. rOpen the file for read only. wOpen the file for write only. aOpen the file appending for data to it. r +The exiting file is opened to the beginning both read and write. Closing a file: A file must be closed as soon as all operation on it has been completed. Syntax: f.close(fp); Input and Output operation on files: getc(); It is used for get character Syntax: c = getc(fp); putc(); It is used to put character to the file. Syntax: putc(c, fp); The file pointer moves by one character position for every operation of getc and putc. The getc will return End of File (EOF) when end of file has been reached. Functions fprintf(); fscanf(); getw(); putw(); fseek(); ftell(); rewind();
ADCPM

Operations Write a set of data values to a file. Read a set of data value form a file. Read an integer from a file. Writes an integer to a file. Sets the position to a desired point in the file. Given the current position in the file. Sets the position to the beginning of the file.
TECHNIQUES & C
Page - 30

Potrebbero piacerti anche