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 programmer‟s 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

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

It shows the main stages of a problem. Then a group of designer can examine the flow-chart and determine. the entry of computer data and output operation means. The input operation means. Annotation Symbol: Programmer often wants to write remarks or comments in a flow chart. Input and Output Symbol: It is used to represent the logical positioning of input and output operations. which provides a detailed description of the flow of data in the processing. 4. 3. Decision Symbol: This Symbol represents logical operations showing a decision point in a program. 5. the display output information.Module – 5 PROGRAMMING APR . In simple words. and how they are related? Flow chart is effective and inexpensive analytical tool. The two main components of a decision symbols are a. Processing Symbol: This symbol represents some operations (processing) of the data. Terminal Symbol: START and STOP It is used to indicate a point at which the flow-chart beings or ends.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. Flow Symbol: A flow symbol is an arrow that shows the flow of program logic in a flow chart. b. 6. 2. With the help of a flow chart programmer can quickly show a series of alternative approach to a problem.5 . you can say that the flow chart is like a road map. which do not affect the processing but clearly a particular point in the flow chart. Flow Chart Symbol: The various symbols of a flow chart are 1. It is an expected procedure to insert the words „START‟ or „STOP‟ within the terminal symbol. ADCPM TECHNIQUES & ‘C’ Page . which solution best suitable for their need. The result of the decision (Yes / No). A question that defines the logical operation.

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

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

There are three logical operators ADCPM TECHNIQUES & ‘C’ Page .Module – 5 PROGRAMMING APR . N2. Relational Operator They are used to test the relationship between two variables. Relational Operators 3. Arithmetic Operators 2. Logical Operators Arithmetic Operators They are used to perform arithmetic calculations. Begin numeric N1.2010 / BLY PSEUDOCODE 1. -. It returns the response as TRUE or FALSE. As 0 > 0 // Returns False.2 The following pseudocode and corresponding flowchart will take two numbers and display the remainder of them.8 . 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. The symbols used are: (+. Sum accept N1 accept N2 Sum = N1 + N2 display Sum end // Variable declaration Start Numeric N1. >. The Relational operators are (=. N2. <=) these operators are good tools to compare the values of two operands. %) PSEDOCODE 1. >=. Logical Operators They are used to combine expressions containing relational operators.1 Here is the pseudocode and corresponding flow chart to accept two numbers to display the result of their addition.

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. N2. In such kind of situation “if condition” will be used. Dept = “Sales” or Dept = “Act” NOT Operator: It is evaluated to true if the condition is not met. To denote conditional statement if conditional construct is used with pseudocode and decision making symbol is used with flow charts. So using logical operator you can club more than one condition together.you require performing an operation on the basis of more than one condition. In this case. Example: If you want to print. Conditional statement is required when decision can be changed based on any condition.g. begin numeric N1. AND 2. OR Operator: It is used when any one of the condition is to be satisfied. else STATEMENT if <condition> begin [Statement to be executed if condition is true] ADCPM TECHNIQUES & ‘C’ Page . the value of no I should be in between 10 and 20. if. „Pass‟ for marks greater than 33 & „Fail‟ for otherwise.2010 / BLY 1. No1 > 10 and No1 < 20.rem accept N1 accept N2 rem = N1 % N2 display rem End Start Numeric N1.Module – 5 PROGRAMMING APR ..N2. OR 3. NOT Sometimes.9 . AND Operator: In the case of AND operator both the conditions should be satisfied e.

but there can be any number of decision boxes in a single flow chart.Module – 5 PROGRAMMING APR . ADCPM TECHNIQUES & ‘C’ Page . begin numeric X. Iteration methods are also called loops. 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.3 The following pseudocode and corresponding flow chart will print the bigger of two numbers using if construct. only one decision can be taken. Using While Loop The repeated portion of a flow chart is called a loop. There are two types of loop: For Statement (If the number of repetition are known in advance). Iteration (Loop) While executing. In a decision box.2010 / BLY end else begin [Statement to be executed if condition is false] end endif PSEUDOCODE 1. the same statement again and again you can use iteration method instead of repeating the code. While Statement (If the number of repetition is not known in advance). Y accept X accept Y if X>Y begin display X end else begin display Y end endif end Start Numeric X.10 .

