Page 1 :
NIE First Grade College, Mysore, COMPUTER CONCEPTS AND C PROGRAMMING, UNIT-1, CHAPTER-1: Computer Fundamentals, , Computer: - A Computer can be defined as an electronic device, which can process large, volumes of data using pre-defined instructions set by a human being., , Monitor, System Unit, (CPU), , Screen, , Speaker, , Keyboard, Mouse, , Data: - Data is a collection of facts, figures, statistics that can be processed to produce, meaningful information., Information: - Information is nothing but the processed data., Human beings supply data to the computer, which are required to be processed. Not only that,, one has to supply the instructions required to process the data. The computer remembers both, the data and instructions, does the processing when asked to and gives us the result in the, specified form., Advantages of a computer, Very high speed: - All the operations in a computer are caused by electrical pulses., We all know that electricity travels at the speed of light, computers too can perform, innumerable operations in just 1 sec. The processing speed of a computer is generally, measured in nanoseconds., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 1
Page 2 :
NIE First Grade College, Mysore, Large storage and retrieval capacity: - Computers have very large storage capacity., The contents of around two hundred sheets of A4 size paper can be stored on a small, floppy disk, which is not even half the size of one sheet of paper., Accuracy in calculation: - Computers have many check circuits built in and so, normally they do not make mistakes. Errors in computing are generally due to human, negligence rather than technological faults., Diligence: - Computers, being machines, do not suffer from fatigue and lack of, concentration. If five million calculations have to be performed, a computer can, perform the five millionth calculations with same accuracy and speed as it performed, the first calculation., Versatility in application: - Computers can perform a wide range of jobs with speed,, accuracy and diligence., Disadvantages of Computer, Cannot think, Cannot learn by experience, Cannot take independent decisions, requires human instruction to take a decision., History of Computers, The evolution of computer has passed through different stages before it reached the present, state of development. The evolution probably started from the 3500 BC when human being, first started to learn to calculate with a calculating machine named Abacus. Thus, the, evolution of counting system from Abacus to modern Microcomputer is the result of, continuous human effort in search of a more versatile and efficient machine., Abacus: - Abacus seems to be the earliest calculating machine, which was developed by the, Chinese. Abacus consists of beads, which can move, in wires. The wires represented the, column. The right most columns represented the unit, the next for ten and so on. Numbers, were represented by moving the beads at appropriate column. Abacus could perform simple, addition and subtraction., Pascal’s Mechanical Calculator: - Blaise Pascal, the French mathematician, laid the, foundation of automatic computing. Blaise Pascal used his adding machine (1662) simply for, addition and subtraction. The machine consisted of gears, wheels and dials. With this, calculation could be performed by dialling these series of wheels carrying the number 0 to 9, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 2
Page 3 :
NIE First Grade College, Mysore, around their circumference. The wheel was arranged in such a manner that each wheel had 10, segments and when a wheel completed one rotation the next wheel would move by one, segment. This machine was later improved by Gottfried (Germany) to perform multiplication, and division., Charles Babbage’s Differential Engine: - Charles Babbage, a professor of mathematics at, Cambridge University, invented a machine called Differential Engine- which could evaluate, accurately algebraic expression and mathematical tables- correct up to 20 decimal places., Later, he developed analytical machine, which could perform addition at the rate of 60 per, minute., For technical limitations of that age, Charles Babbage could not see his invention operational., However, and surprisingly enough, today‟s computer has building blocks, similar to what, was proposed by him. For this reason, Charles Babbage is remembered as the father of, computing. With him, his disciple and co-worker, Lady Lovelace is remembered with, reverence as the first programmer of the world., Mark I: - In 1934, Harvard professor H. Eiken developed an automatic calculating machine,, which was called Mark-I digital computer. Its internal operation was automatically, controlled., The basic drawbacks of the mechanical and electromechanical computers were:, , , The speed was limited due to the friction/inertia generated by the movement of, components., , , , The data movement was quite difficult and unreliable., , The designers were looking for better switching devices, storing of the mechanism and, reducing moving mechanical parts. With the advent of triode vacuum tubes, a better, switching device of earlier years, designers shifted to designing electronic computer., Electronic Numeric Integrator and Calculator (ENIAC): - While Mark-I was the first, electromechanical computer, the first electronic general purpose computer was built in 1946, by a team of professors at Moore school of university of Pennsylvania and was called, ENIAC. The ENIAC ushered in era of what is known as first generation computer. It was a, bulky machine consisting of 18,000 vacuum tubes, 70,000 resistors, 10,000 capacitors,, 60,000 switches and a large size occupying 1500 Sq. Feet of space. It was a very fast machine, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 3
Page 4 :
NIE First Grade College, Mysore, as compared to its ancestors and could perform 5000 additions or 350 simple multiplications, in just one second., The main features of ENIAC can be summarized as: , , ENIAC was a general purpose computing machine where vacuum tube technique was, used., , , , ENIAC was based on decimal arithmetic., , Universal Automatic Computer (UNIVAC): - In the year 1946, Eckert and Mauchly, founded their own company and began to work on the University Automatic Computer, or, UNIVAC. In 1949, Remington Rand acquired the Eckert-Mauchly Computer Corporation,, and in early 1951 the first UNIVAC-1 became operational at the Census Bureau. It was, followed by EDVAC (Electronic Discrete Variable Automatic Computer) which had a, storage capacity of 1024 words or 44 bits each., Computer Generations, The word “Generation” – for computers, indicates a step in technology. Every step includes a, major change in the components used for constructing a computer. Originally, the term, „generation‟ was used to distinguish between varying hardware technologies (in some cases, software also)., First generation (1942-1955): - The computers produced between 1942-1955 are called the, first generation computers. They were extremely large with low reliability. They used, vacuum tubes in their circuitry which were fairly large and generated considerable heat, needed lot of space to install and required special air conditioning system. Storage technique, and the use of punched cards for input output were primitive., Disadvantages, , , Too bulky in size., , , , Unreliable for excessive heat generation., , , , Air conditioning requirement was too much due to heat generation., , , , Non-portable., , Second generation (1955-1964): - The second Generation computers used a more advanced, technology by replacing the vacuum tubes with transistors. A transistors is a two state device, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 4
Page 5 :
NIE First Grade College, Mysore, made from silicon. These components were smaller in size, easier to manufacture, less power, consuming, cheaper and more durable. The processing capacity and the speed of operation of, the components built from transistor were considerably increased., Advantages, , , Smaller in size as compared to first generation computers, , , , More reliable, , , , Less heat generated, , , , Faster computational speed, , Disadvantages, , , Air conditioning required., , , , Frequent maintenance required., , , , Commercial production was difficult and costly., , Third Generation (1964-1975): - The third generation computers employed integrated, circuits in which all the elements of an electronic circuit were contained in a tiny silicon, wafer. The Integrated Circuits (IC) based on the small, medium and Large-Scale Integration, (LSI) technology replaced the individual transistors in the third generation computers. Each, Large-Scale Integrated circuit had hundred or more components packed into an assembly., Advantages, , , Smaller in size as compared to previous generation computers, , , , Even more reliable than second generation, , , , Lower heat generated than second generation, , , , Reduce computational times, , , , Low maintenance cost, , , , Comparatively portable, , , , Less power consumption, , , , Commercial production easier and cheaper, , Fourth generation (1975-1984): - Fourth generation machines appeared in the 1970‟s,, utilizing still newer electronic technology, which enabled them to be even smaller and faster, than those of 3rd generation. The fourth generation computers used VLSI (Very Large Scale, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 5
Page 6 :
NIE First Grade College, Mysore, Integration) technology. The VLSI devices have thousands of more components packed into, an assembly., Advantages, , , Low cost machine, , , , High speed, , , , Large memory, , , , Small size, , , , Less power consumption, , , , Floppy disk is used as storage device, , , , Hardware failure is negligible, , , , Heat generated is negligible, , , , Cheapest among all generations, , Fifth Generation (1984-1990): - Scientists are now at work with the fifth generation of, computers. The world is moving towards the development of what one can call „Super Scale, Integration‟ – which in turn will compliment and improve speed, miniaturization and cost, reduction. Development of artificial intelligence to make computer function and take, decisions almost like human being, implementation of expert systems, robots, intelligent, programs, speech synthesizers as well as the use of video disks and tapes for external storage, media, are included in the fifth generation of computer innovation., year, , Generation Number, , Type of Technology, , 1940, , 1, , Valves (Vacuum Tubes), , 1950, , 2, , Transistor, , 1960, , 3, , IC (Integrated Circuit) with LSI (Large Scale, Integration), , 1970, , 4, , Microprocessor with VLSI (Very Large Scale, Integration), , Late 1980‟s, , 5, , Hardware and Software technology AI (Artificial, Intelligence), , Hardware: - Hardware refers to the physical components of a computer., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 6
Page 7 :
NIE First Grade College, Mysore, Software: - Software consists of sequence of instructions, in the form of a program to, perform a particular task on a computer., Classification of Computers, A computer can be classified in the following methods:, Computational method, 1. Digital: - A digital computer can count and accept numbers and letters, through various input devices. The input devices convert the data into, electronic pulses and perform arithmetical operations on numbers in discrete, form. In addition to performing arithmetical operations, they are also capable, of:, , , Storing data for processing, , , , Performing logical operations, , , , Editing or deleting the input data, , 2. Analog: - Analog computer process data input in a continuous form. Data, such as voltage, resistance or temperature are represented in the computer as a, continuous, unbroken flow of information, as in engineering and scientific, applications, where quantities to be processed exit as waveforms or, continually rising and falling voltages, pressure and so on., 3. Hybrid: - Computer can also be built using some parts employing digital, computations and some parts based on analog principles. Such computers are, called hybrid computer., Size and capability, 1. Super: - These are the largest and fastest computers available but are, typically not used for commercial data processing. Instead they are used in, specialized areas such as in defense, aircraft design, computer generated, movies, weather research etc. The first super computer was the ILLIAC IV, made by Bur roughs. Other suppliers of supercomputer are CRAY, CDC,, FUJITSU, NEC etc. A supercomputer CRAY-1 is considered the most, powerful computer today. Supercomputers can process 64 bits or more at a, time. Their processing speed ranges from 10.000 million instructions per, sec(MIPS) to 1.2 billion instructions per sec. They can support 10.000, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 7
Page 8 :
NIE First Grade College, Mysore, terminals at a time. They have huge numbers of storage and other devices, connected to them., 2. Mainframe: - Mainframes are less powerful and cheaper than super, computers. However, they are big general purpose computers capable of, handling all kinds of scientific and business applications. Mainframes can, process several million instructions per second. More than 1,000 remote, terminals can be supported by a mainframe. Mainframes have large on-line, secondary storage capacity., 3. Mini: - This type of computer performs data processing activities in the same, way as the mainframe but on a smaller scale. The cost of minis is lower. As, the name, a minicomputer is small compared with a mainframe and may be, called a scaled down mainframe as the processor and the numbers of, peripherals are physically smaller. A mini computer can typically support 10, to 12 terminals. The most popular minicomputers or minis are Nova, Dec,, PDP_II and IBM series., 4. Micro: - This is the smallest category of computers, consisting of a, microprocessor and associated storage and input/output devices. These are, also called personal computer systems. Microcomputers were first available, for widespread use in the 1970‟s, when it becomes possible to put the entire, circuitry of computers (CPU) into a small silicon chip., Functional Units of a Computer, , Memory Unit, , Input Unit, , Control Unit, , Output Unit, , Arithmetic Logic, Unit, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 8
Page 9 :
NIE First Grade College, Mysore, Components of a Computer, Classify the hardware components into the following two types., 1. Central Processing Unit (CPU), 2. Peripheral Devices (Connected to and controlled by the CPU), Central Processing Unit (CPU): - A CPU controls the execution of programs and performs, the calculations. The CPU is also called as the brain of the computer. This is because, execution of any task by a computer is controlled entirely by the CPU. The CPU activities, include ensuring- all instructions for a program are executed and in the proper sequence, the, calculations and logical operations are performed correctly and the instructions and data are, available for successfully executing a task., For executing its job the CPU mainly uses two main interactive components., Arithmetic and Logic Unit (ALU), Control Unit (CU), Arithmetic and Logic Unit: - Arithmetic and logic unit (ALU) does the operations on the, data stored in the memory. This part of the CPU contains a large number of electronic circuits, used to carry out arithmetical and logical computations. These computations are carried out, with the help of special purpose storage locations, called the registers., There are basically three types of registers in an ALU:, 1. Storage registers,, 2. Accumulator,, 3. Arithmetic and logic operation unit., Storage registers: - Temporarily holds data during execution of programs. These are, helpful in getting work done by a computer. For example, suppose data stored in two, locations are needed to be interchanged. Then a third entity is required to hold the data, temporarily. If the two locations are named x and y, then one can temporarily fetch x and, keep the data in z. Then y may be fetched and transferred to x. In the third step, z may be, copied to y. This third entity z may be a third location or a storage register. In a typical, computer, storage register operations are faster than memory operation. That is the reason, why storage registers become handy., DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 9
Page 10 :
NIE First Grade College, Mysore, Accumulator: - Holds the result of the calculations until needed later on. Operations are, mostly carried out in two operands like we say, add x to y. Here x and y are operands. If, in a computer instruction, always two operands are provided, then there will be a, requirement of more number bits to express two operands. Computers are normally, provided with a register called accumulator, so that in all operands this accumulator is, assumed by the ALU as the default location for one of the operands. For example, add x, and y may be specified as load accumulator with x, and y. The accumulator holds x and, the adding of y and x takes place in accumulator. The result is also held in accumulator., Arithmetic and logic operation unit: - Receives the data from two or more sources,, performs the arithmetic or logic operation unit and transfers the result to the accumulator., The adder is an important component in ALU. In any case, a computer performs all, operations (subtraction, multiplication and division) through additions. Subtraction is, done by a complimentary addition (a-b = a+ (-b)), multiplication may be done by repeated, addition and in some cases division may also be done by repeated subtraction., Control Unit: - The control unit contains that portion of the CPU, which controls each, operation while a program is being executed. You must have noticed that many times you, keep a book open with your eyes fixed on it, but you do not read a single word. This is, because the control unit of your brain was not allowing your eyes to give any input at that, time. Possibly the control unit of your brain was processing something else., Control unit synchronizes and sequences operations of the CPU for ensuring correct, execution of programs (sequence of instructions to the computer to perform various tasks). In, other words, this unit acts as the central nervous system for various components of the, computer, without as such performing the actual processing., Control unit has a special register called the program counter, which contains the address of, the next instruction to be fetched from the primary memory. In order to sequence the, instructions, the control unit goes through the following sequence of steps:, , , Retrieve the instruction from the processor memory addressed by the program, counter, , , , Increment program counter, , , , Determine what action is being requested by the instruction, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 10
Page 11 :
NIE First Grade College, Mysore, , , Retrieve the appropriate data from the processor memory, , , , Direct the CPU components to perform the operation indicated by the instruction, , , , Determine if the operation was carried out properly, , , , If not, flag the error message to the user, through the output device, , , , Else, store the result in the CPU memory, for further processing, , , , Determine the location of the next instruction to be retrieved, , Peripheral Devices: - Peripherals are the devices that permit a computer system to, communicate with outside world. The peripheral devices allow the computer to receive data, and instructions from the outside world and give the information to the outside world. These, peripheral devices consist of:, 1. The input devices (accept input data), 2. The external storage devices (stores data), 3. The output devices (displays data), Input Devices: - The input devices are used to input data and instruction. Data and, instructions must be entered into the memory of the computer to perform computation. This, task is carried out by the input devices., Example: keyboard, Mouse, Joystick and tracker ball, scanner, Output Devices: - The job of an output device is to bring out the result of computation to the, outside world. As you already know, the result in computer memory is in binary form. So the, binary values are converted to human acceptable forms, with the help of interface electronics, and the output device., The following functions may be attributed to the output device:, 1. It accepts data in binary form from the computer, which are normally not, understandable by human beings., 2. Converts the coded data to human acceptable form., 3. Outputs the converted result to the outside world., Example: video display unit, printer, plotter, External Storage Devices: - These are several devices used as secondary memory for, computers and they can store and retrieve data in machine-readable forms. These are useful, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 11
Page 12 :
NIE First Grade College, Mysore, for storing results temporarily, or for transporting data to other computers, or for storing data, for a long period of time. The commonly used secondary devices are floppy diskette,, magnetic disk, Hard drive, CD-ROM, DVD ROM, Flash drive etc., Primary Storage Section / Main Memory: - Memory is the storage place where data and, instructions can be stored into, and retrieved from, whenever required by other functional, blocks of a computer., Primary storage section, also called as main memory, is that portion of the computer where, data and instructions get stored when a program is being executed., The main memory is used to:, , , Hold data received from input devices and keep them ready for processing, , , , Hold data being processed and the intermediate results being generated therein, , , , Hold the finished results of processing until released to the output devices, , , , Hold the system software and application software in use, , Units of Storage: - A computer memory is provided with locations where the data can be, stored each memory location is identified by a unique address. The locations store the data in, the form of bits [BIT- Binary Digit (0‟s and 1‟s)]., 8 bits = 1byte, 1 byte x 1024 bits (210) = 1KB (Kilo byte), 1 KB x 1024 bits (220) = 1MB (Mega byte), 1 MB x 1024 bits (230) = 1GB (Giga byte), 1 GB x 1024 bits (240) = 1TB (Tera byte), Memory is broadly classified in two types:, 1. Random Access Memory (RAM), 2. Read Only Memory (ROM), Random Access Memory (RAM), The memory where both reading and writing can take place is called Random Access, Memory (RAM). RAM may be of two types, these are: Static RAM: - Static RAM elements, once set to their values, do not loose them if the if the, power supply does not go off. Once some value is stored, it will remain in the main memory, till the power is on. These elements are costly and have a fast access., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 12
Page 13 :
NIE First Grade College, Mysore, Dynamic RAM: - In Dynamic RAM the memory elements have less retention period and, loose its value unless it is refreshed. Refreshing is a process where the RAM is read and, rewritten. This kind of RAM requires extra circuits for refreshing. These are relatively slow, but less costly compared to static RAMs. This kind of memory is therefore used in mass, scale., Both of these are volatile i.e., the moment power goes off all contents of RAM are lost., Read Only Memory (ROM), There are portions in the computer memory where no writing is allowed. The contents are, pre-written and can only be read. Such memories are called Read Only Memory (ROM). It is, used for micro programs not available to normal programmers. The term read only means, that the storage cannot be altered by regular program instructions., ROM can be classified into 2 types:, Programmable ROM: - PROM are those in which the user can insert the contents of choice, only once. Once the PROM is written, it can only be read and never be rewritten., Erasable Programmable ROM: - EPROM is another kind. As the name suggests, it can be, written many times by a special process. These are very useful for design and development., Speed of Memory: - The fastness of main memory is expressed by memory access time. It is, the time taken by the memory to read from or write in a single location of the memory. Speed, is expressed in nano or micro seconds., Other Memory Elements: - Other than the main memory, there are different memory, elements used in different parts of the computer. They are:, , , Cache, , , , Register, , Cache: - Cache is a very fast memory placed in between the main memory and the CPU., We know that each instruction is to be fetched by CPU from main memory. Main, memory is comparatively slower than cache, so it holds cache whenever CPU refers to, memory. Cache memory acts as a buffer and fetches chunk of contents from main, memory to be used by CPU. Cache memory is very fast and very expensive, so amount of, cache memory in any system is usually much smaller than the main memory., Register: - Registers are temporary storage places and hold data, addresses etc., for doing, operations on them for data transfer. Most of the registers are built inside the CPU., However, other blocks also use registers for their operations. There are many registers, spread through the computer. Some of the most important registers in CPU are Program, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 13
Page 14 :
NIE First Grade College, Mysore, Counter (PC) for storing the address of the current instruction being executed,, accumulator (AC) for storing one of the operands being used and also for storing the, result of the operation., Evolutional of Computer Languages, Language is a means of communication between two people. We can communicate with the, computer using a language called programming language., All computer languages can be classified into following categories:, 1. Low level languages, a. Machine level language, b. Assembly level language, 2. High level languages, a. Specific purpose languages, b. General purpose languages, Machine languages: - Or machine code or „absolute language‟. It is considered as first, generation language., Instructions are written using binary 1‟s and 0‟s (ON and OFF), Computer can directly understand the instructions, It is difficult for the user to read, write, modify, and understand such instructions., An instruction in the machine language has two parts, 1. OPCODE (operation code), 2. OPERAND (address/ location), Operation code denotes the operation such as add, multiply, delete etc. More number, of operations the more powerful is the computer. The power of computer is, determined by the number of operations. The operand code gives the specific location, or address of the data., For example a typical program in machine language to add two numbers may look, like, 0000011100000001111001111, , Load the data, , 1110000001111100000011100, , Add the contents, , 0011111011000000001100000, , Store the result, , 0000000001110000011000110, , Print the result, , 0000000000000000000000000, , Stop, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 14
Page 15 :
NIE First Grade College, Mysore, , Advantages of machine language:, , , Machine language makes efficient use of storage., , , , Instructions are directly understood by the computer and immediately executed. There, is no need for translators., , , , Instructions can be used to manipulate the individual bits in a byte of computer, storage., , Disadvantages of machine language:, , , They are machine dependent. (program written on one machine cannot be run on, another as the op-code is different for different computers), , , , It is difficult to remember the operation codes for all operations and difficult to, remember the address of data and instructions., , , , It is difficult to check for errors, correct or modify the written program., , Assembly language: Or Symbolic language Or the second generation languages., Instructions are written using mnemonics/symbols/codes., Computer cannot understand these instructions; a translator called „Assembler’ is, used. Assembler is system software. It translates the assembly code to machine code, and also assembles the machine code into, main memory of the computer execution., A typical program in assembly language to add two numbers may look like., STA, , A, , Load the data to accumulator, , ADD, , B, , Add contents of B to accumulator, , STR, , C, , Store the results in location c, , PRT, , C, , Print the results, , HLT, , Stop, , Advantages of Assembly language, , , It is not required to remember the op-codes and operand addresses., , , , Easier to read, write, understand, modify and debug the instructions., , , , Programs can be written with fewer instructions., , Disadvantages of assembly language:, , , Programs are machine dependent., , , , Computer needs „assembler‟ for translation., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 15
Page 16 :
NIE First Grade College, Mysore, High level languages:, Instructions are written using English words and mathematical symbols., Computer can understand high level language instructions using the translatorcompiler/interpreter., A program in high level language to add two numbers may look like, INPUT A, B, C=A+B, OUTPUT C, END, Advantages of high level language:, , , Machine independent : A high level language program written on one machine can be, run on any machine without any modifications in the program, , , , Easy to learn and use: Programs are written using familiar English words and, mathematical symbols. It is easy to read, write, understand, modify and correct errors, in programs., , , , Better documentation: Documentation is writing explanation about the program in the, form of comments and remarks. High level languages are self documenting., , , , Writing a program in high level language does not require the knowledge of the, internal structure of the computer or any machine instructions. The programmer need, not learn anything about the computer he is using. No need of thinking about how to, store data, where to store them and what to do with them., , Disadvantages of high level languages:, , , Lack of flexibility: An assembly language provides access to all the special features, of the machine. Certain machine level operations can be easily performed in assembly, language which is impossible in high level language. Automatic features of the high, level languages are not under the control of the programmer, they are less flexible, than assembly languages., , , , Slower execution / lower efficiency: Execution is slow due to generality of the, statements. Programs in high level languages take more time to run and require more, main storage., , , , Requires a translator or compiler: High level language instructions can be understood, by the computer using the translator like compiler or interpreter. These translators, occupy space in memory., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 16
Page 17 :
NIE First Grade College, Mysore, Classification of Higher level languages:, General purpose languages: These are used in teaching, training business, art,, science etc., Example: BASIC (Beginners All Purpose Symbolic Instruction Code), Pascal (Named after French mathematician Blaise Pascal), C (Next version of BCPL-Basic compiled Programming Language), Specific purpose languages: These are used only in particular applications, Example: COBOL (Common Business Oriented Language)- used in business, FORTRAN (FORmula TRANslation) – used in scientific applications, C++ (New version of c) - used in Object Oriented Programming, JAVA- Used in Internet Programming., , Compiler: - A Compiler converts human readable instructions into computer readable, instructions one time. It takes longer as it rearranges or optimizes the object code., , Interpreter: - An interpreter converts human instructions into machine instructions each, time the program is run. An interpreter starts interpreting each instruction immediately and, produces result more quickly but is slower overall., , Compiler V/S Interpreter, Compiler takes entire program as input, , Interpreter takes single instruction as, input, , Intermediate object code is generated, Conditional, , control, , statements, , No intermediate object code generated, are Conditional, , control, , statements, , are, , executes faster, , executes slower, , Memory requirement more, , Memory requirement less, , Program need not be compiled every time, , Every time higher level program is, converted into lower level program, , Errors are displayed after entire program Errors are displayed for every instruction, is checked., , interpreted (if), , Ex: c compiler, , Eg: BASIC, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 17
Page 18 :
NIE First Grade College, Mysore, Unit 2:, , INTRODUCTION TO C LANGUAGE, C is a programming language developed at AT & T‟s Bell laboratories of USA in 1972. It, was developed by Dennis Ritchie., Characteristics of C:, C is a general purpose programming language., It is a structured programming language (It allows modularization process of dividing, problems into sub-problems and C has structured statements like sequence, selection, and iteration), C is a middle level language (C is a high level language but also incorporates features, of low-level languages like manipulation of bits, bytes, words and addresses.), Helps in development of system software ( C is used for writing application programs, and since it has low level languages features it can be used in development of system, software), Has rich set of operators and data types and built-in functions., Provides compact representation for expressions. This makes the language simple,, orderly and easy to learn., No rigid format. Any number of statements can be typed in a single line., Portability: any C program can be run on different machines with little or no, modifications., Less number of reserved words, Pointer arithmetic and pointer manipulation, Ability to extend itself by adding functions to its library., , History of C:, year, , Language, , Developed by, , Remarks, , 1960, , ALGOL, , International committee, , Too general, to abstract, , 1963, , CPL, , Cambridge, , Difficult to learn and implement, , University(CU), 1967, , BCPL, , Martin Richards at CU, , Could deal with only specific problems, , 1970, , B, , Ken Thomson at AT & T, , Could deal with only specific problems, , 1972, , C, , Dennis Ritchie at, , Restored the lost generality of BCPL, , AT & T, , and B, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 18
Page 19 :
NIE First Grade College, Mysore, Applications of C: Because of its portability and efficiency, C is used to develop the, system as well as application software. Some important system programs include operating, systems, compilers, interpreters, assemblers, editors, linkers and loaders., Being a structured language, it is useful in developing application programs like database, systems, word processors, spreadsheets, graphics packages, CAD/CAM applications, office, automation tools, scientific and engineering applications, animation and games., , Basic structure of a C program or Syntax:, Every C program includes the following components, Pre-processor directives, Main(), A pair of flower brackets { }, Declaration and statements, User created sub-programs or functions., Pre-processor directives, Global declarations;, Main (), {, Declarations;, Statements;, }, User created sub-programs or functions, , Pre-processor directives: these statements begin with # symbol. They direct the C preprocessor to include header files and symbolic constants into a C program., E.g.: #include<stdio.h>, , : For the standard input, output function, , #include<conio.h>, , : For the Console input, output function, , # define NULL 0, , : For defining symbolic constant, NULL=0, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 19
Page 20 :
NIE First Grade College, Mysore, Global declarations: Variables or functions whose existence is known in the main (), function and other user defined functions, are called the global variables or functions. Their, declarations should be made before main ()., Main (): This is the main function of every C program. Execution of a C program starts with, Main (). No C program is executed without the main () function. It should be written in, lowercase letters and should not be terminated with semicolon. It calls other library functions, and user defined functions. There must be one and only one main () function in any C, program., A pair of flower brackets: The flower brackets indicate body of the program, which, includes instructions to perform the required task. { indicates beginning of the main (), function and } indicates end of the main() function., Declarations: It is the part where all the variables, arrays, functions etc., used in the C, program are declared and may be initialized with their basic data types., Statements: These are instructions to perform certain operations like input, output,, assignment, arithmetic statements, control statements and other statements. They also include, comments. Comments are explanatory notes on some instructions. The statements to be, commented must be enclosed within /* and */. The comment lines are not compiled and, executed., User created sub-programs or functions: These are sub-programs created by the user to, perform certain common functions. They may be written before or after main ()., Example:, /* C program to display hello world */, #include<stdio.h>, #include<conio.h>, void main(), {, printf(“\n HELLO WORLD”);, getch();, }, Output:, HELLO WORLD, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 20
Page 21 :
NIE First Grade College, Mysore, C PROGRAMMING PRELIMINARIES, CHARACTER SET:, Alphabets, , Uppercase letters, , A to Z, , Lowercase letters, , a to z, , Digits, , 0 to 9, , Special Characters, , blank , ; : “ + - * / { } ? ! # _= | ^ ~ < > \ () []@...etc., , IDENTIFIERS: These are names given to program elements like variables, arrays, functions, and structures. Basically identifiers are the sequence of alphabets and digits., Rules for forming identifier names:, 1. The first character must be an alphabet (upper or lowercase) or an underscore., 2. All succeeding characters must be either letters or digits but no other special, character or punctuation symbols allowed., 3. Uppercase and lowercase identifiers are different in C. (E.g.: SUM, sum and, sum are different identifiers.), 4. No two successive underscores are allowed., 5. Keywords should not be used as identifiers., 6. Identifiers should be single words. That is, blank spaces cannot be included in, identifiers., E.g.: valid identifiers: - sum, emp_name, stu_address, number, age, Invalid identifiers: - father‟s-name, while, @total, do-it, 3by2., VARIABLES:, An identifier/ quantity that change its value during program execution are called, „variable‟. A variable is an object or element that may take on any value of a specified type., Variables represent named storage locations, whose value can be manipulated during, program execution., E.g.:- sum, area, m1, length, sname, age, city etc., Rules for naming a variable – same as rules for forming an identifier name, Valid variables, Marks, TOTAL_MARK, Gross_salary_2004, Area_of_circle, Num[20], DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Invalid variables, 8ab, TOTAL-MARK, Gross-salary-2004, Area-of-circle, Num(20), Page 21
Page 22 :
NIE First Grade College, Mysore, CONSTANTS: It refers to fixed values that do not change during the execution of the, program. C supports several types of constants., 1. Numeric Constants, a. Integer constant, b. Float (real) constant, 2. Character constants, a. Single character constants, b. String constants, 3. Symbolic constants, 4. Backslash constants, 1. Numeric Constants, a. Integer constants: All whole numbers are integer constants. They are, sequence of digits without decimal point, E.g.: Decimal constants, : 134, 9000, 3567, -987, Octal constant, : 06, 034, 0677, -07867, Hexadecimal constant : 0x20, 0xA, 0x1AB, b. Float (Real) constant: Numbers having decimal point are floating point, constants. They can contain both an integer part and a fractional part in the, number. They are stored differently from integers. They may be represented, either in decimal form or in the exponent form., E.g.: Valid decimal constants: - 18.5, .18, 5. , -25.67, Valid exponent constants: - 5.3E-5, -6.79E3, 34e-8, Here the number before „E‟ / „e‟ is called mantissa and, mantissa can be either real or integer, the number after „E‟/‟e‟ is called, exponent and exponent should be an integer., 2. Character constants, a. Single character: It is a letter or any symbol enclosed in single quotes., Character constants can be used in assignment statements or in symbolic, constant definitions., E.g.: ch=‟h‟ ;, #define PERIOD „.‟, b. String constant: A sequence of characters enclosed between double, quotes is called string constant., E.g.: “C programming is fun”, “Enter two numbers”, 3. Symbolic constants, It is a name that substitutes a numeric, character or a string constant., E.g.: #define PI 3.1415 (Here we substitute PI for numeric constant), #define PLACE “MYSORE”, #define FOUND 1, #define NUM 023 /* indicates octal number */, #define VALUE 0x20 /*0x indicates hexadecimal */, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 22
Page 23 :
NIE First Grade College, Mysore, 4. Backslash constant, They are also called „escape sequences‟ and are used in the output statements. A, backslash constant is a combination of two characters in which the first character is, always the backslash (\) and the second character can be any one of a, b, f, n, r, t, v., Backslash constant, Meaning, „\a‟, System alarm, „\b‟, Back space, „\f‟, Form feed, „\n‟, New line, „\r‟, Carriage return, „\t‟, Horizontal tab, „\v‟, Vertical tab, „\”‟, Double quote, „\‟‟, Single quote, „\0‟, Null character, „\\‟, Back slash character, KEYWORDS (Reserved words): These are predefined words that have special meaning, and these meanings cannot be changed. They can be used only for the purpose for which they, have been defined. All keywords must be written in lowercase letters., Example:, auto, , double, , int, , struct, , break, , else, , long, , static, , case, , enum, , register, , switch, , char, , extern, , return, , typedef, , const, , float, , short, , union, , continue, , for, , signed, , unsigned, , default, , goto, , sizeof, , void, , do, , if, , while, , volatile, , DATA TYPES:, Data type indicates the type of data a variable can have. Data type defines set of, values, which can be stored in the variable along with certain operations that may be, performed on those values., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 23
Page 24 :
NIE First Grade College, Mysore, There are three classes of data types, Primary (or fundamental) data types:- int, float, char, double, Derived data types:- arrays, functions, structures, pointers, User-defined data types:- typedef, enum, Primary Data types:, int: Means that the variable is an integer. An integer needs two bytes of space. Range of, values that can be stored in two bytes is -32768 to +32767. The operations that can be, performed on an integer value are addition, subtraction, multiplication, division and, remainder., char: Means that the variable is a character. A character needs one byte of storage space. If, unsigned, the range of values is 0 to 255. The possible operations are input and output., float: Means that the variable is a real number. Four bytes or 32 bits are allocated in memory,, this includes 7 significant digits after the decimal point. The range of values is 3.4E-38 to, 3.4E+38., double: Means that that variable is a double precision float type. Eight bytes or 64 bits of, storage space and range of values is 1.7E-308 to 1.7E+308., Void: the void type has no values. This is usually used to specify the type of functions. The, type of a function is said to be void when it does not return any value to the calling function., Size and Range of data types, Type, Char or signed char, Unsigned char, int or signed int, Unsigned int, Short int or signed short int, Unsigned short int, Long int or signed long int, , Size (bits), 8 (1 byte), 8 (1 byte), 16 (2 bytes), 16 (2 bytes), 8 (1 byte), 8 (1 byte), 32 (4 bytes), , Unsigned long int, float, double, Long double, , 32 (4 bytes), 32 (4 bytes), 64 (8 bytes), 80 (10 bytes), , Range, -128 to 127, 0 to 255, -32,768 to 32,767, 0 to 65535, -128 to 127, 0 to 255, -2,147,483,648, 2,147,483,647, 0 to 4,294,967,295, 3.4E-38 to 3.4E+38, 1.7E-308 to 1.7E+308, 3.4E-4932 to 1.1E+4932, , to, , Declaration (definition) of variables:, Syntax: data_type variable list;, Variables must be separated by comma and declaration statement must end with a semicolon., Example: int a, b, c; float sum, average;, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 24
Page 25 :
NIE First Grade College, Mysore, Assigning values to variables:, Method 1: values can be assigned to variables at the time of declaration, E.g.: int sum=0;, float val=3.14159;, char ans=‟y‟;, Method 2: values can be assigned using an assignment statement, E.g.: sum=0;, Val=3.14159;, Ans=‟y‟;, Example: C program to compute area and circumference of circle, #include<stdio.h>, #include<conio.h>, #define PI 3.1415, void main(), {, int r;, float a, c;, clrscr();, printf(“enter the radius of the circle\n”);, scanf(“%d”,&r);, a=PI*r*r;, c=2*PI*r;, printf(“area of the circle=%f\n”,a);, printf(“circumference=%f\n”,c);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 25
Page 27 :
NIE First Grade College, Mysore, STORAGE CLASS, This class of variables provides information about the scope of the variable and how, long a variable retains its value., Four Storage class specifiers, 1. auto: - Local variable known only to the function in which it is declared., Note:, default is auto, The variable is limited to only the function in which it has been defined., Declared inside the function., They are created when the function is called and destroyed automatically, when the function is exited., Undefined variable values it will take garbage value, Example:, #include<stdio.h>, void main(), {, auto int count=10;, clrscr();, printf("%d\n",count);, getch();, }, Output:, , 2. Static:- Local variable which exists and retains its value even after the control is, transferred to the calling function., Note:, Declared within a function, Static variable is initialized only once, Same as that of automatic variables., All static variables are automatically initialized to zero‟s, Only constants should be used to initialize, Example:, #include<stdio.h>, #include<conio.h>, void main(), {, static int sn;, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 27
Page 28 :
NIE First Grade College, Mysore, clrscr();, sn=sn+23;, printf("%d",sn);, getch();, }, Output:, , 3. Extern: - Global variable known to all functions in the file., Note:, Declared outside the function, This is both alive and active throughout the entire program., Automatically initialized to zero., Example:, #include<stdio.h>, extern int first=10,last=20;, int main(), {, clrscr();, printf("%d\n%d",first,last);, getch();, return 0;, }, Output:, , 4. Register: - Local variable which is stored in the register., Note:, Faster than a memory access., Faster execution of programs, Undefined variable values it will take garbage value, Example:, #include<stdio.h>, #include<conio.h>, void main(), {, register char ch='A';, clrscr();, printf("%c Stored in register",ch);, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 28
Page 29 :
NIE First Grade College, Mysore, getch();, }, Output:, , INPUT-OUTPUT STATEMENTS, C is a functional programming language. To perform input-output operations C, provides a library of functions. This library is called a standard input-output library. It is, denoted by stdio. The header file containing such library functions is called stdio.h, Some of the standard I-O functions in C are, et, , 1., 2., 3., 4., , scanf(), printf(), getchar(), putchar(), , 5. gets(), 6. puts(), 7. getch(), 8. getche(), , There are two types of input-output statements, 1. Formatted I/O statements, 2. Unformatted I/O statements, Formatted, Unformatted, , Input statements, scanf(), getchar() getche() getch(), gets(), , Output statements, printf(), putchar() puts(), , FORMATTED I/O STATEMENTS:, They allow the input read from the keyboard or the output displayed on VDU to be, formatted as per our requirements i.e., where this output will appear on screen, how many, spaces between two values, number of decimal places etc. Can be controlled using formatted, I/O statements., FORMATTED INPUT:, scanf() statement is used to input the numeric, character and string type of data., Syntax:- scanf(“control string”, address_list);, Example:- scanf(“%d%d”,&a,&b);, scanf(“%c%d%f”,&ch,&a,&r);, % indicates that a conversion specification., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 29
Page 30 :
NIE First Grade College, Mysore, Control String, %c, %d, %e or %f or %g, %h, %I, %o, %p, %s, %u, %x, , Meaning, Read a single character, Read a decimal integer, Read a floating-point number, Read a short int, Read a decimal or hexadecimal or octal number, Read on octal number, Read a pointer, Read a string, Read an unsigned integer, Read a hexadecimal number, , FORMATTED OUTPUT:, C provides the printf() function to display the data on the monitor., Syntax:, E.g.:, , printf(“control string”, varlist);, printf(“%d”,num);, printf(“ result=%f\n”,res);, printf(“ area=%6.2f, circumference=%6.2f\n “,ar,ci);, , Format specifiers for integers:, printf(“%d”,6789);, 6, , 7, , 8, , 9, , 1, , 2, , printf(“%8d”,1239);, 3, , 9, , printf(“%-8d”,1239);, 1, , 2, , 3, , 9, , printf(“%08d”,1239);, 0 0 0 0 1 2 3 9, Format specifiers for floating point numbers:, printf(“%f”,num);, 1 2 3 4 ., 6 7 8 0 0 0, printf(“%10.2f”,num);, 1 2 3 4 ., 6 8, printf(“%-10.2f”,num);, 1 2 3 4 ., 6 8, printf(“%10.2e”,num);, 1 ., 2 3 E + 0 3, Format specifiers for characters:, printf(“%c”,”A”);, A, printf(“%4c”,”A”);, A, printf(“%-4c”,”A”);, A, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 30
Page 32 :
NIE First Grade College, Mysore, gets() function: This function reads in everything you enter from the keyboard until the, ENTER key is pressed i.e., it reads a string of all printable ASCII characters., Syntax:, , gets(string);, , UNFORMATTED OUTPUT:, These statements are mainly concerned with displaying or printing the character type, data on the monitor., putchar() function:- This function prints a single character on the screen., Syntax:, , putchar(ch_var);, , puts() function:- This function prints a string of characters on screen., Syntax:, , puts(string);, , Example 1:, #include<stdio.h>, #include<conio.h>, void main(), {, char letter;, clrscr();, letter=getchar();, putchar(letter);, getch();, }, Output:, , Example 2:, #include<stdio.h>, #include<conio.h>, void main(), {, char mesg[20];, clrscr();, printf(“enter the message to be displayed\n”);, gets(mesg);, puts(mesg);, getch();, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 32
Page 33 :
NIE First Grade College, Mysore, Output:, , All data transfer operations in C are carried out using functions available in the, standard library. These functions are known as the standard I/O library. These operations can, be classified into two types., i., Buffered Input/output, ii., Unbuffered Input/output, Buffered Input:, Buffer is a temporary storage in the memory. The characters entered at the keyboard, are stored in the buffer until the ENTER key is pressed and then made available to the, program as a block of characters., Input-output operations take less time on a buffered system., If any mistake is done while entering the data before ENTER key is pressed, can be, corrected., E.g.: scanf() and getchar() are buffered input function., Unbuffered Input:, Here, the character which is entered at the keyboard is made available to the program, immediately. It is useful in some interactive programs and to read and write binary data., E.g.: getch() and getche() are unbuffered input function., STANDARD MATHEMATICAL FUNCTIONS, Mathematical functions such as cos, sqrt, log, etc, are frequently used in analysis of, real life problems. Most of the C compilers support these basic math, functions[#include<math.h>]., Note : x and y should be declared as double., Function, acos(x), asin(x), atan(x), atan2(x,y), cos(x), sin(x), tan(x), cosh(x), sinh(x), tanh(x), ceil(x), exp(x), fabs(), , Meaning, Arc cosine of x, Arc sine of x, Arc tangent of x, Arc tangent of x/y, Cosine of x, Sine of x, Tangent of x, Hyperbolic cosine of x, Hyperbolic sine of x, Hyperbolic tangent of x, X rounded up to the nearest integer, E to the x power (ex), Absolute value of x, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 33
Page 34 :
NIE First Grade College, Mysore, floor(x), fmod(), log(x), log 10(x), pow(x,y), sqrt(x), , X rounded down to the nearest integer, Remainder of x/y, Natural log of x, x>0, Base 10 log of x, x>0, X to the power y (xy), Square root of x, x>0, , Example:, #include<stdio.h>, #include<conio.h>, #include<math.h>, void main(), {, int x,y,p,z;, clrscr();, printf("enter x value\n");, scanf("%d",&x);, printf(“enter power\n”);, scanf(“%d”,&p), y=sqrt(x);, z=pow(x,p);, printf("\n %d square root is=%d",x,y);, printf("\n %d power of %d=%d",x,p,z);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 34
Page 35 :
NIE First Grade College, Mysore, OPERATORS AND EXPRESSIONS, OPERATORS:, Operators are tools for manipulating data. Data items on which operators act are, called operands. Some operators act on only one operand. Such operators are called unary, operators. Similarly binary and ternary operators are there depending on the number of, operands on which they act., Operators in C, Arithmetic operators, Assignment operator, Relational operators, Logical operators, Conditional operators, Bitwise operators, Special operators, a. Arithmetic operators:, They are used to perform numerical manipulations in C., Binary arithmetic operators, OPERATOR, PURPOSE, +, Addition, Subtraction, *, Multiplication, /, Division, %, Remainder of division, E.g.: sum=num1+num2;, Val=a-b-c;, Unary arithmetic operators, OPERATOR, PURPOSE, Unary minus, ++, Increment, -Decrement, E.g.: value=-6;, Z=-x+y;, Num=++i;, ++int_var indicates pre increment. That is, the value of int_var must be incremented before it, is used (increment and use), int_var++ indicates post increment. That is, use the value of int_var first and then increment, it (use and increment)., For example, a=++b;, This is equal to, b=b+1;, a=b;, Similarly,, a=b++;, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 35
Page 36 :
NIE First Grade College, Mysore, This is equal to, a=b;, b=b+1;, b. Assignment operator:, It is used to assign value to an identifier., Syntax: variable=value or expression;, E.g.: num=20;, C allows users to combine assignment operators with arithmetic operators. Such, operators are called as compound assignment operators/ shorthand assignment operator., Let num1=10, num2=13, f1=7.8 and f2=4.2, Assignment statement, Equivalent, Result, Num1=num1+50;, Num1+=50;, 60, Num1=num1*2;, num1*=2;, 20, num2=num2*10+20;, num2*=10+20;, 150, f1=f1/1.3;, f1/=1.3;, 6.0, num2=num2%5;, num2%=5;, 3, f1=f2+f1;, f2+=f1;, 12.0, c. Relational operators:, They are used to relate two quantities in conditional statements (if -statement), Relational operator, Meaning, ==, Equal to, !=, Not equal to, <, Less than, <=, Less than or equal to, >, Greater than, >=, Greater than or equal to, E.g.: if x=5, y=2 and z=0;, Then x > y + z evaluates to 5>2+0=1(true), x + z <= y evaluates to 5+0<=2=0(false), Differences between = and == signs, == is a relational operator, = is an assignment operator, == Sign does not change the value of the identifier, it only checks if one value is, equal to another value and gives the answer true or false, = sign assigns the value of the identifier on its left., d. Logical operators:, The logical operators && and || are used when we want to test more than one, condition and make decisions., Operator, Meaning, &&, Logical AND, ||, Logical OR, !, Logical NOT, E.g.: if (age>55 && salary<1000), DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 36
Page 37 :
NIE First Grade College, Mysore, if (number<0|| number>100), if(num!=0), e. Conditional operators:, It is also called ternary operator, as it operates on three operands., Syntax: result=exp1? exp2:exp3;, E.g.1: c=a<b? a: b;, That is,, If a<b, c=a;, else, c=b;, E.g.2: C program to find biggest of two numbers., #include<stdio.h>, #include<conio.h>, void main(), {, int a,b,big;, clrscr();, printf(“\n enter two numbers”);, scanf(“ %d%d”,&a,&b);, printf(“%d,%d\n”,a,b);, big=a>b?a:b;, printf(“\n bigger is %d\n”,big);, getch();, }, Output:, , f. Bitwise operators:, All data are stored in the computer as a sequence of bits (0‟s and 1‟s), and some, applications need the manipulation of these bits. Manipulation of individual bits is possible in, machine and assembly languages. But c provides operators to manipulate bits. Bitwise, operators can be applied only on integers and characters but not on float., Operator, &, |, ^, , Symbol name, Ampersand, Pipeline, Caret, , Meaning, Bitwise AND, Bitwise OR, Exclusive-OR (XOR), , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 37
Page 38 :
NIE First Grade College, Mysore, ~, <<, >>, , Tilde, Double less than, Double greater than, , 1‟s complement, Left shifting of bits, Right shifting of bits, , For an 4-bit binary representation of numbers, Decimal, Binary, Number, 0, 0000, 1, 0001, 2, 0010, 3, 0011, 4, 0100, 5, 0101, 6, 0110, 7, 0111, 8, 1000, 9, 1001, 10, 1010, For example consider a=4, b=3, 4(10)=0100(2) and 3(10)=0011(2), The result of bitwise AND of a and b, The result of bitwise OR of a and b, a=0100, a=0100, b=0011, b=0011, a&b =0000, a|b=0111, The result of bitwise Exclusive-OR, a=0100, b=0011, a^b =0111 ( XOR gives output 1 if bits are different (1 and 0), if bits are same i.e., either, 0 and 0 or 1 and 1 it gives output 0.), The result of 1‟s complement, C = ~a, C = ~ (0100), =1011, Left and right shift operators., Syntax: <variable><shift operator><number of bits to be shifted>, Ex: Right shift operator, Left shift operator, num=110011110 then, ch=11010111 then, num>>1 gives 011001111, ch<<1 gives 10101110, num>>3 gives 000110011, ch<<3 gives 10111000, num>>5 gives 000001100, ch<<5 gives 11100000, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 38
Page 39 :
NIE First Grade College, Mysore, Example: C program to illustrate bitwise operators., #include<stdio.h>, #include<conio.h>, void main(), {, unsigned int x,y;, clrscr();, x=128; y=32;, x=x>>1;, printf(“\n After right shifting by 1,x=%d”,x);, y=y<<2;, printf(“\n After left shifting by 2,y=%d”,y);, getch();, }, Output:, , 27, , 21, , 20, , 4, 0, 0, , 2, 0, 0, , 1, 0, 0, , The result after shifting the bits, X= 0, 1, 0, 0, 0 0, , 0, , 0, , Y= 1, , 0, , 0, , 128, X= 1, Y= 0, , 26, , 25, , 24, , 23 22, , 64, 0, 1, , 32, 0, 0, , 16, 0, 0, , 8, 0, 0, , 0, , 0, , 0, , 0, , 0, , g. Special operators:, C supports the following special operators., 1), 2), 3), 4), , Comma operator, Sizeof() operator, Pointer operators-> * dereferencing operator, & address operator, Member selection operators-> dot (.) operator, -> arrow operator, , Comma operator: It is basically associated with for statement. It is used to link the, related expressions together, it is used as statement separator to simplify some code., Ex 1: sum=(a=10, b=15, a+b);, 2) b=(a=20, a+10);, Equal to: a=10;, equal to:, b=15;, a=20;, sum=a+b;, b=a+10;, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 39
Page 41 :
NIE First Grade College, Mysore, EXPRESSIONS:, An expression in c consists of a syntactically valid combination of operators and, operands that computes a value., E.g.: 2+5*10 here + and * are operators and 2, 5 and 10 are operands., An expression in c can be of the following types., a. Arithmetic expression, b. Relational expression, c. Logical expression, Arithmetic expression: An expression that use arithmetic operators along with numeric or, character operands is called arithmetic expression., i., Integer mode expressions: These are formed using integer type constants, variables,, functions and operators., Operator, Expression, Result, +, 10+3, 13, 10-3, 7, *, 10*3, 30, /, 10/3, 3, %, 10%3, 1, ii., , Real mode expressions: These are formed using real mode quantities constants,, variables functions and operators., Operators, Expression, Result, +, 1.5+6.7, 8.2, 6.7-1.5, 5.2, *, 1.5*6.3, 9.45, /, 6.4/3.2, 2, , iii., , Mixed mode expressions: C permits mixing of integer and real quantities in an, expression., Expression, Result, 1.5*10+6.7, 21.7, 7%5+10.0*10/4, 27.0, , Relational Expression: A meaningful combination of operands and relational operators., Operator, ==, !=, <, <=, >, >=, , Expression, 7==8, 4/3!=7-5, 8<19, 3*3<=3*4, 9>23, 3*2>=3*4, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Result, false, True, True, True, False, False, , Page 41
Page 42 :
NIE First Grade College, Mysore, Logical Expression: The expression that result into 1 (true) or 0 (false) are called logical, expressions they use logical operators., Operator, !, &&, ||, , Meaning, negation, AND, OR, , Value, Num=3, m=69, ch=‟h‟, , Expression, !num, (m>=35)&&(m<=100), (ch>=‟a‟ || ch<=‟z‟), , Result, False, True, true, , TYPE CONVERSIONS:, C can perform conversion between different data types, but a programmer should take, care with these conversions., i., Implicit type conversion, ii., Explicit type conversion, i., Implicit type conversion:, When we perform arithmetic manipulation on operands belonging to different, data types, they may undergo type conversion automatically before evaluating the, final value., Example 1:, #include<stdio.h>, #include<conio.h>, void main(), {, int a=5;, float b;, clrscr();, b=a;, printf("\n the value of a=%f",b);, getch();, }, Output:, , Example 2:, #include<stdio.h>, #include<conio.h>, void main(), {, int a;, float b=45.67;, clrscr();, a=b;, printf("\n the value of a=%d",a);, getch();, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 42
Page 43 :
NIE First Grade College, Mysore, }, Output:, , ii., , Explicit Conversion (Type casting):, An explicit type conversion is user-defined that forces an expression to be of, specific type. Variable may be converted explicitly by type casting., Example:, #include<stdio.h>, #include<conio.h>, void main(), {, int a=5;, float x;, clrscr();, x=(float)a;, printf("\n the value of x=%f",x);, getch();, }, Output:, , Evaluation of Arithmetic expression:, The operators in C are evaluated in a specific order. This is known as precedence, (hierarchy) of operators., Precedence Level, Operators, Associativity, 1, ( ), Left to right, 2, ++, -Left to right, 3, % * /, Left to right, 4, + Left to right, BODMAS Rule:, Brackets will have the first precedence, Of operator will have the second precedence, Division operator will have the third precedence, Multiplication operator will have the fourth precedence, Addition operator will have the fifth precedence, Subtraction operator will have the sixth precedence, Example 1: 6*(2+3)/5, =6*5/5, =6*1, =6, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 43
Page 44 :
NIE First Grade College, Mysore, Example 2: x=a-b/3+c*2-1 let a=9, b=12 and c=3, X=9-12/3+3*2-1, =9-4+3*2-1, =9-4+6-1, =5+6-1, =11-1, =10, Example 3: C program to illustrate the use of variables in expressions and their, evaluation., #include<stdio.h>, #include<conio.h>, void main(), {, float a,b,c,x,y,z;, clrscr();, a=9; b=12; c=3;, x=a-b/3+c*2-1;, y=a-b/(3+c)*(2-1);, z=a-(b/(3+c)*2)-1;, printf(“x=%f\n”,x);, printf(“y=%f\n”,y);, printf(“z=%f\n”,z);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 44
Page 45 :
NIE First Grade College, Mysore, CONTROL STRUCTURE, Structured high level languages such as C contain statements that can alter the flow of, a sequence of instructions. These statements are called as control statements., There 3 types of statements, A. Selection statement, B. Looping statement, Conditional control statements, c, C. Jumping statement, Unconditional control statements, o, Selection statement:, It is the ability of a programming language to allow the user to decide on the, execution of a certain set of statements based on a requirement or condition. These constructs, are also called conditional constructs., They are used to indicate decision in a program, Selection structure can be used to implement the following statements, 1) Simple-if, 2) if-else 3) Nested-if, 4) if- else if, 5) switch, 1. Simple-if:, The if statement is the simplest form of selection statement. It is very frequently used, in decision making and altering the flow of program execution., Syntax: if (test condition), Statement;, Action: 1. Test condition is checked., 2. if test condition true, statement is executed, Example: C program to print bigger of two numbers, #include<stdio.h>, #include<conio.h>, void main(), {, int a,b,big;, clrscr();, printf(“\n Enter two numbers”);, scanf(“%d%d”,&a,&b);, big=a;, if(b>big) big=b;, printf(“bigger of %d and %d is=%d\n”,a,b,big);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 45
Page 46 :
NIE First Grade College, Mysore, 2. If-else:, Syntax: if (test condition), Statement A;, else, Statement B;, Action: 1. Test condition is checked., 2. If test condition is true, statement A is executed., 3. If test condition is false A is skipped, statement B is executed., Example: C program to check the given number is even or Odd., #include<stdio.h>, #include<conio.h>, void main(), {, int num;, clrscr();, printf(“\n Enter a number”);, scanf(“%d”,&num);, if(num%2==0), printf(“\n Number is Even”);, else, printf(“\n Number is Odd”);, getch();, }, Output:, , 3. Nested-if:, The if statement may itself contain another if statement is known as nested if., Syntax: if (test condition 1), if (test condition 2), Statement A;, else, Statement B;, else, if (test condition 3), Statement C;, else, Statement D;, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 46
Page 47 :
NIE First Grade College, Mysore, Action: 1. Test condition 1 is checked., 2. If condition 1 is true, condition 2 is checked. If condition 2 is true,, statement A is executed if condition 2 is false, statement B is executed., 3. If condition 1 is false, condition 3 is checked. If condition 3 is true,, statement C is executed if condition 3 is false, statement D is executed., Example: C program to find the biggest of three numbers., #include<stdio.h>, #include<conio.h>, void main(), {, int a,b,c,big;, clrscr();, printf(“\n Enter 3 numbers”);, scanf(“%d%d%d”,&a,&b,&c);, if(a>b), if(a>c), big=a;, else, big=c;, else, if(b>c), big=b;, else, big=c;, printf(“biggest of %d, %d and %d is %d\n”,a,b,c,big);, getch();, }, Output:, , 4. If else-if:, Syntax: if (test condition 1), Statement A;, else if (test condition 2), Statement B;, else if (test condition 3), Statement C;, else, Statement D;, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 47
Page 48 :
NIE First Grade College, Mysore, Action: 1. Test condition 1 is checked, if it is true A is executed., 2. if condition 1 is false, condition 2 is checked, if condition 2 is true B is, executed., 3. if condition 2 is false, condition 3 is checked, if condition 3 is true C is, executed., 4. if all the conditions are false, statement D is executed., Example: C Program to find the grade of the student marks., #include<stdio.h>, #include<conio.h>, void main(), {, int marks;, clrscr();, printf(“\n Enter marks”);, scanf(“%d”,&marks);, if(marks<35), printf(“fail”);, else if(marks<50), printf(“pass class”);, else if(marks<60), printf(“second class”);, else if(marks<70), printf(“first class”);, else, printf(“Distinction”);, getch();, }, Output:, , 5. Switch: (Multiple-selection statement), Syntax:, Switch (control expression), {, Case value 1: {statement A;, Break;, }, Case value 2: {Statement B;, Break;, }, -------------------, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 48
Page 49 :
NIE First Grade College, Mysore, Case value n :{ statement C;, Break;, }, Default: {default statement;, }, }, Action: 1. Control expression may be integer or character. This is compared with the, case value 1, case value 2 etc in the given order., 2. If control expression=case value 1 then statement A is executed., 3. If control expression= case value 2 then statement B is executed., 4. If control expression is not equal to any of the case values 1,2,3,...n then, default statement is executed., Example: C program to perform arithmetic operations., #include<stdio.h>, #include<conio.h>, #include<stdlib.h>, void main(), {, int a,b,c,ch;, clrscr();, printf("\n enter two numbers");, scanf("%d%d",&a,&b);, printf("1.add\n2.sub\n3.mul\n4.div\n5.exit");, printf("\n enter u r choice");, scanf("%d",&ch);, switch(ch), {, case 1: c=a+b;, printf("\n sum=%d",c);, break;, case 2: c=a-b;, printf("\n sub=%d",c);, break;, case 3: c=a*b;, printf("\n mul=%d",c);, break;, case 4: c=a/b;, printf("\n div=%d",c);, break;, case 5: exit(0);, default: printf("\n enter proper choice");, }, getch();, }, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 49
Page 50 :
NIE First Grade College, Mysore, Output:, , Looping Statement:, The concept of loops is fundamental to structured programming. A loop is a program, construct that causes a statement to be executed again and again. The process of repeating the, execution of a certain set of statements again and again is termed as looping., C has several such statements that can be used to form loops they are., i., while statement, ii., do-while statement, iii., for statement, i., while statement:, This structure is also called as the “pre-tested” looping statement., Syntax: while (test condition), {, Statement 1;, Statement 2;, ..........., }, Statement n+1;, Example: C program to find sum of the digits using while loop., #include<stdio.h>, #include<conio.h>, void main(), {, int sum=0,count=1;, clrscr();, while(count<=10), {, sum=sum+count;, count++;, }, printf(“Total sum=%d”,sum);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 50
Page 51 :
NIE First Grade College, Mysore, ii., , do-while statement, This structure is also called as the “post-tested” looping statement., Syntax: do, {, Statements 1;, Statements 2;, .........., } while(test condition);, Statements n+1;, Example: C program to find product of the digits using do-while loop., #include<stdio.h>, #include<conio.h>, void main(), {, int prod=1,count=1;, clrscr();, do, {, prod=prod*count;, count++;, } while(count<=10), printf(“Total product=%d”,prod);, getch();, }, Output:, , iii., , for statement, for statement is also called as the “fixed execution” looping structure., Syntax: for(Expression_1;Expression_2;Expression_3), {, Statements_1;, Statements_2;, -------------------}, Statement_n+1;, 1. Expression_1 represents the initialization expression., 2. Expression_2 represents the expression for the final condition., 3. Expression_3 represents the increment of decrement expression., Example: C program to print the n elements using for loop., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 51
Page 52 :
NIE First Grade College, Mysore, #include<stdio.h>, #include<conio.h>, void main(), {, int i,n;, clrscr();, printf(“\n Enter n value”);, scanf(“%d”,&n);, for(i=0;i<=n;i++), printf(“%d\n”,i);, getch();, }, Output:, , Jumping statement:, The jump statements unconditionally transfer program control within a function., There are 5 types of jumping statement, goto, break, continue, exit(), return, 1. goto statement:, The goto statement is a simple statement, used to transfer control from one, point in a program to any other point in that program., Example:, goto label;, ................., ................., label: statement;, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 52
Page 53 :
NIE First Grade College, Mysore, Example: C program to demonstrate the working of goto statement., # include<stdio.h>, #include<conio.h>, void main(), {, float num,average,sum;, int i,n;, clrscr();, printf("Maximum no. of inputs: ");, scanf("%d",&n);, for(i=1;i<=n;++i), {, printf("Enter n%d: ",i);, scanf("%f",&num);, if(num<0.0), goto jump;, sum=sum+num;, }, jump: average=sum/(i-1);, printf("Average: %.2f",average);, getch();, }, Output:, , 2. break statement:, The break statement is used to terminate loops. It can be used within a while,, do-while or for statement., Example:, while(.....), {, .........., .........., break;, .........., }, Next statement;, Example: C program to demonstrate the working of break statement., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 53
Page 54 :
NIE First Grade College, Mysore, # include<stdio.h>, #include<conio.h>, void main(), {, float num,average,sum;, int i,n;, clrscr();, printf("Maximum no. of inputs: ");, scanf("%d",&n);, for(i=1;i<=n;++i), {, printf("Enter n%d: ",i);, scanf("%f",&num);, if(num<0.0), break;, sum=sum+num;, }, average=sum/(i-1);, printf("Average: %.2f",average);, getch();, }, Output:, , 3. continue statement:, In some programming situation we want to take the control back to the beginning, of the loop, bypassing the statements inside the loop, which have not yet been executed., Example:, while(......), {, ..........., ..........., Continue;, ..........., }, Next statement;, Example: C program to find the product of 4 integers entered by a user. If user enters, 0 skip it., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 54
Page 55 :
NIE First Grade College, Mysore, # include<stdio.h>, #include<conio.h>, void main(), {, int i,num,product;, for(i=1,product=1;i<=4;++i), {, printf(“Enter num%d:”,i);, scanf(“%d”,&num);, if(num==0), continue;, product*=num;, }, printf(“\n Product=%d”,product);, getch();, }, Output:, , 4. exit() function:, exit() is a standard library function that comes ready-made with the C compiler., Its purpose is to terminate the execution of the program., 5. return statement:, The return statement is used to return from a function., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 55
Page 56 :
NIE First Grade College, Mysore, ARRAYS, An array is defined as an ordered list of homogenous data elements stored in, consecutive memory locations., OR, An array is a collection of similar type of elements stored in consecutive memory, locations., Need for Arrays:, If a large amount of data is to be stored, it would be a long and tedious task to think of, a separate variable name for each datum, and then to type the declaration for each one of, these variables. Arrays are the solution to this problem. They are such an important part of, the art of programming that they are included in every high level language., To reduce program length., Easy to access., Make faster execution., To store large volume of data for similar type., Index, , Array Representation:, , Array name, , A[0] 2, A[1] 3, A[2] 4, A[3] 5, A[4] 6, A[5] 7, A[6] 8, A[7] 9, a) Vertical representation, , 23, , 45 90, , A[7] 5, A[6] 3, A[5] 4, A[4] 6, A[3] 8, A[2] 9, A[1] 1, A[0] 8, b) Building representation, , 35, , 40, , 22, , 85, , 65, , 48, , 50, , 59, , 60, , 65, , A[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12], c) Horizontal representation, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 56
Page 57 :
NIE First Grade College, Mysore, Types of Arrays:, Arrays are of different typesi., One-dimensional array: A structured collection of elements, all of the same type, that is given a single name. Each element is accessed by an index that indicates, the components position within the collection., ii., Two-dimensional array: A two dimensional array is a collection of elements, all, of the same type, structured in two dimensions. Each element is accessed by a pair, of indices that represent the elements position in each dimension., iii., Multi-dimensional array: A collection of elements, all of the same type, ordered, on N dimensions (N>=1). Each element is accessed by N indices, each of which, represents the elements position within that dimension., One-dimensional array (1D):, A one-dimensional array is a structured collection of elements that can be accessed, individually by specifying the position of an element with a single index value., Declaration of array (1D):, Data_type Array_name[size];, Example: int a[20];, float height[5];, char name[30];, Array Initialization:, There are two types of array initialization., i., Compile time initialization, ii., Run time initialization, Compile time initialization:, We can initialize the elements of arrays in the same way as the ordinary variables, when they are declared., Syntax: type array_name [size] = {list of values};, Example: int num[5]={2,5,6,4,6};, Run time initialization:, An array can be explicitly initialized at run time. This approach is usually applied for, initializing large arrays., Example:, , int x[3];, scanf(“%d%d%d”,&x[0],&x[1],&x[2]);, Will initialize array elements with the values entered through the keyboard., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 57
Page 58 :
NIE First Grade College, Mysore, Example 1: C program to read and print one-dimensional array., #include<stdio.h>, #include<conio.h>, void main(), {, int a[50],i,n;, clrscr();, printf(“\n Enter size of elements”);, scanf(“%d”,&n);, printf(“\n Enter array elements”);, for(i=0;i<n;i++), scanf(“%d”,&a[i]);, printf(“\n entered elements are\n”);, for(i=0;i<n;i++), printf(“%d\n”,a[i]);, getch();, }, Output:, , Example 2: C program to find the largest element in an array and position of its occurrence., #include<stdio.h>, #include<conio.h>, void main(), {, int a[100];, int large,pos,num,i;, clrscr();, printf(“\n enter number of elements”);, scanf(“%d”,&num);, for(i=0;i<num;i++), scanf(“%d”,&a[i]);, large=a[0];, pos=0;, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 58
Page 59 :
NIE First Grade College, Mysore, for(i=1;i<num;i++), {, if(large<a[i]), {, large=a[i];, pos=i;, }, }, printf(“\n Largest element in the array is %d\n”,large);, printf(“\n largest elements position in the array %d\n”,pos+1);, getch();, }, Output:, , Two-dimensional array (2D):, A two dimensional array is used to represent elements in a table with rows and, columns, provided each element in the table is of the same type., Two-dimensional array declaration:, , Example:, , Data_type array_name[row size][column size];, int A[10][10];, A is a two dimensional array which contains 10 rows and 10 columns., , Two-dimensional array initialization, Similar to the one dimensional array, we can initialize a two-dimensional array either, by initializing it in its declaration or by using assignment statements., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 59
Page 60 :
NIE First Grade College, Mysore, Example:, , Unsized:, , int matrix[2][3]={1,2,3,4,5,6};, int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};, int sales[][4]={1,2,3,4,6,1,4,5,3,4,5,6};, , Accessing elements of an array:, Initializing an array in its declaration is impractical if the array is large. For a 100-row, by 100-column array, it is very difficult to list 10,000 values. If the values are all different,, input them into array at runtime., Consider the following declaration:, int a[3][3];, Read the 2D array and store them in the array a., for(i=0;i<3;i++), {, for(j=0;j<3;j++), {, scanf(“%d”,&a[i][j]);, }, }, Print the 2D array and store them in the array a., for(i=0;i<3;i++), {, for(j=0;j<3;j++), {, printf(“%d”,a[i][j]);, }, }, Example 1: C program to read and display a square matrix., #include<stdio.h>, #include<conio.h>, void main(), {, int a[10][10],m,n,i,j;, clrscr();, printf(“\n Enter order of the matrix”);, scanf(“%d%d”,&m,&n);, printf(“\n enter matrix elements”);, for(i=0;i<m;i++), {, for(j=0;j<n;j++), {, scanf(“%d”,&a[i][j]);, }, }, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 60
Page 61 :
NIE First Grade College, Mysore, printf(“matrix A is \n”);, for(i=0;i<m;i++), {, for(j=0;j<n;j++), printf(“%d\t”,a[i][j]);, printf(“\n”);, }, getch();, }, Output:, , Example 2: Program to add and subtract two MxN matrices, #include<stdio.h>, #include<conio.h>, void main(), {, int a[10][10],b[10][10],c[10][10],i,j,m,n;, clrscr();, printf("Enter m and n for matrix size\n");, scanf("%d%d",&m,&n);, printf("Enter the First Matrix : ");, for(i=0;i<m;i++), {, for(j=0;j<n;j++), scanf("%d",&a[i][j]);, }, printf("Enter the Second Matrix : ");, for(i=0;i<m;i++), {, for(j=0;j<n;j++), DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 61
Page 62 :
NIE First Grade College, Mysore, scanf("%d",&b[i][j]);, }, printf("\nThe Sum of Matrices is : \n");, for(i=0;i<m;i++), {, for(j=0;j<n;j++), {, c[i][j]=a[i][j]+b[i][j];, printf("%d\t ",c[i][j]);, }, printf("\n");, }, printf("\n\nThe Difference of Matrices is : \n");, for(i=0;i<m;i++), {, for(j=0;j<n;j++), {, c[i][j]=a[i][j]-b[i][j];, printf("%d\t ",c[i][j]);, }, printf("\n");, }, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 62
Page 63 :
NIE First Grade College, Mysore, , Example 2: Program to multiply two MxN matrices, #include<stdio.h>, #include<conio.h>, void main(), {, int a[10][10],b[10][10],c[10][10],i,j,k,m,n;, clrscr();, printf("Enter the size of the matrix \n");, printf("as m*n\n");, scanf("%d",&m);, scanf("%d",&n);, printf("Enter the First matrix\n");, for(i=0;i<m;i++), {, for(j=0;j<n;j++), {, scanf("%d",&a[i][j]);, }, }, printf("Enter the Second matrix\n");, for(i=0;i<m;i++), DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 63
Page 64 :
NIE First Grade College, Mysore, {, for(j=0;j<n;j++), {, scanf("%d",&b[i][j]);, }, }, printf("The First matrix is\n");, for(i=0;i<m;i++), {, printf("\n");, for(j=0;j<n;j++), {, printf("%d\t",a[i][j]);, }, }, printf("\nThe Second matrix is\n");, for(i=0;i<m;i++), {, printf("\n");, for(j=0;j<n;j++), {, printf("%d\t",b[i][j]);, }, }, for(i=0;i<m;i++), {, for(j=0;j<n;j++), {, c[i][j]=0;, for(k=0;k<n;k++), {, c[i][j]=c[i][j]+a[i][k]*b[k][j];, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 64
Page 66 :
NIE First Grade College, Mysore, Unit-3, , STRING HANDLING, String:, A string is a sequence of characters., Declaration of string arrays:, Syntax: char variable_name [size];, Example: char name [20];, STRING ARRAY INITIALIZATION, Once you declare an array, you can enter its value using scanf () or gets (). You can, also assign the array initial values when you declare it., Example: consider the following string initialization., Case 1: char name [9] =”COMPUTER”;, , C, , O, , name [0], Case 2:, , [1], , M, , P, , U, , [2] [3], , [4], , T, [5], , E, , R, , [6] [7], , \0, [8], , char name [] =”Computer”;, OR, , Case 3: char name [9] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’\0’};, , READING A STRING:, To read a string, we use a standard I-O library function scanf (). Scanf () reads, formatted input from the standard input device, which is usually the keyboard. We can read, values into a string with scanf () function using %s formatting code:, scanf (“%s”,name);, There is a problem with scanf () function while reading a string data. Consider the, following program., Program 1: A C program to read a string using scanf () function., #include <stdio.h>, #include<conio.h>, void main(), {, char name[20];, clrscr();, printf(“Enter a string\n”);, scanf(“%s”,name);, printf(“\n Entered string was %s”, name);, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 66
Page 67 :
NIE First Grade College, Mysore, getch();, }, Output:, , The input string was sri nagar but the output result is sri, this is because of, the blank space. The scanf () function accepts characters one at a time until it encounters a, blank space or newline character. To avoid such error, c provides another function called, gets(). The gets() function accepts an entire line of input from the standard input device., Program 2: A C program to read a string using gets() function., #include <stdio.h>, #include<conio.h>, void main(), {, char name[20];, clrscr();, printf(“Enter a string\n”);, gets(name);, printf(“\n Entered string was %s”, name);, getch();, }, Output:, , WRITING (PRINTING) A STRING:, puts() and printf() functions are used to display a string on the standard output device., Program 2: A C program to read and write a string using gets() and puts() function., #include <stdio.h>, #include<conio.h>, void main(), {, char name[20];, clrscr();, puts(“Enter a string\n”);, gets(name);, puts(“\n Entered string is:”);, puts(name);, getch();, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 67
Page 68 :
NIE First Grade College, Mysore, }, Output:, , STRING OPERATIONS:, The C library supports a large number of string handling functions that can be used to, carry out many of the string manipulations such as, , , , , , , Length (number of characters in a string), Concatenation (Adding two or more strings), Comparing two strings, Substring (Extract substring from the given string), Copy (copies one string over another), , Note: To use all the string operations in C you must include string.h library header file in, the program, STRING HANDLING FUNCTIONS:, FUNCTION, Strcat(), Strcmp(), Strcmpi(), Strcpy(), Strlen(), Strlwr(), Strupr(), Strchr(), Strcspn(), Strncat(), Strncmp(), Strncpy(), Strnset(), Strrev(), Strstr(), , DESCRIPTION, Adds the characters of one string to another., Compares two strings considering case., Compare two strings; not case sensitive., Copies one string or string literal, to another., Calculates the string length., Converts a string to lowercase., Converts a string to uppercase., Returns the position of a specified character in the string., Returns the position of a character in the string from a specified character, set., Appends specified characters from one string to another., Compares specified characters of two strings., Copies specified characters from one string to another., Changes specified characters in a string to another character., Reverses the characters in a string., Finds one string within another., , 1. strlen() FUNCTION, This function counts and returns the number of characters in a string. The length does not, include the NULL character., , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 68
Page 69 :
NIE First Grade College, Mysore, Syntax:, , n=strlen(string);, Where n is an integer variable which receives the value of the length of, , the string., Example1: write a c program to find the length of a string., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char name[100];, int length;, clrscr();, printf(“enter a string\n”);, gets(name);, length=strlen(name);, printf(“\n Number of characters in the string is %d”,length);, getch();, }, Output:, , Example2: write a c program to find the frequency of occurrence of a specified character., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char text[100],ch;, int length,i,count=0;, clrscr();, printf(“enter a string\n”);, gets(text);, puts(“Enter a character to be searched”);, scanf(“%c”,&ch);, length=strlen(text);, for(i=0;i<length;i++), if(text[i]==ch) count++;, if(count), DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 69
Page 70 :
NIE First Grade College, Mysore, printf(“\n %c occurs %d times”,ch,count);, else, printf(“\n %c does not exist in the text”,ch);, getch();, }, Output:, , 2. strcpy() FUNCTION:, C does not allow you to assign characters to a string directly, as in the, statement, char name[30];, name=”NIE”;, Instead, use the strcpy() function found in most compilers. The syntax of the function, is illustrated below:, Syntax:, strcpy(string1,string2);, Assign the contents of string2 to string1. String2 may be a character, array variable or a string constant., Example:, strcpy(name,”NIE”);, Example1: write a c program to copy one string to another., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char name[100], city[100];, clrscr();, printf(“enter a string\n”);, gets(name);, strcpy(city,name);, printf(“\n copied string is %s”,city);, getch();, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 70
Page 72 :
NIE First Grade College, Mysore, Example2: strcmp(“their”,”there”) will return -9 which is the numeric difference, between ASCII “i” and ASCII “r”., Example3: strcmp(“there”,”their”) will return 9 which is the numeric difference, between ASCII “r” and ASCII “i”., Example4: strcmp(“THE”,”the”) will return -32 which is the numeric difference, between ASCII “T” and ASCII “t”., Example5: write a c program to compare two strings., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char st1[100], st2[100];, int n;, clrscr();, printf(“enter a string1\n”);, gets(st1);, printf(“enter a string2\n”);, gets(st2);, n=strcmp(st1,st2);, printf(“\n Numeric difference between ASCII value is %d”,n);, getch();, }, Output:, , 5. strcmpi() FUNCTION, This function is same as strcmp(), which compares two strings, but is not case, sensitive., Example1: write a c program to compare two strings using strcmpi()., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char st1[100], st2[100];, int n;, clrscr();, printf(“enter a string1\n”);, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 72
Page 73 :
NIE First Grade College, Mysore, gets(st1);, printf(“enter a string2\n”);, gets(st2);, n=strcmpi(st1,st2);, printf(“\n Numeric difference between ASCII value is %d”,n);, getch();, }, Output:, , 6. strlwr() FUNCTION:, This function converts all uppercase characters in a string to lowercase, Syntax:, strlwr(string);, Example1: write a c program to convert uppercase character to lowercase character., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char name[100];, clrscr();, strcpy(name,”COMPUTER”);, printf(“\n Converted string is %s”,strlwr(name));, getch();, }, Output:, , 7. strupr() FUNCTION:, This function converts all lowercase characters in a string to uppercase, characters., Syntax:, strupr(string);, Example1: write a c program to convert lowercase character to uppercase character., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 73
Page 74 :
NIE First Grade College, Mysore, char name[100];, clrscr();, strcpy(name,”computer”);, printf(“\n Converted string is %s”,strupr(name));, getch();, }, Output:, , 8. strrev() FUNCTION:, This function reverses the characters in a string., Syntax:, , strrev(string);, , Example1: write a c program to check whether a given word is palindrome or not., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char st1[100], st2[100];, clrscr();, printf(“Enter a string”);, scanf(“%s”,st1);, strcpy(st2,st1);, strrev(st2);, if(strcmp(str1,str2)==0), printf(“%s is a palindrome”,st1);, else, printf(“%s is not a palindrome”,st1);, getch();, }, Output:, , ARRAY OF STRINGS, An array of strings is a two-dimensional array. The size of first index (rows), determines the number of strings and the size of second index (columns) determines, maximum length of each string., Example: consider the following array declaration, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 74
Page 75 :
NIE First Grade College, Mysore, char name[8][20];, Declares an array of 8 strings, each of which can hold maximum of 20 characters., An array of strings appears in memory as shown in figure., 0, name[0], ., ., ., ., ., ., ., ., ., Name[7], , 1, , 2, , 3, , 4, , 5, , 6, , D, G, S, C, M, , H, U, H, H, Y, , A, L, I, I, S, , R, B, M, K, O, , W, A, O, A, R, , D, R, G, M, E, , \0, G, A, A, \0, , B, K, H, , A, A, A, , N, R, S, , G, A, S, , A L, W A, A N, , O, R, \0, , 7, , 8, , 9 10 11 12 13 14 15 16 17 18 19, , A, \0, G, , \0, A, , L, , R, \0, , E, , \0, , U, , R, , \0, , Example: A C program to arrange N names in alphabetical order., #include<stdio.h>, #include<string.h>, #include<conio.h>, void main(), {, char name[10][20];, char tempname[20];, int n,i,j;, clrscr();, printf(“Enter number of names\n”);, scanf(“%d”,&n);, printf(“Enter list of names\n”);, for(i=1;i<n;i++), gets(name[i]);, for(i=1;i<n;i++), for(j=0;j<n-i;j++), if(strcmp(name[j],name[j+1])>0), {, strcpy(tempname,name[j]);, strcpy(name[j],name[j+1]);, strcpy(name[j+1],tempname);, }, printf(“\n Sorted names”);, for(i=0;i<n;i++), printf(“\n%s”,name[i]);, getch();, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 75
Page 76 :
NIE First Grade College, Mysore, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 76
Page 77 :
NIE First Grade College, Mysore, FUNCTIONS, MODULE: A self contained collection of steps that solves a problem or sub-problem., Large programs can be made manageable by dividing it into smaller sub-programs or, modules. These sub-programs are called as functions., OR, A function is a named unit of a group of program statements designed to perform a, specific task and returns a single value., C supports two types of functions. They are, i., Built-in or library functions., ii., User defined functions., i., , Built-in or library functions:, A function defined by the C compiler., Example: sqrt(), strcpy(), pow(), cos() and so on., ii., User defined functions:, A function defined by the user., Example: sum(), mul(), search(),read() and so on., NEED OF FUNCTIONS:, i., Repetition: If there is a portion of the program, which is to be repeated in a number, of places in the program, a function may be used to avoid rewriting the same sequence, of code at two or more, locations in the program. This is especially useful if the code, involved is long or complicated., ii., Universal use: Some tasks might be needed in more than one program or a large, group of programmers may need the same task. By writing a function and making it, available to others the duplication of effort can be avoided., iii., Modularity: A program for complex problems can be developed in a modular fashion, by dividing the problem into modules, or functions, each function performing a, definite task. Since the functions are independent of each other, each one of them can, be developed and tested without worrying about the details of the other modules., iv., Teamwork: If a program is divided into sub-programs, a number of members can, form a team and each person in the team can develop a separate sub-program, rather, than having a single person work on the complete program., USE OF FUNCTIONS:, Programs with functions are compact thus decreasing the number of lines of code to a, very large extent., Debugging the code is much simpler because errors can be localized and corrected, easily., DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 77
Page 78 :
NIE First Grade College, Mysore, Functions increase the readability of the program and helps in proper and good, documentation., Many other programs may use a function, thus helping us to create our own libraries., FUNCTION DEFINITION OR SYNTAX, Return_type_specifier function_name (type arg1, type arg2............), {, Local variable declarations;, Statement 1;, Statement 2;, ......................., ......................., Statement n;, Return (Expression);, }, , Body of the function, , i., , Argument list with declaration, , Return_type_specifier, , The return_type_specifier identifies the type of value, which will be sent back, after the function has performed its task. The return_type_specifier can include the, normal data types such as int, float, char the data type void is used if the function does, not return a value., ii., , Function_name, The function_name thus helps us to uniquely identify and call a function., , iii., , Argument list with declaration, The argument list identifies the set of values, which are to be passed to the, , function from either the main program or a sub-program., iv., , Body of the function, The body of the functions first includes the identification of those components,, , which will be used only within the function and not outside it. Thus those components are, declared as local variables., Next a function contains a set of executable statements, which will perform the, required task for the user. The last executable statement of the function is the word, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 78
Page 79 :
NIE First Grade College, Mysore, “return” with an expression, which contains the value that has to be sent back to the, main program., FUNCTION CALL:, A statement that transfers control to a function. In c, this statement is the name of the, function, followed by a list of arguments., A function can be called by simply using the function name in a statement. A function, call has the following syntax., Variable=function_name (arg1, arg2 ...);, Values are passed on to a sub-program by copying values from the actual paramenters, (function call) to the formal parameters (function header), Formal parameter: A variable declared in a function heading is also called formal argument, or formal parameter., OR, The definition of a function or the function body also includes a set of parameters or, arguments these arguments are called as formal arguments or dummy arguments., Actual Argument: A variable or expression listed in a call to a function is also called actual, argument or actual parameter., OR, A function call includes the function name with some parameters or arguments, these, arguments are known as actual arguments., Function prototypes:, A function prototype is a declaration of the function that tells the program about the, type of the value returned by the function and the number and type of arguments., Syntax:, , return_type_specifier function_name();, OR, Return_type_specifier function_name(type1,type2,.....);, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 79
Page 80 :
NIE First Grade College, Mysore, Example 1: C program to find the sum of the digits of a number until the resulting value is a, one digit number., #include<stdio.h>, #include<conio.h>, void main(), {, int sum_of_digits(int);, , function prototype, , int num,sum,n;, clrscr();, printf(“Enter a number\n”);, scanf(“%d”,&num);, n=num;, while(n>=9), , calling function, , {, sum=sum_of_digits(n);, , n is an actual argument, , n=sum;, }, printf(“the number is=%d\n”,num);, printf(“sum of digits until one digit=%d\n”,sum);, getch();, }, int sum_of_digits(int n), {, , n is a formal argument, Called function, , int d,s=0;, , Local declaration, , while(n>0), {, d=n%10;, n=n/10;, s=s+d;, }, return(s);, , returns value, , }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 80
Page 81 :
NIE First Grade College, Mysore, Output:, , LOCAL AND GLOBAL VARIABLES:, Local variable: A variable declared within a block and not accessible outside of the block, Example:, Function(int m, int n), {, int a,b;, --------------}, , a and b are local variables, , Global variable: A variable declared outside of all the functions in a program., Example:, int a,b;, main(), {, , a and b are global variables, , int p,q;, ---------------, , p and q are local variables, , }, , Example 2: C program to find the largest of two numbers using the global variable, declaration., #include<stdio.h>, #include<conio.h>, int num1,num2,lar;, , Global declaration, , void main(), {, int largest();, , Function prototype, , clrscr();, printf(“enter two numbers”);, scanf(“%d%d”,&num1,&num2);, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 81
Page 82 :
NIE First Grade College, Mysore, printf(“Largest of %d and %d is %d”,num1,num2,largest());, getch();, , Calling function, , }, int largest(), , Called function or definition of the function, , {, lar=(num1>num2)?num1:num2;, return(lar);, }, Output:, , CALL BY VALUE:, A parameter that receives a copy of the value of corresponding argument., Example 1: C program to illustrate the function using call by value mechanism., #include<stdio.h>, #include<conio.h>, void main(), {, void function(int,int);, int a=20,b=30;, clrscr();, printf(“a=%d b=%d before function call \n”,a,b);, function(a,b);, printf(“a=%d b=%d after function call\n”,a,b);, getch();, }, void function(int x,int y), , call by value function, , {, x=x+x;, y=y+y;, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 82
Page 83 :
NIE First Grade College, Mysore, Output:, , The corresponding formal parameter represents a local variable in the called function., The current value of the corresponding actual parameter becomes the initial value of the, formal parameter. The value of formal parameter may then change in the body of the, subprogram by assignment or input statements. This will not change the value of the actual, parameter., CALL BY REFERENCE:, A parameter that receives the memory address of corresponding argument., Example 2: C program to illustrate the function using call by reference mechanism., #include<stdio.h>, #include<conio.h>, void main(), {, void function(int *,int *);, int a=20,b=30;, clrscr();, printf(“a=%d b=%d before function call \n”,a,b);, function(&a,&b);, printf(“a=%d b=%d after function call\n”,a,b);, getch();, }, void function(int *x,int *y), , call by reference function, , {, *x=*x+*x;, *y=*y+*y;, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 83
Page 84 :
NIE First Grade College, Mysore, Example 3: C program to exchange the contents of the two variables using call by value and, call by reference., #include<stdio.h>, #include<conio.h>, void main(), {, int a,b;, void swap_val(int,int);, void swap_ref(int *,int *);, clrscr();, printf(“Enter two numbers\n”);, scanf(“%d%d”,&a,&b);, printf(“a=%d b=%d before function call\n”,a,b);, swap_val(a,b);, printf(“a=%d b=%d after function call using call by value\n”,a,b);, swap_ref(&a,&b);, printf(“a=%d b=%d after function call using call by reference\n”,a,b);, getch();, }, void swap_val(int x,int y), {, int temp;, temp=x;, x=y;, y=temp;, }, void swap_ref(int *x,int *y), {, int temp;, temp=*x;, *x=*y;, *y=temp;, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 84
Page 85 :
NIE First Grade College, Mysore, Output:, , TYPES OF FUNCTIONS OR CATEGORIES OF FUNCTION:, i., , Functions with no arguments and no return values., , ii., , Functions with arguments and no return values., , iii., , Functions with arguments and with return values., , iv., , Recursive functions., , i., , Functions with no arguments and no return values:, In this type of function the first function calls the second function. However no, arguments are passed to the second function. The second function performs its, calculations but no value is sent back to the first function., Calling Function, , Action, , Function1(), , Called Function, Function2(), , {, , No arguments, , {, , ----------------, , ----------------, , -----------------, , ----------------, , Function2();, , ---------------No return values, , }, , }, , Example: C program to illustrate a function with no arguments and no return values., #include<stdio.h>, #include<conio.h>, void main(), {, void Our_address();, clrscr();, Our_address();, getch();, }, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 85
Page 86 :
NIE First Grade College, Mysore, void Our_address(), {, printf(“\n NIE FGC”);, printf(“\n Mysore”);, }, Output:, , ii., , Functions with arguments and no return values:, In this type of function the first function calls the second function by passing some, arguments or values to the second function. The second function performs its, calculations but no value is sent back to the first function., Calling Function, , Action, , Function1(), , Called Function, Function2(a), , {, , Arguments, , {, , ----------------, , ----------------, , -----------------, , ----------------, , Function2(x);, , ---------------No return values, , }, , }, , Example: C program to find the type of character entered using functions., #include<stdio.h>, #include<conio.h>, void main(), {, void char_type(char);, char ch;, clrscr();, printf(“enter a character\n”);, scanf(“%c”,&ch);, char_type(ch);, getch();, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 86
Page 87 :
NIE First Grade College, Mysore, void char_type(char c), {, if((c>=‟a‟)&&(c<=‟z‟)), printf(“%c is a lower case alphabet\n”,c);, else if((c>=‟A‟)&&(c<=‟Z‟)), printf(“%c is an upper case alphabet\n”,c);, else if((c>=‟0‟)&&(c<=‟9‟)), printf(“%c is a digit\n”,c);, else, printf(“%c is a special character\n”,c);, }, Output:, , iii., , Functions with arguments and with return values:, In this type of function the first function calls the second function by passing some, arguments or values to the second function. The second function performs its, calculations and returns the answer or a value back to the first function., , Calling Function, , Action, , Function1(), , Called Function, Function2(a), , {, , Arguments, , {, , ----------------, , ----------------, , -----------------, , ----------------, , Function2(x);, , ---------------Return values, , }, , return(e);, }, , Example: C program to find all prime numbers in the range N and M using functions., #include<stdio.h>, #include<conio.h>, void main(), {, int a,b,g,l;, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 87
Page 88 :
NIE First Grade College, Mysore, int gcd(int,int);, clrscr();, printf(“Enter the numbers a and b\n”);, scanf(“%d%d”,&a,&b);, g=gcd(a,b);, l=(a*b)/g;, printf(“GCD of %d and %d=%d\n”,a,b,g);, printf(“LCM of %d and %d=%d\n”,a,b,l);, getch();, }, int gcd(int x,int y), {, while(x!=y), if(x>y), x=x-y;, else, y=y-x;, return(x);, }, Output:, , iv., , Recursive functions:, Functions that call itself directly or indirectly again and again is called recursive, function., Function1(a), {, ______________, ______________, ______________, Function1(x);, }, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 88
Page 89 :
NIE First Grade College, Mysore, Example: C program to find the factorial of the given number using recursive function., #include<stdio.h>, #include<conio.h>, void main(), {, int n;, int fact(int);, clrscr();, printf(“enter any non-negative integer\n”);, scanf(“%d”,&n);, if(n<0), printf(“Invalid Input”);, else, printf(“factorial of %d is=%d\n”,n,fact(n));, getch();, }, int fact(int n), {, if(n==0), return(1);, else, return(n*fact(n-1));, }, Output:, , FUNCTIONS AND ARRAYS:, We can pass an entire array from one function to another. To pass an entire array to a, function we will have to just pass the name of the array as the actual argument. When we, pass a normal variable other than an array, c makes a copy of the data and places it in a, memory location associated with the receiving variable., Example: C program to sort in ascending order using a function., #include<stdio.h>, #include<conio.h>, void main(), {, int a[100];, int i,num;, void output(int *,int);, void selection_sort(int *,int);, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 89
Page 90 :
NIE First Grade College, Mysore, clrscr();, printf(“Enter number of element in the array\n”);, scanf(“%d”,&num);, printf(“Enter Array elements \n”);, for(i=0;i<num;i++), scanf(“%d”,&a[i]);, printf(“Unsorted array\n”);, output(a,num);, selection_sort(a,num);, printf(“\n sorted array\n”);, output(a,num);, getch();, }, void output(int b[],int n), {, int i;, for(i=0;i<n;i++), printf(“%d\t”,b[i]);, }, void selection_sort(int b[],int n), {, int i,j,min,pos;, for(i=0;i<n-1;i++), {, min=b[i];, pos=i;, for(j=i+1;j<n;j++), if(b[j]<min), {, min=b[j];, pos=j;, }, b[pos]=b[i];, b[i]=min;, }, }, Output:, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 90
Page 91 :
NIE First Grade College, Mysore, STRUCTURES AND UNIONS, STRUCTURE:, C provides a way to collect different types of data together into one entity,, called a structure., OR, It is a group of logically related data items of same type or different types., DIFFERENCE BETWEEN ARRAY AND STRUCTURE:, , Array, , Structure, , Array is a collection of homogeneous data, , Structure is a collection of heterogeneous, data, Array elements are referred by subscript, Structure elements are referred by unique, name, Array elements are accessed by its position Structure elements are accessed by its objects, or subscript, as „.‟ Operator, Array is a derived data type, Structure is user defined data type, struct structure_name, Syntax:, {, Data_type array_name[size];, Data_type member 1;, Data_type member 2;, ------------------------------------------------------Data_type member n;, }struct_var_name;, struct item, Example:, int rno[5];, {, int rno;, char name[50];, }itm;, , DEFINITION AND DECLARATION OF A STRUCTURE OR SYNTAX:, struct structure-name, {, Data_type, member_name_1;, Data_type, member_name_2;, Data_type, member_name_3;, ..................................................., Data_type, member_name_n;, };, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 91
Page 94 :
NIE First Grade College, Mysore, Way 2: Declaring and Initializing multiple variables., struct student, {, char name[20];, int roll;, float marks;, }, std1={“prakash”,67,78.5};, std2={“ramesh”,75,86.4};, STRUCTURES WITHIN STRUCTURES (NESTED STRUCTURES):, Structures can be used as structures within structures. It is also called as 'nesting of, structures'., Syntax:, struct structure_nm, {, <data-type> element 1;, <data-type> element 2;, --------------------<data-type> element n;, struct structure_nm, {, <data-type> element 1;, <data-type> element 2;, --------------------<data-type> element n;, }inner_struct_var;, }outer_struct_var;, , Example :, struct stud_Res, {, int rno;, char nm[50];, char std[10];, struct stud_subj, {, DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 94
Page 98 :
NIE First Grade College, Mysore, Output :, , UNION:, Union is user defined data type used to stored data under unique variable name at single, memory location., Union is similar to that of structure. Syntax of union is similar to structure. But the, major difference between structure and union is 'storage.' In structures, each member has, its own storage location, whereas all the members of union use the same location. Union, contains many members of different types; it can handle only one member at a time., To declare union data type, 'union' keyword is used., Union holds value for one data type which requires larger storage among their members., , Syntax:, union union_name, {, <data-type> element 1;, <data-type> element 2;, <data-type> element 3;, }union_variable;, , Example:, union techno, {, int comp_id;, char nm;, float sal;, }tch;, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 98
Page 100 :
NIE First Grade College, Mysore, Output :, , DEPT. OF COMPUTER SCIENCE, JAYARAM N, , Page 100