C Programming Notes (R10 I Year I Semester)
C Programming Notes (R10 I Year I Semester)
Introduction to Computers
Today computer systems are found everywhere. Computers have become almost as common as televisions. A computer is a system made of two major components. A Computer System consists of Hardware and Software. Computer Hardware is the collection of physical elements that comprise a computer system. Computer Software is a collection of computer programs and related data that provides the instructions for a computer what to do and how to do it. Software refers to one or more computer programs and data held in the storage of the computer for some purposes. Computer System
Basically Computer Software is of three main types Operating System: The Operating System (OS) is an interface between the computer software and hardware. The most popular and latest operating systems include Windows XP, Mac, UNIX, Linux, Windows Vista, etc. Application Software: The application software is widely used for accomplishment of specific and precise tasks which is a step ahead than the basic operations or running of the computer system. The application software includes printing documents, and permitting access to internet for web and video conferencing activities. The Application software indirectly does the interaction with the machine to perform all these functions. System Software: System software directly interacts with computer hardware. Some of the examples are the device drivers for CPU, Motherboard, Mouse, Printer, Keyboard, etc. The system software takes the responsibility of control, integration and managing individual hardware machine of the computer.
Page 1
System Support
Page 2
Computing Environment: Computing Environment is a collection of computers/machines, software, and networks that support the processing and exchange of electronic information meant to support various types of computing solutions. Types of Computing Environments Personal Computing Environment Client Server Environment Time sharing Environment Distributed Environment
Page 3
Distributed Computing
Page 4
Computer Languages To write a program for a computer, we must use a computer language. Over the years computer languages have evolved from machine language to natural languages. Machine Language Symbolic Language High-Level Languages Evolution of Computer Language
Page 5
Note: The only language understood by computer hardware is machine language. Example, Multiplication Program in Symbolic Language
Note: Symbolic language uses symbols, or mnemonics, to represent the various machine language instructions. Example, Multiplication Program in Computer Language /* This program reads two integers from the keyboard and prints their product */ #include<stdio.h> int main(void) {
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 6
T.RAVI KIRAN COMPUTER PROGRAMMING //Local Definitions int number1; int number2; int result; //Statements scanf(%d, &number1); scanf(%d, &number2); result = number1 * number2; printf(%d, result); return 0; } //main
Creating and Running the Programs Writing and Editing Programs Compiling Programs Linking Programs Executing Programs
Building a C Program
Text Editor
Compiler
Linker
Runner
Page 7
System Development This process determines the overall quality and success of our program. If we carefully design each program using good structured development techniques, our programs will be efficient, error-free, and easy to maintain. Waterfall Model
Systems Requireme nts Analysis Design Code System Testing Maintenan ce
get UserInfo
calculate
print Report
calc Kitchen
calc BathRoom s
calc BedRoom s
calc LivingAre as
calc FamilyRoo m
calc DineLivin g
Pseudocode: English like statements that follow a loosely defined syntax and are used to convey the design of an algorithm. Example Pseudocode for Calculate Bathrooms Algorithm Calculate Bathrooms 1 prompt user and read linoleum price 2 prompt user and read number of bathrooms 3 set total bath area and baths processed to zero 4 while ( baths processed < number of bathrooms ) 1 prompt user and read bath length and width 2 total bath area = 3 total bath area + bath length * bath width 4 add 1 to baths processed 5 bath cost = total bath area * linoleum price 6 return bath cost end Algorithm Calculate Bathrooms Flow Chart for Calculate Bathrooms
Page 9
Note: Except for the simplest program, one set of test data will not completely validate a program. Software Engineering Software engineering is the establishment and use of sound engineering methods and principles to obtain software that is reliable and that works on real machines. This definition, from the first international conference on software engineering in 1969, was proposed 30 years after the first computer was built. During that period, software was more of an art than a science. Algorithm An algorithm is a description of a procedure which terminates with a result. Algorithm is a step-by-step method of solving a problem. Properties of an Algorithm Finiteness: An algorithm terminates after a finite numbers of steps. Definiteness: Each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted in multiple ways & can be performed without any confusion. Input: An algorithm accepts zero or more inputs Output: An algorithm should produce at least one output. Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time. Compilers and Interpreters
A program is a set of instructions for performing a particular task. These instructions are just like English words. The computer processes the instructions as 1s and 0s. A program can be written in assembly language as well as high level language. This written program is called a source program. The source program is to be converted to the machine language,
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 10
T.RAVI KIRAN COMPUTER PROGRAMMING which is called an object program. Either an interpreter or a compiler will do this activity. Compiler: A compiler reads the entire program and converts it to the object code. It provides errors not of one line but errors of the entire program. Only error-free programs are executed. It consumes little time for converting a source program to an object program. When the program length for any application is large, compilers are preferred. A Compiler is software translates a complete source program into machine code. The whole source code file is compiled in one go, * a complete version of the file is produced. This can be saved on some secondary storage medium. This means that: The program can only the executed once from translation is executed. Any changes to the source code require a complete recompilation. Interpreter: An Interpreter reads only one line of a source program at a time and converts it to the object codes. In case there are errors, the same will be indicated instantly. The program written with an interpreter can easily be read and understood by the other users as well, so security is not provided. Anyone can modify the source code. Hence, it is easier than compilers. The disadvantage is that it consumes more time for converting a source program to an object program. Interpreter software, on the other hand, provides a means by which a program written in source language can be understood and executed by the CPU line by line. As the first line is encountered by the interpreter, it is translated and executed then it moves to the next line of source code and repeats the process. This means that: The interpreter program is loaded into memory alongside the source code program. Statements from the source program are fetched and executed one by one. No copy of the translation exists, and if the program is to the re-run, if has to be interpreted all over again. So to run a program, source code and an interpreter is required all the time.
Flowchart
A flowchart is a pictorial representation depicting the flow of steps in a program, people in an organization, or pages in a presentation. In instructional design, flowcharts provide a bird's-eye view of the structure and sequence of a lesson. Elements are represented by simple icons (circles, rectangles, diamonds, or other shapes), with lines and arrows representing connections between events and the direction or order in which they occur. A flowchart indicates sequences and decision points as well as starting and stopping points. Since it is easier to grasp relationships in a visual form than
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 11
T.RAVI KIRAN COMPUTER PROGRAMMING in a verbal description, flowcharts can prevent the omission of steps in a process. Flowcharts are particularly useful for instructional designers who are novice or occasional programmers. A flowchart is a graphical or pictorial representation of an algorithm. Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction. A flowchart represents an algorithm in graphical symbols. A flowchart is a diagram that depicts the "flow" of a program. A flowchart is a graphical representation of an algorithm. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program.
Example of flowchart symbols Terminal: Used to indicate the start and end of a flowchart. Single flow line. Only one "Start" and "Stop" terminal for each program. The end terminal for function/subroutine must use "Return" instead of Stop. Process: Used whenever data is being manipulated. One flow line enters and one flow line exits. Input/Output: Used whenever data is entered (input) or displayed (output). One flow line enters and one flow line exits. Decision: Used to represent operations in which there are two possible selections. One flow line enters and two flow lines (labeled as Yes and No) exit. Function/Subroutine: Used to identify an operation in a separate flowchart segment (module). One flow line enters and one flow line exits. On-page Connector: Used to connect remote flowchart portion on the same page. One flow line enters and one flow line exits.
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 12
Off-page Connector: Used to connect remote flowchart portion on different pages. One flow line enters and one flow line exits. Comment: Used to add descriptions or clarification.
Get A Get B
Stop
Page 13
Example flowchart for the pay-calculating Notice there are three types of symbols in this flowchart: rounded rectangles parallelograms a rectangle Each symbol represents a different type of operation.
Page 14
Output Operation
Parallelogra m
Process:
Rectangle
Output Operation
START
Rounded Rectangl e
Input x
Input y Sum = x + Example, algorithm and flowchart for finding the average of two y numbers
Page 15
Output: the average of x and y Steps: 1. 2. 3. 4. 5. input x input y sum = x + y average = sum /2 output average
Flowchart Structures
Sequence Structures a series of actions are performed in sequence The pay-calculating example was a sequence flowchart.
Page 16
A new symbol, the diamond, indicates a yes/no question. If the answer to the question is yes, the flow follows one path. If the answer is no, the flow follows another path
In the flowchart segment below, the question "is x < y?" is asked. If the answer is no, then process A is performed. If the answer is yes, then process B is performed.
Page 17
The flowchart segment below shows how a decision structure is expressed in C++ as an if/else statement.
Flowchart
The flowchart segment below shows a decision structure with only one action to perform. It is expressed as an if statement in C++ code.
Page 18
Flowchart
Repetition Structure A repetition structure represents part of the program that repeats. This type of structure is commonly known as a loop.
Notice the use of the diamond symbol. A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists.
Page 19
T.RAVI KIRAN COMPUTER PROGRAMMING In the flowchart segment, the question "is x < y?" is asked. If the answer is yes, then Process A is performed. The question "is x < y?" is asked again. Process A is repeated as long as x is less than y. When x is no longer less than y, the repetition stops and the structure is exited.
The flowchart segment below shows a repetition structure expressed in C++ as a while loop.
Flowchart
The action performed by a repetition structure must eventually cause the loop to terminate. Otherwise, an infinite loop is created. In this flowchart segment, x is never changed. Once the loop starts, it will never end. A Simple Question: How can this flowchart be modified so it is no longer an infinite loop?
Page 20
Answer By adding an action within the repetition that changes the value of x.
This type of structure is known as a pre-test repetition structure. The condition is tested BEFORE any actions are performed.
In a pre-test repetition structure, if the condition does not exist, the loop will never begin.
Page 21
This flowchart segment shows a post-test repetition structure. The condition is tested AFTER the actions are performed. A post-test repetition structure always performs its actions at least once.
The flowchart segment below shows a post-test repetition structure expressed in C++ as a do-while loop.
C++ Code do { cout << x << endl; x++; } while (x < y);
Flowcha rt
Page 22
T.RAVI KIRAN COMPUTER PROGRAMMING Case Structure One of several possible actions is taken, depending on the contents of a variable.
The structure below indicates actions to perform depending on the value in years_employed. If years_employed = 3, bonus is set to 400 If years_employed is any other value, bonus is set to 800 3 Other
bonus=1
bonus=2
bonus=4
bonus=8
Page 23
T.RAVI KIRAN COMPUTER PROGRAMMING Characteristics of Computers Speed You will be surprised to know that computer can perform millions (1,000,000) of instructions and even more per second. Therefore, we determine the speed of computer in terms of microsecond (10-6 part of a second) or nanosecond (10-9 part of a second). From this you can imagine how fast your computer performs work. Accuracy Suppose someone calculates faster but commits a lot of errors in computing. Such result is useless. There is another aspect. Suppose you want to divide 15 by 7. You may work out up to 2 decimal places and say the dividend is 2.14. I may calculate up to 4 decimal places and say that the result is 2.1428. Someone else may go up to 9 decimal places and say the result is 2.142857143. Hence, in addition to speed, the computer should have accuracy or correctness in computing. The degree of accuracy of computer is very high and every calculation is performed with the same accuracy. The accuracy level is determined on the basis of design of computer. The errors in computer are due to human and inaccurate data. Versatility It means the capacity to perform completely different type of work. You may use your computer to prepare payroll slips. Next moment you may use it for inventory management or to prepare electric bills. Power of Remembering Computer has the power of storing any amount of information or data. Any information can be stored and recalled as long as you require it, for any numbers of years. It depends entirely upon you how much data you want to store in a computer and when to lose or retrieve these data. No Feeling It does not have feelings or emotion, taste, knowledge and experience. Thus it does not get tired even after long hours of work. It does not distinguish between users. Storage The Computer has an in-built memory where it can store a large amount of data. You can also store data in secondary storage devices such as floppies, which can be kept outside your computer and can be carried to other computers.
Page 24
memory
input (keyboar d)
interface
microprocess or
interface
output (monitor )
interface
interface
cd rom
hard
floppy
Hardware: The physical components which are used to assemble computer system are known as hardware. Any computer device which we can touch including cables and wires is hardware. Input Unit: Computers need to receive data and instruction in order to solve any problem. Therefore we need to input the data and instructions into the computers. The input unit consists of one or more input devices. Keyboard is the one of the most commonly used input device. Other commonly used input devices are the mouse, floppy disk drive, magnetic tape, etc. All the input devices perform the following functions. Accept the data and instructions from the outside world. Convert it to a form that the computer can understand. Supply the converted data to the computer system for further processing.
Page 25
Storage Unit: The storage unit of the computer holds data and instructions that are entered through the input unit, before they are processed. It preserves the intermediate and final results before these are sent to the output devices. It also saves the data for the later use. The various storage devices of a computer system are divided into two categories. Primary Storage: Stores and provides very fast. This memory is generally used to hold the program being currently executed in the computer, the data being received from the input unit, the intermediate and final results of the program. The primary memory is temporary in nature. The data is lost, when the computer is switched off. In order to store the data permanently, the data has to be transferred to the secondary memory. The cost of the primary storage is more compared to the secondary storage. Therefore most computers have limited primary storage capacity. Secondary Storage: Secondary storage is used like an archive. It stores several programs, documents, data bases etc. The programs that you run on the computer are first transferred to the primary memory before it is actually run. Whenever the results are saved, again they get stored in the secondary memory. The secondary memory is slower and cheaper than the primary memory. Some of the commonly used secondary memory devices are Hard disk, CD, etc., Memory Size All digital computers use the binary system, i.e. 0s and 1s. Each character or a number is represented by an 8 bit code. The set of 8 bits is called a byte. A character occupies 1 byte space. A numeric occupies 2 byte space. Byte is the space occupied in the memory. The size of the primary storage is specified in KB (Kilobytes) or MB (Megabyte). One KB is equal to 1024 bytes and one MB is equal to 1000KB. The size of the primary storage in a typical PC usually starts at 16MB. PCs having 32 MB, 48MB, 128 MB, 256MB memory are quite common. Output Unit The output unit of a computer provides the information and results of a computation to outside world. Printers, Visual Display Unit (VDU) are the commonly used output devices. Other commonly used output devices are floppy disk drive, hard disk drive, and magnetic tape drive. Arithmetic Logical Unit All calculations are performed in the Arithmetic Logic Unit (ALU) of the computer. It also does comparison and takes decision. The ALU can perform basic operations such as addition, subtraction, multiplication, division, etc and does logic operations viz, >, <, =, etc. Whenever calculations are required, the control unit transfers the data from storage unit to ALU once the computations are done, the results are transferred to the storage unit by the control unit and then it is send to the output unit for displaying results.
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 26
T.RAVI KIRAN COMPUTER PROGRAMMING Control Unit It controls all other units in the computer. The control unit instructs the input unit, where to store the data after receiving it from the user. It controls the flow of data and instructions from the storage unit to ALU. It also controls the flow of results from the ALU to the storage unit. The control unit is generally referred as the central nervous system of the computer that control and synchronizes its working. Central Processing Unit The control unit and ALU of the computer are together known as the Central Processing Unit (CPU). The CPU is like brain performs the following functions: It performs all calculations. It takes all decisions. It controls all units of the computer. A PC may have CPU-IC such as Intel 8088, 80286, 80386, 80486, Celeron, Pentium, Pentium Pro, Pentium II, Pentium III, Pentium IV, Dual Core, and AMD etc. Software Software is a set of program or instructions given to the computer to carry out certain jobs or tasks. It is set of programs which actually makes the computer useful. The software can be classified into three categories. System Software System software is responsible for managing a variety of independent hardware components, so that they can work together. Its purpose is to unburden the application software programmer from the often complex details of the particular computer being used, including such accessories as communications devices, printers, device readers, displays and keyboards, and also to partition the computer's resources such as memory and processor time in a safe and stable manner. Device drivers Operating systems Servers Utilities Window systems Programming Software Programming Software usually provides tools to assist a programmer in writing computer programs, and software using different programming languages in a more convenient way. The tools include, Compilers Debuggers Interpreters Linkers Text editors Application Software Application software is developed to aid in any task that benefits from computation. It is a broad category, and encompasses Software of many
T.RAVI KIRAN@COMPUTER PROGRAMMING Page 27
T.RAVI KIRAN COMPUTER PROGRAMMING kinds, including the internet browser being used to display this page. This category includes, Business software Computer aided design Databases Decision making software Educational software Image editing Industrial automation Mathematical software Medical software Simulation Spreadsheets Telecommunications Video games Word processing Applications of Computers Computers applications are used worldwide in almost all fields. Science: scientists use computers to analyze large quantity of data to analyze the effect of earthquake on buildings dams, for satellite launching and remote controlling etc. Education: Computers are used in all educational institutions ranging from ordinary schools to universities for variety of purpose like training, elearning, exams and results. Medicine and Health: The doctors and technicians use computer to diagnose the human problems and monitor them to provide treatment. Engineering/ Architecture / Manufacturing: They are used for planning, designing, and drawing the layouts. Entertainment: Computers used to listen the music, play the video games, graphics in movies. Communication: to send and receive mails, e-commerce, e-shopping, ebanking and e-learning. Business and Banking Applications: Computers are used in all commercial and business organizations. Government: Used for weather forecasting, in military, satellite launching and controlling, communication and e-governance.
Page 28
Introduction to Programming
Software refers to a program or set of instructions that instructs a computer to perform some task. Software can be divided into two major categories called system software and application software. Systems software includes operating systems and various device drivers. Application software is used to perform real world tasks and solve specific problems. A Program is simply a set of instructions that tells a computer how to perform a particular task. Programs are developed using programming languages. Computer Programming is the art of developing computer programs. Programming is rather like a recipe; a set of instructions that tells a cook how to make a particular dish. It describes the ingredients (the data) and the sequence of steps (the process) on how to mix those ingredients. A programming language provides a set of rules to develop a program. A person who writes a program using a programming language is called programmer. His/her job is to convert a solution to a problem (i.e. algorithm) into set of instructions understood by a computer. The programmer should also test the program to see whether it is working properly and corrective actions should be taken if not. Program Development Developing a program involves a set of steps: 1. 2. 3. 4. 5. Define the problem. Outline the solutions. Develop the algorithm. Test the algorithm for correctness. Code the algorithm using a suitable programming language.
Page 29
T.RAVI KIRAN COMPUTER PROGRAMMING 6. Compile and correction of compile errors. 7. Run the program on the computer. 8. Test, document and maintain the program. Most of these steps are common to any problem solving task. Program development (software development) may several hours, days, weeks, months or years. After development, customers will make use of the system. While in use, the system needs to be maintained. The maintenance phase will continue for several months, years or even several decades. Therefore software development is not a onetime task; it is a lifecycle where some of the above steps are reformed again and again. Running a Program After a program is developed using a programming language, it should be executed by the computer. Programmers write programs in human readable language called high level language. However, the computer understands only 1's and 0's (referred as the machine language or machine code). Therefore we need to convert the human readable programs into a machine language before executing. This is conversion is achieved by a special set of programs called compilers (or interpreters). These programs convert the high level language program, into machine language programs. Converting a human readable program into machine language
int a; a = 10; b = 2 * a; c = a * a; 01010011110
Compil e
Compiler translates a source program (human readable) into an executable (machine readable) program. Executable machine code produced by a compiler can be saved in a file (refers as the executable file) and used whenever necessary. Since the source program is already compiled, no compilation is needed again unless the source program is modified. The saving on the compilation time is an advantage that is gain from compiling and therefore these programs run much faster. Programs written in programming languages such as FORTRAN, COBOL, C, C++ and PASCAL must be compiled before executing. 1.1 Compiling and executing a program Source Code Code
Compiler
Machine
Page 30
Input data
Executab le
1.2 Interpretation of a program
Output data
Source Code
Interpret er
Output data
Input data As in Figure 1.2 when the executable file is available it can be executed by providing necessary input data so that it produces the desired outputs. Interpreters convert a source program and execute it at the same time (Figure 1.3). Each time the program runs, the interpreter converts high level language instructions and input data to a machine readable format and executes the program. This process can be slower than the process which compiles the source program before execution. The program needs to be converted as well as executed at the same time. Programs written in languages like BASIC, Perl, Smalltalk, Lisp and VB Script are interpreted.
Page 31