4 The following pseudocode and corresponding flow chart. The value of Num is increased by 1. prints the sum of first ten natural numbers using while loop. When you know the number of times. The pseudocode and flow chart will be as follows: ADCPM TECHNIQUES & ‘C’ Page . N N=1 while(N <= 10) begin Sum = Sum + N N=N+1 end end while display Sum end Start Numeric Sum.11 . Here the step 4 and 5 are repeated until the variable Num is less than 10. Each time the variable Num is added to the variable sum. 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. the loop is to be continued you can use for loop. Let us take another example to simplify the loop. N = 1 A Sum = Sum + N N=N+1 If N >10 Yes No A Display Sum Stop Loop is performed until condition is satisfied.2010 / BLY PSEUDOCODE 1. Thus.Module – 5 PROGRAMMING APR .5 We will accept the Name from the user. PSEUDOCODE 1. which has to be printed 5 times. begin numeric Sum. Using For Loop From the Flowchart discussed above. N Sum = 0. the variable Num works as a counter.

Process: This part of algorithm does the required computation with the ADCPM TECHNIQUES & ‘C’ Page .e. An algorithm written in a computer language is called a program. It becomes programmer‟s duty to precisely define his problem in the form of algorithm i. 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. is known as algorithm. The set of rules that define how a particular problem can be solved in finite sequence of steps is known. Input: This part of algorithm reads the data by accepting the input of given problem. which gives solution of a problem. 1. unambiguous steps written in simple English.Module – 5 PROGRAMMING APR . 2. An algorithm written in a computer language is called as a program. The desirable features of an algorithm are: Characteristic of Algorithm: There are five basic characteristics.2010 / BLY Begin char name numeric a a=0 accept name For a = 0 to 5.12 . Logical sequence of steps. as algorithm. The most common approach to define a problem is to summarize its algorithm in English as clearly as possible. The most common approach to define a problem is to summarize its algorithm in English as clearly as possible.

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

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

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

7e+308 3.4e-4932 to 1. called as symbolic variables.%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. which represent type of the value stores in the variable. 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 is declared in the program. to store name of a student and marks of a student during program run.7e-308 to 1. whose values can be manipulated during program run.4e-38 to3. serve ADCPM TECHNIQUES & ‘C’ Page .%c string . short integer float double value accept char character or string (sentence or word) string long int .%d float . you require storage locations that too named so that these can be distinguished easily. Variables.Module – 5 PROGRAMMING APR .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. for instance.16 .%f char .2010 / BLY identifier‟s names.4e+38 1.

There are two values associated with a symbolic variable: 1. “my name is raj”. This is sometimes referred to as a variable‟s lvalue. 1. 2. followed by include statement and a file name with h (header) extension enclosed within angle bracket (<… . #define: This pre-processor is used to create constant in a program.h>). ADCPM TECHNIQUES & ‘C’ Page .Module – 5 PROGRAMMING APR . The method of writing integer constants has been specified in the following rules. It is the data value. Example: int a=100. It is the location value. This statement is called a pre-processor directive. Each preprocessor is an instruction to the compiler. the following statement declares a variable b of the data type int (integer): int b. which instructs the compiler to insert another file into the source file. Hexadecimal Character Constant: A character constant is one character enclosed in single quotes. #include: This pre-processor is used to insert another file in a program. Memory Address  Data value of variable Variable‟s 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. stored at some location in memory. A string literal is a sequence of characters surrounded by double quotes. The variables are called symbolic variables because these are named. which is the address in memory at which its data value is stored. Literals: Literals are data items that never change their value during a program run.1. Floating Constant: Floating constants are also called real constants. String Literal: Multiple Characters constants are treated as string literals. Initialization of variables: Type varname=value.2010 / BLY the purpose. as in „a‟.0. Pre-processor: The first line in a program starts with # (hash) sign. Real constants are numbers having fractional parts. Where type is any data type of C and varname is the name of variable. Decimal 2.75. Octal 3. This is sometimes referred to as a variable‟s rvalue. Example: 2. C allows several kinds of literals: Integer Constant: Integer constants are whole numbers without any fractional part. Example: “abc”. For instance.17 .

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

5 log(2. generally called braces. For mathematical calculations and various conversions. For example: In A+B The symbol „+‟ is an operator and two data items A and B are called operands. sqrt(6.e. When a void return is required. The two curly brackets. Arithmetic Operators: + Addition Subtraction * Multiplication / Division % Module 2. routines are available in this <math.h file declares the prototypes of the mathematical and mathematical error handler functions.h> void main() { printf(“welcome in C world”).815276313 cos(0. If this is missing then main may be taken as a variable by the compiler. If it is not present in a program. where the counter moves during starting of execution.19 . Logical Operators: ADCPM TECHNIQUES & ‘C’ Page . <math.h> header file.y) Description Returns the value of x y Raised to the power y i.25) returns 2. 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.2) 0.980066577 returns Return pow() sqrt() log() sin() cos() MAIN FUNCTION The word main is very important.2010 / BLY 4. and must appear once in each C program. Such as the following : Function pow(x. First Program in C: #include<stdio. 9. It must exist as the entry point.2598) 0.h>: The math. are used to define the limits of the program itself. it is necessary to include return 0 as the last statement or declare main function as void main().Module – 5 PROGRAMMING APR . int2) returns 2 the value 3 i. 1. The bracket () form a part of the main function. If no return value is specified. } OPERATORS An operator is a symbol or letter use to indicate a specific operation on the variables in a program. an error signal is given by the linker. It is stand alone function. Main function returns an integer to the operating system that is specified in the return statement.e. some compiler by default assumes a void return.

Syntax: if(expression) { statement 1. 3. if condition is true the statement under if condition will execute. then the result will be true. If the expression is true then it converts to false. otherwise the statement after the else statement will execute. ?: Select Construct (Selective Execution Conditional Statement) : In this case. The IF Statement: This statement helps us in the selection of one out of two alternative courses of action. any one condition is false than the result will be false. In C. When the given all conditions or any one condition is true the result will be true. } 2. } ADCPM TECHNIQUES & ‘C’ Page . 1.20 .Module – 5 PROGRAMMING APR . 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. The IF . c. you can use if else statement. The conditional operator is allowed on the left side of the expression. 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. If in all given conditions. Syntax: if(expression) { statement. 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.Else Statement: In this case. it requires three operands. ! (NOT): This operator negates or reverse the value of the expression follows by it. && (AND): If you want to check two or more condition at a time than you can use „&&‟ operator.2010 / BLY a. Only if all given conditions are true. b. II (OR): This operator is used to check two or more condition at a time. if statement is used for selective execution of a program segment. and vice versa.

} else { statement. : : case constant n: statement n. It begins with the keyword switch followed by a variable in parentheses which is the switching variable. The various case values can be in any order and if a value is not found. therefore. } else if(expression) { statement 2. } else if(expression) { statement. And the break statement will cause you to jump out of the switch. then a colon. The statement sequence of if else may contain another if statement.Else IF Statement). the default portion of the switch will be executed. statements will be executed until a break is found or until the program drops through the bottom of the switch braces. } 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. } Nested IF Statement (IF . } if(expression) { if(expression) { statement. } else { statement 3. ADCPM TECHNIQUES & ‘C’ Page . It is a multi-branch selection statement. Once an entry point is found. which makes the control to jump to one of the several statements based on the value of an integer variable or expression. and the statements to be executed. break. if else statement can be nested within one another. Syntax: switch(expression) { case constant 1: statement 1. break. Syntax: if(expression) { statement 1.21 .Module – 5 PROGRAMMING APR . The reserved word case is used to begin each case entered followed by the value of the variable.2010 / BLY else { statement 2. case constant 2: statement 2.

2010 / BLY break. There are three types of loop are 1. Syntax: initialization: while(conditional expression) { statement. and finally an expression in parentheses.Module – 5 PROGRAMMING APR . The statements in the braces are executed repeatedly as long as the expression in parentheses is true. } LOOP Some problems require that a set of statement should be executed a number of times. then the reserved word while. each time changing the values of one or more variables so that every execution is different from the previous one. default: statement. I++. Do … While loop: Do… While loop is the exit control loop. while(I <= 10) { printf(“%d\n”. While Loop: It is the loop. in which first initialization the value and check the condition. l). } 2. and control passes to the following statement. Syntax: ADCPM TECHNIQUES & ‘C’ Page . : : increment/decrement. This kind of repetitive execution of a set of statements in a program is known a loop. execution is terminated. followed by a compound statement in braces.22 . When the expression in parentheses becomes false. I = 1. } Example: void main() { int I. } getch(). This loop begins with the reserved word do. 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. 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.

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

j++) scanf(“%d”. Example: char name [20]. Syntax: <data type> <array name> [rows] [columns]. 1. in which you can store similar data items. 1. } printf(“\n”). Display of 2 D Array in Matrix form: for(i=0. Declaration of 2 D Array: int a [3] [3]. 2. i++) for(j=0. a[i]). i++) { for(j=0. 2. j<3.2010 / BLY Example: int rollno [20]. i<3.&a[i]). 3. 1. ADCPM TECHNIQUES & ‘C’ Page .24 . Declaration: char <string name> [size]. and multi dimensional. Its lower limit start from 0 and upper limit is (n-1) or (size-1). 2 dimensional (2D). in which you can store the data in rows and columns. Declaration 1 D Array – int rollno [20].a[i][j]). is a string constant. We can define array 1 dimensional.Module – 5 PROGRAMMING APR . Example: int a [3] [3]. i<n . Any group of characters is defined between double quotation mark. Initialization of 2 D Array: for(i=0. i++) { printf(“%d”. i<3. j++) { printf(“%d”. Print the Output of the Array and Display Array: for(i=0 . Example: “ I am student ”. i<n . i++) { scanf(“%d”.&a[i][j]). j<3. } 3. 1 D Array: It is a single row array. } 2 D Array: It is a 2 dimensional array. Initialization in Array – for(i=0 . } STRING A string is a sequence of character that is as a single data item. 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.

2. name). Function Definition: Function definition is an independent program modal that is special written to implements the requirement of the function. b. Display the string: printf(“%s”. Comparison to string. FUNCTION If a program divided into fictional part than each part may be separately coded and later combine into a single unit. String Handling Function: 1. It copies one string over another. ADCPM TECHNIQUES & ‘C’ Page . Input (1) char ch.Module – 5 PROGRAMMING APR . ch =getchar(). 3. 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. (2) gets(name).2010 / BLY 2.25 . 1. Reading String by using Scanf:Example: scanf (“%s”. Used getchar and gets: A getchar read a single char but gets read a string without space. Function 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. 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.h. Find the length of string. Function type. 2. 4. These functions are available in header file stdio. In C function are divided into two parts. Function strcat() strcmp() strcpy() strlen() Action It can concatenate to string. These separately coded programs are called sub programs that are much easier to understand debug and test in C. Initialization: char name [10] = “ Ramnagar ”. name).Library Function And User Define Function : Example: These are predefined function (library function): User Defined Function: In user define function. Definition of Function: Function Definition is also known as Function Implementation: a. 3. Such sub programs are referred to as functions. Function Call: Function call in order to use. you need to establish three elements that are related to function.

Declaring a pointer variable: Syntax: <data type> * <ptr 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. Call by Value: In this function. It is built from one of the fundamental data type available in C. address operator AND Operator: And operator is an address operator. (or)float * sal. *p. 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. e.2010 / BLY c. ADCPM TECHNIQUES & ‘C’ Page . Example: register int n. Static Variable: These variables are declared with static keyword like. quantity = 125. Pointer: A pointer is a derived data type in C.26 . Automatic Variable: Automatic variable are declared inside a function in which they are utilize. Syntax: <function type> <function name> (List of parameter) { Local variable declaration. Local variable declaration. Written statement. which assigned the address of given variable into pointer type variable. Accessing a variable through its pointer: When you declare a pointer type variable then you can use Example: int quantity. Example: static int n. when you pass the variable without any operator then called call by value parameters. d. you can pass the parameter as value type or reference type. p =& quantity. } Function prototype: <function type> <function name> (List of parameter). Pointers content memory address as their values. return statement. 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. They are created when the function is called and destroyed automatically when the function is exited.Module – 5 PROGRAMMING APR . Example: int * salary. they are also called local and internal variable. Statement. f. Function statement.

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

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

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

r +The exiting file is opened to the beginning both read and write. Syntax: for declaring a file FILE * fp. TECHNIQUES & ‘C’ Page .fopen(“filename”. anytime when you want. Functions fprintf(). Syntax: f.  The variable fp as a pointer to the data type FILE. ftell(). 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.  The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. Defining a File (Declaring File): If you want to store the data in a file. you must specify certain thing about the file. ADCPM Operations Write a set of data values to a file.Module – 5 PROGRAMMING APR . fscanf(). rewind(). to the operating system. Read a set of data value form a file. It is used for get character Syntax: c = getc(fp). located in the secondary memory. b. Sets the position to a desired point in the file. Sets the position to the beginning of the file. Read an integer from a file. aOpen the file appending for data to it. putw(). Purpose: It is used to store the data for use in future purpose. Input and Output operation on files: getc(). File name: Filename is a string of characters that make up a valid file name for the operating system.  Mode: Mode specifies the purpose of opening this file mode can be following types. Opening a file: fp. It is used to put character to the file.close(fp). putc(). They include a. Closing a file: A file must be closed as soon as all operation on it has been completed. The getc will return End of File (EOF) when end of file has been reached. wOpen the file for write only. Writes an integer to a file. Syntax: putc(c. rOpen the file for read only. c.2010 / BLY FILE HANDLING File: File is a define data type. fseek(). fp). getw().30 . The file pointer moves by one character position for every operation of getc and putc. Given the current position in the file. It is use for store data in a manner in the secondary memory and uses this data every time. “mode”).

Sign up to vote on this title
UsefulNot useful