+ All Categories
Home > Documents > wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the...

wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the...

Date post: 14-Jan-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
200
BE Computer Programming in C Yagya Rimal CMP 103.3 Programming in C(3-0-3) Evaluation: Theory Practical Total Sessio nal 30 20 50 Final 50 - 50 Total 80 20 100 Course Objectives: The object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses the use of programming systems to achieve specified goals, identification of useful programming abstractions or paradigms, the development of formal models of programs, the formalization of programming language semantics, the specification of program, the verification of programs, etc. the thrust is to identify and clarify concepts that apply in many programming contexts: Course Contents: 1. Introduction (4 hrs) History of computing and computers, Text editing and file concepts, Traditional and structured programming concept, Problems analysis, flow chart and algorithm, Program Documentation 2. Variables and data types (3 hrs) Constants and variables, Variable declaration, Variable Types, Simple input/output function, Operators 1
Transcript
Page 1: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalCMP 103.3 Programming in C(3-0-3)

Evaluation:

Theory Practical Total

Sessional 30 20 50

Final 50 - 50

Total 80 20 100

Course Objectives:

The object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses the use of programming systems to achieve specified goals, identification of useful programming abstractions or paradigms, the development of formal models of programs, the formalization of programming language semantics, the specification of program, the verification of programs, etc. the thrust is to identify and clarify concepts that apply in many programming contexts:

Course Contents:

1. Introduction (4 hrs)History of computing and computers, Text editing and file concepts, Traditional and structured programming concept, Problems analysis, flow chart and algorithm, Program Documentation

2. Variables and data types (3 hrs)Constants and variables, Variable declaration, Variable Types, Simple input/output function, Operators

3. Loops and Decisions (5 hrs)Introduction, For Loop, While Loop, Do while Loop, Nested Loop, Case, break and continue statements, The if, if else, else-if and switch statements.

4. Functions (6 hrs)Introduction, Returning a value from a function, Sending a value to a function, Arguments, External variables, Preprocessor directives, C libraries, Macros, Header files and prototyping

5. Arrays and Strings (9 hrs)Introduction to Arrays, Initializing Arrays, Multidimensional Arrays, String, Functions related to the strings, Function related to Graphics

1

Page 2: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal

6. Pointers (10 hrs)Pointers definition, Pointers and Arrays, Returning multiple values from functions, using pointers, Pointer Arithmetic, Pointer and Strings, Double Indirection, Pointer to Arrays

7. Structure and Unions (5 hrs)Definition of Structure, Nested type Structure, Arrays of Structure, Structure and Pointers, Unions

8. Files and File Handling (3 hrs)Operating a file in different modes (Real, Write, Append), Creating a file in different modes (Read, Write, Append)

Laboratory:

Laboratory work at an initial stage will emphasize on the verification of programming concepts learned in class and use of loops, functions, pointers, structures and unions. Final project of 10 credit hours will be assigned to the students which will help students to put together most of the programming concepts developed in earlier exercises.

Textbooks:

1. A book on C by A1 Kely and Ira Pohl2. The C Programming Language by Kerighan, Brain and Dennis Ritchie

2

Page 3: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Main memory

Input

Secondary

Output

CPUALU

Register

Control Unit

BE Computer Programming in C Yagya RimalComputerA computer is an electronic machine which operates under human/user control accepts data using some input devices, performs certain operation then required information can be stored for future used, fianally it displays the results in output devices.Computers are used in wide areas like houses, schools, colleges, hospitals, business, and industries. They are used to accomplished job in very quicklly and efficiently. Computer is device that cannot do nothing alone without certain programs or instructions to be supplied. A program is a set of code /instructions which causes a computer to perform particular operation.

Computer System The computer requires computer system because of different components work together to produce the desired result to the user. The various components of computers of computer systems are as follows:Hardware: All the physical components of the computer system are called hardware such as Monitor, CPU, and Mouse,RAM, Keyboard etc.Software: The collection of instruction or logical components that instruct the hardware to perform certain task is called software. They are intermediate between hardware and user.Producer/Users: The way of operating computer is called procedure. The users are the primary component of computer system. All the system are primarily for user requirement. Data /Instruction: The raw data under which computer work after processing the raw data are converted inot meaningful information. Each and every instructions should have to given to the system.Connectivity: When two or more computers and their peripherals are connected to communicate in the computer system are called connectivity.

Computer ArchitectureComputer architecture is the theory behind the design of a computer. The digital computer can be divided into 3 major sections are CPU, Memory and I-O unit. The simple architecture of computers is as follows. The CPU and other units are linked with the parallel communication channels data channels, address channels and controls channels are called bus/cable. Computer system is a group of physical parts that are configured to achieve the objectives. A computer system needs to do the following operations:

i. Input: Obtain the data / instructions (program)ii. Process: Process data, based on the instructions/ programs, taken from the user or pre-defined progam.iii. Output: Gives the final result to users.

This cycle of operation of a computer is referred as Input-Process-Output or IPO cycle.Computer System Architecture (Anatomy) is concerned with the structure of computer. It consists of the various functional components such as

1. Input Unit2. Central Processing Unit3. Memory Unit and4. Output Unit

Fig: Block diagram of computer system architectureProcessor (CPU): The processor is a computer hardware chip (Heart of computer) that receives the data input from the input devices , processes the data in some way by performing calculations or reorganizing it, stores the results in memory until it sends them to an output devices or stores them in a backup storage devices. The CPU is divided into 3 major sections are above architecture:

3

Page 4: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalControl Unit (CU): The control unit manages program/ instruction, so that data is received form input devices and send to output devices at right time. It sends output control signals at a speed that is measured in Meghthertz (MHz) and Gigahertz (GHz).Arithmetic and Logical Unit :The arithmetic and logical unit carries out all the arithmetic and logical operations that are needed to produces data/information.Register Unit: It is special temporary storage location inside CPU. Registers are very quickly accept, store and transfer data and instruction that are being used currently.Bus: A bus is simple a parallel communication pathway over which information and signals are transferred between several computer components/parts.Address Bus: The address bus is used to carry address signals for addressing data in different location in computer memory. So that it is uni-directional bus.Data Bus: The data bus is used to communicate data form CPU to other internal unit of computer system. Data bus is bi-directional.Control Bus: The control signals are transmitted through control bus it store proper timeing calculation in sequenceal manner. After that it makes quess and transfer to the several instruction to various distinations.Affecting Factors for Speed of CPUSystem Clock Rate: It is the rate of an electronic pulse used to synchronize processing among various location it is measured in MHZ (1 MHz= 1 Million Cycles per Second).Bus Width: The amount of data from CPU can transmit at a time to main memory and to input other output devices. An 8 bit bus moves 8 bits of data at a time. They are 8, 16, 32, 64, and 128 types.Word Size: The amount of data can be processed by the CPU at one time is called word size. An 8 bit processor can manipulate 8 bits at a time. The processors are also various types as 8, 16, 32, 64 and so far. The bigger the number means the faster the computer system that counts faster length of binary bits at a time.

Characteristics of ComputerSpeed: Computer can perform complex calculation at a very high speed. The speed of computer performance in a single operation can measure in terms of Millisecond, Microsecond, Nanosecond and Picoseconds.

1/1000(10-3) - Sec-1 Millisecond1/1000000(10-6) - 1 Microsecond1/1000000000(10-9)- 1 Nanosecond

1/1000000000000(10-12)- 1 PicosecondsStorage: A large amount of data can store in computer memory. The storing capacity is measured in terms of Bytes, Kilobytes, Megabytes, Gigabytes and Terabytes.

1024 Bytes= 1 Kilobytes (KB)1024 Kilobytes =1 Megabytes (MB)1024 Megabytes= 1 Gigabytes (GB)

1024 GB= 1 Terabytes (TB)Accuracy: A computer can perform all the calculation and comparision accurately. Sometimes errors may produce by computers due to the fault in machine instruction or due to bugs in the programs. If input data are not correct, this may also lead to incorrect output. The computer follows the simple rules of GIGO (Garbage in, Garbage Out). Therefore, if we supply accurate instruction /data it always produce accurate output.Reliability: Computer never tired, bored or fell laziness to do some in multiple times. The computer is capable of performing various task repeatedly at the same level of speed and accuracy even if it has to carry complex operations for a long period. Computers are quite capable to perform automatic and accurate operation, when the instruction is given to it.Automatic: Computer is an automatic machine. Everything that is given to computers is processed and dome by computers automatically without any mistake.Versatility: A computer has wide range of application areas i.e. computers can do many types of jobs. It can perform operation ranging from single mathematical calculations to higher complex and logical evaluations for any extended periods of times.Diligence: A computer can perform respective tasks without being bored, tired without any losing concentration. It can continuously work for several hours without human intervention after the data and

4

Page 5: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprogram are feed to it. They can handle complicated and complex task too. There is not aging effect on computer i.e. efficiency does not decrease over the years of user.Therefore computer is obident instrument.Limitations of Computer

1. Sometime the failure in devices and programs can produce unreliable information.2. Computer is dull machine it does not have intelligence on it.3. Computer cannot draw conclusion without going through all intermediate steps.

Historical Development of ComputerThe computer which is most advanced discoveries has got a long history. Around 3000 years before the birth of Jesus Christ, there were no any kind of counting system. So people had to remember a lot of information. They felt something need to count their cattle’s. Then they started counting their fingers. But the limited number of finger had made difficult for them to remember more facts. So they used stone for counting. As result around in fifth century Hindu Philosopher develops new methods of counting using numbers from 1 to 9. In 8th century Alkhawarism of Iraq, developed 0. Since there are ten digits these number systems method was called decimal number system.

Mechanical Era/ the Age of Mechanical CalculatorThe most significant early computing tools is ABACUS, was developed in 1000-1500 AD, a wooden rack holding parallel rods on which different sizes balls are stung. The arithmetic operations can be carried out with the help of breads on the wire. The frame consists of upper parts and lower parts. The upper part is called heaven and lower is called earth. Each part consists of five beads on earth part and heaven parts consist of two beads. This is used for addition and subtraction. In 1500, Leonardo Da Vinci developed mechanical calculator that was very heavy. After that a Scottish Mathematician, John Napier (1614) invented another calculator which was made of bone had more functionality that could add and multiplication of numbers. It used analog mechanism which was replaced modern times by pocket calculators. The significant evolution of computing system was the invention by French Mathematician, Blasé Pascal (1642). La Pascal Machine that could do multiply, divide and find square root. In 1822 a professors of mathematician, Thomas (Charles Xavier Thomas) developed a machine called differential engine which was the first commercially mechanical calculators. Charles Babbage (1792- 1871) at Cambridge University was developed the first digital computer. By 1822 he built an automatic mechanical calculator called Difference Engine. Unfortunately, Babbage analytical engine was never completed because its design required fabrication precision beyond what was feasible at that time. In 1840 Augusta (first programmer) suggested binary storage. In 1887 an American statistician Herman Hollerith constructed a tabulating machine to compute the staticstatics of 1890 US census. He used the punch cards to store data. This machine can read 200 punched cards per minutes. In 1900 Johan Ambrose Fleming invents the vacuum tube to store data and instruction, which was very big. The major step in the evolution of computer system is invention of punch card which was first used during the U.S. Similarly; Lee de Frost invented Triode and Semiconductors. After his retirement in 1913 Thomas J Watson becomes president of the company which become International Business Machines Corporation (IBM) in 1924.

Electronic Era/Age of Electronic Mechanical ComputerThe electronic era was the time when computers were made with electronics components. Following are some of the historical keys dates and inventions pf cpmputer devices in this era.1937- John V. Atanasoff designed the first special purpose digital electronic computer. Professor Howard Akine constructed electro-mechanical computer named Mark I, which can perform according to pre programming instructions automatically. It was based on Charles Babbage principle after 100 years of his death. Although it was very huge 51 feet long and 8 ft height and 3 ft wide used 18000 vacuum tubes. Similarly Howard Aiken modified Mark 1 and invented Mark II which used 19000 vacuum tubes.1945- John w Mauchly and Presper Eckert built ENIAC (Electronic Numerical Integrator and Calculator) for the U.S. Army. ENIAC was the first machine is used more than 2000 tubes to 18000 tube ENICA which was the first high speed data storage, general purpose electronic digital computer was produce.

5

Page 6: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal1946 UNIVAC (Universal Automatic Computer) was designed by Persper Eckert and John Mauchly are inventors of the ENICA. The UNIVAC was completed in 1950. It was the first commercial computer produced in the United States.1948- Howard Aiken Developed the Harvard Mark III electronic computer with 5000 tubes. The Harvard Mark III, also known as ADEC (Aiken Dahlgren Electronic Calculator) was an early computer that was partly electronic and partly electronic mechanical at Harvard University under US Navy.1952- Remington Rand bought the ERA in 1951 and combined the UNIVAC product in 1952; the UNIVAC 1101 was used to calculate vote of presidential election in US.1950-National Bureau of Standards(NBS) introduced its standards Eastern Automatic Computer with 10000 newly germanium diodes in its logic circuits, and the first magnetic disk drive designed by Jacob Rainbow.1953-Tom Watson and IBM introduced model 604 computers, made up with transistor, which becomes the basic of the model 608, the first solid state computer for the commercial market. 1964- IBM produce SABRE, the first airline reservation tracing system for American Airlines, IBM announce system 360, all purpose computer using for 8 bit character word length.1968- DEC introduced the first minicomputer, the PDP-8 named after the mini skirt, DEC was founded in 1975 by Kenneth H. Olsen which was the project at MIT and began sales of PDP in 1960.1969-Developemtn began on ARPA net, founded by DoD (Department of Defense).1970 – First Microprocessors and Dynamic RAMs were developed by Hoff the first microprocessors 4004.1971- Intel produces Large Scale Integrated (LSI) circuits that were used in digital system support audio device. Gilbert Hyatt at micro computer company introduced 4 bit 4004, a VLSI of 2300 components for Japanese company business to create a single chip for calculator. Similarly IBM introduced the first 8 inch memory disk; it was called then floppy disk. 1972- Intel made the 8 pins 8008 and 8080 microprocessors; Gary Kendall wrote control program for microprocessor disk operating system (DOS) to provide instructions for floppy disk to work with 8080 processors.1973- IBM developed the first true sealed hard disk drive called Winchester at the rifle company, using two 30 mb plates. Robert Metcalfe at Xerox Company created Ethernet for local area network.1975-Bill Gates and Paul Allen established Microsoft Corporation.1976- Job and Woznik developed the Apple personal computer; Alan Shugart introduced 5.2’ floppy disk.1980- IBM signed a contract with Microsoft Company of Bill Gates and Paul Allen and Steve Ballmer to supply an operating system for IBM PC model. 1984- Apple computer introduced the Macintosh personal computer in January 24.1985 Microsoft developed Windows 85 was the first window operating system.1991- World Wide Web (WWW) was developed by Tim Brenner Lee and released by CERN in Korea.1993- The first web browser called Mosaic was created by student Marc Andresen and programmer Eric Binna at NCSA in 1993. The beta version 0.5 of X, UNIX was released in Jan 23 1993.1994- Netscape Navigator 1.0 was released DEC 1994 which covers 75% world market.1996 Intel Corporation introduces pro(X 86) microprocessors.1997- Intel Corporation produced Pentium II1999- Intel Corporation produced Pentium III2000- Intel Corporation produced Pentium IV

History of Computer in Nepal In 2018 BS an electronic calculator called “Fact It” was used for census. In 2028 BS, IBM 1401, a second generation mainframe computer was used in CBS, Kathmandu. In 2031 BS, a center for Electronic Data Processing, later renamed to National Computer Center

(NCC), was established for National Data Processing and Computer Training. In 2038 BS ICL 2950/10, a second generation mainframe computer was used for the census data

calculation. Generations of ComputersA generation refers to the state of improvement in the development of a product.  This term is also used in the different advancement of computer technology.  With each new generation, the circuit structure has become

6

Page 7: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalsmaller and more advanced than the previous generation.  As a result speed, power, and memory of computers have increased dramitacally.  New discoveries are constantly being developed that affect the way we live, work and play. The First Generation:  1946-1958 (The Vacuum Tube Years)

 The first generation computers were huge, slow, expensive, and often undependable.  In 1946two Americans, Presper Eckert, and John Mauchly built the ENIAC electronic computer which used vacuum tubes instead of the mechanical switches of the Mark I.  The ENIAC used thousands of vacuum tubes, which took up a lot of space and gave off a great deal of heat just like light bulbs do.  The ENIAC led to other vacuum tube type computers like the EDVAC (Electronic Discrete Variable Automatic Computer) and the UNIVAC I (Universal Automatic

Computer).         Vacuum tube was an extremely important step in advancement of computers technology.  Vacuum tubes were invented the same time light bulb was invented by Thomas Edison and worked very similar to light bulbs principle.  Its purpose was to act like an amplifier and a switch.  Without any moving parts, vacuum tubes could take very weak signals and make the signal stronger (amplify it).  Vacuum tubes could also stop and start the flow of electricity instantly (switch).  These two properties made the ENIAC computer possible.         The ENIAC gave off much heat that they had to be cooled by big air conditioner.  However even with huge coolers, vacuum tubes still overheated regularly. Characteristics

Very large in size and slower than other generation. Thousand of vacuum tubes were used in a single computer. So they produce large amount of heat and

prone to frequent hardware failure. Punch cards used as secondary storage. Machine level programming language is used. Cost was very high and not available for commercial use. Computing time in milliseconds.

The Second Generation:  1959-1964 (The Era of the Transistor)         The transistor computer did not last as long as the vacuum tube computer lasted, but it was no less important in advancement of computer technology.  In 1947 three scientists, John Bardeen, William Shockley, and Walter Brattain working at AT&T's Bell Labs invented what would replace the vacuum tube forever.  This invention was transistor which functions like vacuum tube it can be used as switch electronic signals. There were obvious differences between transistor and vacuum tube.  The transistor was faster, more reliable, smaller, and much cheaper to build than a vacuum tube.  One transistor replaced the equivalent of 40 vacuum tubes.  These transistors were made of solid material, some of which is silicon, an abundant element (second only to oxygen) found in beach sand and glass.  Therefore they were very cheap to produce.  Transistors conduct electricity faster and better than vacuum tubes.  They were also much smaller and gave off virtually no heat compared to vacuum tubes.  Their use marked a new beginning for the computer.  Without this invention, space travel in the 1960's would not have been possible.  However, a new invention would even further advance our ability to use computers. Characteristics

Transistor were smaller faster and higher reliable compared to tubes. Transistor can do the task of 1000 tubes. They occupied less space and were ten times cheaper than

those using tubes. These transistors had no filament, so they did not generate heat. It requires less electricity less

electricity and emitted less heat than vacuum tubes. Magnetic cores were developed for primary storage and magnetic tapes and magnetic disk for

secondary storage. Second generation computers replaced machine language with assembly language. COBAL (common

Business Oriented Language) and FORTAN (Formula Translation) are in common use during this time.7

Page 8: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal The operating speed was increased up to the Microseconds. Examples: IBM 1401, IBM 1600, 7070, 7080, ICL 1950, Honey Well 400.

 The Third Generation:  1965-1970 (Integrated Circuits)        Transistors were a tremendous breakthrough in advancing the computer.  However no one could predict that thousands even now millions of transistors (circuits) could be compacted in such a small space.  The integrated circuit, or as it is sometimes referred to as semiconductor chip, packs a huge number of transistors onto a single wafer of silicon. Robert Noyce of Fairchild Corporation and Jack Kilby of Texas Instruments independently discovered the amazing attributes of integrated circuits.  Placing such large numbers of transistors on a single chip vastly increased the power of a single computer and lowered its cost considerably.         Since the invention of integrated circuits, the number of transistors that can be placed on a single chip has doubled every two years, shrinking both the size and cost of computers even further and further enhancing its power.  Most electronic devices today use some form of integrated circuits placed on printed circuit boards-- thin pieces of Bakelite or fiberglass that have electrical connections etched onto them -- sometimes called a mother board.         These third generation computers could carry out instructions in billionths of a second.  The size of these machines dropped to the size of small file cabinets. Yet, the single biggest advancement in the computer era was yet to be discovered.The development of the integrated circuit was the hallmark of the third generation of computers. Transistors were re-placed on silicon chips, called semiconductors, which drastically increased the speed and efficiency of computers.A nonmetallic chemical element in the carbon family of elements. Silicon - atomic symbol "Si" - is the second element in the earth's crust, surpassed only by oxygen. Silicon does not occur uncombined in nature. Sand and almost all rocks contain silicon combined with oxygen, forming silica. When silicon combines with other elements, such as iron, aluminum or potassium, a silicate is formed. Compounds of silicon also occur in the atmosphere, natural waters, and many plants and in the bodies of some animals.Silicon is the basic material used to make computer chips, transistors, silicon diodes and other electronic circuits and switching devices because its atomic structure makes the element an ideal semiconductor. Silicon is commonly doped, or mixed, with other elements, such as boron, phosphorous and arsenic, to alter its conductive properties.A chip is a small piece of semi conducting material (usually silicon) on which an integrated circuit is embedded. A typical chip is less than ¼-square inches and can contain millions of electronic components (transistors). Computers consist of many chips placed on electronic boards called printed circuit boards. There are different types of chips. For example, CPU chips (also called microprocessors) contain an entire processing unit, whereas memory chips contain blank memory.Semiconductor is a material that is neither a good conductor of electricity (like copper) nor a good insulator (like rubber). The most common semiconductor materials are silicon and germanium. These materials are then doped to create an excess or lack of electrons.Computer chips, both for CPU and memory, are composed of semiconductor materials. Semiconductors make it possible to miniaturize electronic components, such as transistors. This mean that the components take up less space, it also means that they are faster and require less energy.Instead of punched cards and printouts, users interacted with third generation computers through keyboards and monitors and interfaced with an operating system, which allowed the device to run many different applications at one time with a central program that monitored the memory. Computers for the first time became accessible to a mass audience because they were smaller and cheaper than earlier.Characteristics

Using ICs proved to be highly reliable, relatively inexpensive and faster. Less human labor was required at assembly stage. Computers become portable. They were smaller in size but had high memory. The computer used programming language such as Pascal and Fortan.

Fourth Generation - 1971-Present: Microprocessors8

Page 9: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThe microprocessor brought the fourth generation of computers, as thousands of integrated circuits we rebuilt onto a single silicon chip. A silicon chip that contains a CPU. In the world of personal computers, the terms microprocessor and CPU are used interchangeably. At the heart of all personal computers and most workstations used microprocessor. Microprocessors also control the logic of almost all digital devices, from clock radios to fuel-injection systems for automobiles.Three basic characteristics differentiate microprocessors:

Instruction Set: The set of instructions that the microprocessor can execute. Bandwidth: The number of bits processed in a single instruction. Clock Speed: Given in megahertz (MHz), the clock speed determines how many instructions per

second the processor can execute. In both cases, the higher the value, the more powerful the CPU. For example, a 32-bit microprocessor that runs at 50MHz is more powerful than a 16-bitmicroprocessor that runs at 25MHz.What in the first generation filled an entire room could now fit in the palm of the hand. The Intel 4004chip, developed in 1971, located all the components of the computer - from the central processing unit and memory to input/output controls - on a single chip.Abbreviation of central processing unit, and pronounced as separate letters. The CPU is the brains of the computer. Sometimes referred to simply as the processor or central processor, the CPU is where most calculations take place. In terms of computing power, the CPU is the most important element of a computer system.On large machines, CPUs require one or more printed circuit boards. On personal computers and small workstations, the CPU is housed in a single chip called a microprocessor.Two typical components of a CPU are:

The arithmetic logic unit (ALU), which performs arithmetic and logical operations. The control unit, which extracts instructions from memory and decodes and executes them, calling on

the ALU when necessary. In 1981 IBM introduced its first computer for the home user, and in 1984 Apple introduced the Macintosh. Microprocessors also moved out of the realm of desktop computers and into many areas of life as more and more everyday products began to use microprocessors.As these small computers became more powerful, they could be linked together to form networks, which eventually led to the development of the Internet. Fourth generation computers also saw the development of GUI's, the mouse and handheld devicesCharacteristics

Highly accurate and totally reliable. Operation speed increased beyond Picoseconds and MIPS (Million of Instruction per Second). These chips reduced the physical size of computer and increased

their power. Magnetic and optical storages devices. Sony, Dell, Acer, Compact

Fifth Generation - Present and Beyond: Artificial IntelligenceFifth generation computing devices, based on artificial intelligence, are still in development, though there are some applications, such as voice recognition, that are being used today.Artificial Intelligence is the branch of computer science concerned with making computers behave like humans. The term was coined in 1956 by John McCarthy at the Massachusetts Institute of Technology. Artificial intelligence includes:

Games Playing: programming computers to play games such as chess and checkers Expert Systems: programming computers to make decisions in real-life situations (for example, some

expert systems help doctors diagnose diseases based on symptoms) Natural Language: programming computers to understand natural human languages Neural Networks: Systems that simulate intelligence by attempting to reproduce the types of physical

connections that occur in animal brains 9

Page 10: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal Robotics: programming computers to see and hear and react to other sensory stimuli

Currently, no computers exhibit full artificial intelligence (that is, are able to simulate human behavior). The greatest advances have occurred in the field of games playing. The best computer chess programs are now capable of beating humans. In May, 1997, an IBM super-computer called Deep Blue defeated world chess champion Gary Kasparov in a chess match.In the area of robotics, computers are now widely used in assembly plants, but they are capable only of very limited tasks. Robots have great difficulty identifying objects based on appearance or feel, and they still move and handle objects clumsily.Natural-language processing offers the greatest potential rewards because it would allow people to interact with computers without needing any specialized knowledge. You could simply walk up to a computer and talk to it. Unfortunately, programming computers to understand natural languages has proved to be more difficult than originally thought. Some rudimentary translation systems that translate from one human language to another are in existence, but they are not nearly as good as human translators.There are also voice recognition systems that can convert spoken sounds into written words, but they do not understand what they are writing; they simply take dictation. Even these systems are quite limited -- you must speak slowly and distinctly.In the early 1980s, expert systems were believed to represent the future of artificial intelligence and of computers in general. To date, however, they have not lived up to expectations. Many expert systems help human experts in such fields as medicine and engineering, but they are very expensive to produce and are helpful only in special situations.Today, the hottest area of artificial intelligence is neural networks, which are proving successful in a number of disciplines such as voice recognition and natural-language processing.There are several programming languages that are known as AI languages because they are used almost exclusively for AI applications. The two most common are LISP and Prolog.Characteristics

They will be able to understand natural language, speak command, capacity to see their surrounding and will think power called Artificial Intelligence (AI).

In contrast to present DIPS/ LIPS (Data/ Logic Information Processing System), the 5 th generation will have KIPS (Knowledge Information Processing System).

Will support parallel processing in full fledge

Computer SoftwareSoftware is a computer program which is a sequence of instructions designed to direct a computer to perform certain task. The software enables a computer to receive input, store information, make decisions, manipulate and output data in the correct format. A program consists of instruction that tell the computer what to do and how to behave. When we buy a computer we don’t automatically get every program produced in the world. It may load operating system (like Window XP) if we want to write the text, presentation some slides, do some calculation then we must installed the office package, that is another software.System Software: The most essential for computer operation and directs inter operation of system and its hardware, services, utility, drivers and other preferences configuration files. The programs that are used in past computer system which includes assemblers, compilers, file management, system utility. For example: Windows 85, Windows 98, Window XP, Window Red hat, Window Vista etc.Application Software: The types of software which is used for user’s specific application are called application software. It consists of a number of programs designed to perform specific user application. E.g. Word, Excel, PowerPoint, Photoshop, CorelDraw, Spss, Stata, Epiinfo etcComputer LanguagesComputer program is a set of instruction that execute, causes the computer to behave in a predetermined manner. Without program computers are unless and cannot do anything. However most people are confused computer are intelligent devices but concept is wrong. Computer cannot understand human natural language like English or Nepali. To instruct a computer to perform certain job we need language which can understand by the computer. The languages which are used to instruct the computer to do certain jobs called computer programming languages. There are many programming languages like C, C++,Pascal, Basic etc. There are

10

Page 11: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Programming Language

Low-Level High-Level

Machine Level Assembly Level

OPERAND(Address/Location)

OPCODE(Operation Code)

BE Computer Programming in C Yagya Rimalmainly two types High Level Programming language and Low Level Programming Language. The low level language is closer to the hardware /machine level but than high level programming languages are closer English language. These language extablished the communication between various devices.

Low Level LanguageA language that is acceptable to computer system is called a computer language or programming

language. And the process of writing instructions in such a language for an already planned program is called programming or coding. All computer languages can be broadly classified into the following categories:

Machine Language (1st Generation) Assembly Language (2nd Generation) High-Level Language

o Procedural-oriented Language (3rd Generation)o Problem-oriented Language (4th Generation)o Natural Language (5th Generation)

Machine LanguageIt is a language computer can understand. It is composed of 0’s and 1’s. The machine language of a computer is normally written as strings of binary 1s and 0s. A machine language instruction normally has a two-part format

Operation code, which tells the computer what function to perform and Operand, which tells the computer where to find or store the data or other instruction, which are to be

manipulatedExample: To write an instruction ADD 2 and 3 then we may have to write 01100001(i.e. ADD) 00000010(i.e. 2) and 00000011(i.e. 3)

Machine level language is a language that computers actually understand. The least possible level at which we can program a computer is in its own native machine code.Consisting of strings of 1 and 0, and are stored as binary numbers. Thus machine language is a sequence of instruction written in the form of binary numbers. The main advantages of machine languages is that they execute fast as the computer understand them and does not need translation into other forms. However machine level languages are difficult to write. For e.g. 11=0001101. There are different instruction sets for each operation it is difficult to remember for programming.

Advantages of Machine LanguageProgram written in machine language can be executed very fast by the computer because no translation is required. But difficult to write, even if one bit change whole meaning may change. Lots of inputs required even for doing very small program. Because the internal design of every type of computer is different from every other type of computer, the machine language also differs from computer to computer. In short, writing a program in machine language is so difficult and time consuming that it is rarely used today.Disadvantage of Machine Level LanguageMore Executing Time: As program written in high level language cannot directly generate executable code, it has to be translated into assembly language then to machine language. This takes more time for executions.Need own Translate: To change high level language program into machine level each language its own translator. C is popular middle level language. This doesn’t mean C is less powerful, and hard to use. C combines the advantages of high-level language of assembly language. Like a higher level language, C

11

Page 12: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprovides block structures, stand alone functions, and some small amount of data. Like assembly language, it allows the manipulation of bits, bytes, word and pointers and it is mostly used in system programming.

Assembly LanguageAssembly language use alphanumeric mnemonic codes, instead of numeric codes for instruction in instruction set. For example, using ADD instead of 1110(binary) or 14(decimal). Since CPU doesn’t understand the assembly language, it needs conversion, which is done by Assembler.Assembler: The assembler is software, which translates an assembly language program into an equivalent machine language. But assembly languages have advantage over machine language, they are easier to understand and use. But they are machine dependent.

Assembly language is a symbolic representation (mnemonics) of machine code. They are similar to machine code but cannot understand them easily. The assembly language program must be translated into machine code by a separate program called an assembler. The assembler program recognized the character strings that make up symbolic names of various machines operations. 11 ADD 110 //here ADD is mnemonic for addition.ADD- AdditionSUB- SubtractionINR- IncreaseDCR- DecreaseAdvantages

It is relatively easy to write and read while desing program. It is more convinent that writing machine level language. A program in assembly language is used symbolic instructions which improve readability. It needs less code than high level language.

DisadvantagesHard to Remember: There are large numbers of mnemonics for a machine. It is difficult to remember all the mnemonics for writing assembly language.Machine Dependent: Assembly language is specific to particular machine architecture. Therefore assembly language program written for open processors will not work on different processors if they are architecturally different.Less Efficiently: Assembly language is translated into machine language before execution. Thus a program written in assembly language is less efficient compared to machine level programming.

High-Level LanguageBoth machine and assembly languages are often referred to as low-level programming languages. High-level languages were designed to overcome their limitation such as machine dependent and machine level coding. They are similar to written English. Using high-level language any one without computer science and engineering background can be programmer. They are easy to learn and work but executing they have to be translated into assembly language and then to machine language. So it is slow execution but is efficient for developing programs.Advantages of High-level language

1. Machine Independence: A program written in a high-level language can be executed on any different types of the computers.

2. Easier to Learn and Use: High-level languages are easier to learn, because they are similar to the natural language used by us in our day-to-day life.

3. Fewer Errors: While programming in a high-level language, a programmer need not worry about how and where to store the instructions and data of the program, and need not write machine-level instructions for the steps carried out by the computer.

12

AssembleAssembly language program

Machine language

Page 13: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal4. Better Documentation: The statements of program written in a high-level language are very similar to

the natural english language statement used by us in our day-to-day life. Hence a programmer familiar with the problem domain can easily understand. As a result, very few, or practically no separate comment is required in program written in high-level language.

5. Easier to Maintain: Programs written in high-level language are easier to maintain, they are easier to understand, and hence, it is easier to locate the errors, correct and modify instructions.

6. Portable: High level programming language can be run on different machines with little or no change. It is therefore possible to exchange software migration.

7. Fast Development of Software: The commands of high-level language are very closer to English language so software can be developed with easily and quickly.

Disadvantages of High-level language1. More time to execute because highlevel code must have to compile into machine lecel code2. No direct mechanism to control computer hardware

Procedural-Oriented LanguagesGeneral-purpose programming languages are called procedural languages or third generation language. They are languages such as Pascal, BASIC, COBOL and FORTAN, which are designed to express the logic, procedure, and problem oriented. Because of their flexibility, procedural languages are able to solve a variety of problems.Procedural languages have many advantages over machine and assembly languages:

The program statements resemble English and hence are easier to work with. Because of their English-like nature, less time is required to develop problem solution. Once coded, programs are easier to understand and to modify. The programming languages are machine-independent.

However, procedure-oriented languages still have some disadvantages compared to machine and assembly languages:

Programs execute more slowly. The languages use computer resource less efficiently( memory and devices).

Problem-Oriented LanguageThis is also known as 4GL. This is one step ahead from 3GL. These are result oriented and can included database query language. There are fewer options for programmers, but the programs are much easier to write than in lower level languages. 4GL programs are also needed to be translated either by compiler or interpreter. In fact, 4GL cannot be used for all-purpose. They are dedicated for some particular application developments. Example of 4GL is SQL (structured Query language).

Third Generation Languages Fourth Generation LanguagesIntended for use by professional programmers. May be used by a non-programming end user as well as

a professionalRequires specification of how to perform tasks. System determines how to perform the task.Require large number of procedural instruction Require fewer instructions.Code may be difficult to read, understand and maintain.

Code is easy to understand and maintain because of English-like commands.

Can be difficult to learn Easy to learnTable: Difference between 3GL and 4GL

Natural Language5th generation language, is still in development The computer professionals are being trying to developed language independent form various language with Artificial Intelligante. In such a language we would write statements that look like normal sentence. Natural languages have two characteristics:

They are designed to make inter-connections from humans to machine. The professional are being trying to accept natural language like humanlike.

13

Page 14: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Problem Analysis

Algorithm Development

Flowcharting

Program Coding

Compilation and Execution

Debugging and Testing

Documentation

BE Computer Programming in C Yagya Rimal They are designed to allow the computer to become “smarter” – to actually simulate the learning

process by remembering and improving upon earlier information.

Compiler and InterpreterCompiler: Since computer can directly execute only machine language program, a high-level language program must be converted into its equivalent machine language program before it can be executed on computer. This is done with the help of translator program, which is known as a compiler. A compiler is a translator program, which translates a high-level languages program into its equivalent machine language program. Compiler is language dependent. FORTAN compiler can’t compile COBOL program. In additional to translating, compiler also automatically detects and indicates certain type of errors in source programs.A high level source program must be translated first into a form machine can understand. This is done by software called compiler. The compiler takes the source code as input and produces the machine language code for the machine on which it is to be executed as output. During the process compiler reads the source programs statement wise then checked syntax and errors. In case of any errors, the computer generates message of error. Example: C, C++, Java etc.Interpreter: An interpreter is another type of translator, which is used for translating programs written in high-level languages. The working principle is different from that of compiler in the sense that interpreter reads each line at a time and execute. As compared to compiler, error is detected and brought to the attention as soon as the program is interpreted. The main disadvantage of the interpreter is that they are slower than compiler. An interpreter like compiler is also translating which translate high level language into a machine level language. The difference between compiler and interpreter is their working principle. The intempe translates and executes the program line by line. Every line is checked for syntax errors and then converted to equivalent machine error. Like QBasic, PHP, ASP and PERL.

Compiler InterpreterCompiler scans the entire program before translating into machine code

Interpreters translate and execute the program line by line.

Syntax errors are found only after the compilation of complete program.

Syntax error can be trapped after translation of every line.

It takes less execution time It takes more execution time.Problem Solving Using ComputerIn our daily life we may have a number of problems to be solved using computer for example; sometimes we have to calculate simple interest when principal amount, time and rate are provided, similarly student can calculate his/her percentage, division and position . A computer simply hardware cannot do anything alone without software. Software gives the life to the computer. Actually, software is a set of program written to solve particular problems. On the basic of instruction given to the system computer produces results. If our instructions are not correct the computer produces wrong results. There are number of steps must be follow before writing code to the system. Problem AnalysisAlgorithm DevelopmentFlowchartingProgram CodingCompilation and ExecutionDebugging and TestingDocumentation

Problem Analysis: This step is the process of becoming familiar with the problem that will be solved with the help of computer program. Before solving the problem, it should be analyzed and understood well. It is possible to solve a problem by computer without clear understanding & identification of problems depth. In this stage all the system required, time enough and problem in depth are analyzed. The relationship between

14

Page 15: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalone problem to another and its interdependence between various components should study deeply. This process may start with primary study then detailed studies are done to the specific problem in modern society. Algorithm Development: Algorithm is a step-by-step description of how to solve a particular problem. An algorithm provides step by step description of various methods to solve a problem. It is an effective procedure for solving a problem in a defined number of steps. Algorithm maintains sequences of computer instructions required to solve a problem in such a way that if the instructions are executed in specified sequence. The Desirable Features of an Algorithm are:

1. Each step of the algorithm should be simple.2. It should be unambiguous in the sense that the logic should be clear.3. It should be effective.4. It must end in finite number of steps.

5. It should be an efficient as possible.6. One or more instructions should not be repeated infinitely.7. Desirable result must be obtained on the algorithm termination

Example: Algorithm to multiply two numbers a, b.Step 1: StartStep 2: Input numbers a & bStep 3: Multiply a & b & store on c, i.e. c = a*bStep 4: Display the value of cStep 5: Stop

Developing an algorithm is steps of program design. Let us consider an example of an algorithm for making a tea.

Step 1: StartStep2: Put water in KettleStep 3: Plug the Kettle into switch.Step 4: If the water in the kettle is not boil, then go to step 3.Step 5: Switch off the kettleStep 6: Pour water from the kettle into the teapot.Step 7: Stop

It can be seen that the algorithm has number of steps and some steps involve decision making (step 4) in this case step 4 will waiting for to boil. The rest of steps are in sequences. The algorithm shows the following three features.Sequences (Process): Sequences means that each step or process in the algorithm is executed in the specified order. Each process must be in proper place previous steps must be executed before any other next steps.Decision (Selection): In some cases we have to make decision to do something. If the output of the decision is true, one thing is done otherwise othercontrol should execute. The outcomes of decision either true or false, there is not state in between them. For eg. If the number is less than zero, then the number is negative.Repetition (Iteration or loop): Repetition can be implemented using control statements like loop, while loop, and if – then go to...loop etc.Some Conventions Used in Developing Algorithms Design

Each algorithm will be enclosed by two statements start and stop To accept data form user, input and read statements is used. To display any user message the print display statement is used The arithmetic operators (+,-* and /) are used in the expressions. The relational operators (>,>=,<,<=,==,!=) are used in conditions The logical operators (and or not) are used for logical expressions.

FlowchartThe flowchart is graphical representation of an algorithm using standard symbols. In other words, flowchart is a pictorial representation of an algorithm that used different geometric pictures for different instruction. The flowcharts play vital role in programming to solve problem and they are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn it becomes easy to write the program

15

Page 16: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

CONNECTORFLOW

Start

Read two Numbers A &B

C=A+B

Display C

End

BE Computer Programming in C Yagya Rimalin any high level language. Hence the flowchart is better documentation of the complex program. Flowchart is also a very effective analytical tool. With the help of a flowchart, programmer can quickly show a series of alternative approaches to solve problems.Symbols Used in FlowchartThe various flowchart symbols suggested by ANSI are as follows:

Terminal Symbol: It is used to indicate a point at which the flowchart begins or ends. The words START & STOP are written within the terminal symbol.

Processing Symbol: This symbol represents some operations on data. I/O symbol: It is used to represent the logical positioning of input/output operation. Decision Symbol: This symbol represents a logical operation showing a decision point in a program.

The two main components of a decision symbol are:o A question that defines the logical operation.o The result of the decision (yes, no)

Connector Symbol: It is used to indicate a junction at whom the flowchart comes from a part of the flowchart on another page.

Flow Symbol: A flow symbol is an arrow that shows the flow of program logic in a flowchart.Advantages

Better Communication: Flowcharts are a better way of communications it quickly provides logic, ideas and detailed descriptions of computer operations.

Effective Analysis: Flowchart provides a clear overview of the entire problem and its algorithm for solutions. IT shows all major elements and their relationship among components.

Proper Documentation: The flowchart provides a permanent programming logic. It documents the steps followed in an algorithm. A clearly comprehensive flowchart is an indispensible part of documentations for each program.

Efficient Coding: Flowcharts shows all major parts of a program. Programmer can easily instruct the computer in any platform. The flowchart specifies the steps to be coded and help to prevent errors. Thus flowchart is blue print of system analysis and program development phase.

Easy in Debugging: Flowchart helps easy debugging and maintenance of operation in program. A flowchart is a pictorial representation of a program. Hence it is easier for a programmer to explain

the logic of a program through flowchart. Easy to convert flowchart to programming language

Limitation Complex Logic: A flowchart becomes complex when the program logic is quite complicated.Difficulty in alternation and modifications: if alterations are required the flowchart may need to redrawn completely.

1. Very time consuming and laborious job2. Redrawing a flowchart is a tedious task3. How much to include in flowchart is unclear.

Write an algorithm and draw a flowchart to find the sum of any two numbersAlgorithm

Step 1: StartStep 2: Display “Enter two numbers”Step 3: Read A and B

16

Input/outputProcessTERMINAL

DECISION

Page 17: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Start

Read PTR

i=P*T*R/100

Display i

End

Start

Read Num

Display Positive

End

IsNum<0 ?

Display num is -ve

F T

Start

Display Even

Remainder =0

Display Odd

Calculate remainder

End

TF

BE Computer Programming in C Yagya RimalStep 4: C=A+BStep 5: Display CStep 6: Stop

Write an algorithm and draw a flowchart for calculating the simple interest using the formula i=P*T*R/100Algorithm

Step 1: StartStep 2: Display “Enter Value of PTR”Step 3: Read P,T and RStep 4: i=P*T*R/100 n Step 5: Display iStep 6: Stop

Write an algorithm and draw a flowchart to determine a number whether it is positive or negativeAlgorithm

Step 1: StartStep 2: Display “Enter Numbers”Step 3: Read NumStep 4: if num<0 then display number is -ve If num is==0 display num is +veStep 5: Stop

Write an algorithm and draw a flowchart to test a number is even or oddAlgorithm

Step 1: StartStep 2: Display “Enter Number”Step 3: Read NumStep 4: Calculate remainder by 2Step 5: If remainder =0 then print Even number else print number is oddStep 6: Stop

17

Read Num

Page 18: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Start

Read Num A, B, C

A is Largest

End

Is A>B

B is Largest

A>CB>C

C is Largest

TF

F F

T TT

Start

Read Num

Read nums

End

Is count<num

Sum

Sum=0 &count=1

Sum=Sum+Nums

count=count +1

TF

Read Num

Fact=0 &count=1

Start

End

Is count<=Num

Display factfact=fact*count

count=count +1

BE Computer Programming in C Yagya RimalWrite an algorithm and draw a flowchart to find the largest numbers among three numbersAlgorithm

Step 1: StartStep 2: Display “Enter Three Numbers”Step 3: Read Num A, B, CStep 4: If A>B and A>C then Print A is largest

If B>A and B>C print B is largestElse C is largest

Step 5: Stop

Write an algorithm and draw a flowchart to read N numbers form user and display sum of all numbersAlgorithm

Step 1: StartStep 2: Display “How many numbers?”Step 3: Read Num Step 4: Initialize SUM and CounterStep 5: Read NumbersStep 6: Sum=Sum +num and counter =counter +1Step 7: if counter <=n then go to step 5Step 8: Print sumStep 9: Stop

Write an algorithm and draw a flowchart for calculating the factorial of a given number NAlgorithm

Step 1: StartStep 2: Display “Enter number”Step 3: Read Num Step 4: Initialize SUM and CountStep 5: While count<=Num fact=fact*count count=count+1Step 6: Print factStep 9: Stop

18

Page 19: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalCodingThe coding is process of transforming program logic design into a computer language format. This stage translates program design into computer instructions using some programming language like C, C++ and java. The coding is the act of transforming operation into program statement. The knowledge of computer programming language is necessary to write coding. The code written using programming language is also known as source code. During coding of program, programmer should eliminate all syntax and format errors form the program and all logic errors are detected and resolved during process. Compilation and ExecutionThe process of changing high level language into machine level language is known as compilation. It is done by special software, known as compiler. Compilation process tests the program whether it contains errors or not. If syntax errors are present, compiler cannot compile the code. Once compilation is completed then the program is linked with other object program is competed then the program is linked with other object program needed for execution. Thereby resulting in binary program and then program is loaded in the memory for the purpose of execution. During execution program may ask user for inputs and generates outputs after processing the inputs.Debugging and TestingDebugging is the recovery and correction of programming errors. Even after taking full care in program design and coding, some errors may remain in the program become the programmer might never about case. These errors may appear during compilation or execution of program. When the errors are appeared the debug is necessary. Testing ensure that program perform correctly the required task. Thus programming testing and debugging are very closer.Program DocumentationProgram documentation is description of program and its logic written to support understanding the program structure. Documentation of program helps to use and extend the program future. A program may be difficult to understand even to the programmer who wrote the code after same day. If a program coded by one person is to maintained, there will be more difficult to understand it. Proper documentation is necessary which will be useful and efficient in debugging, texting, maintained and redesign process. Diagrams such as Flow Charts, Comments, Definition list are written inside documentation sections in the program.

Historical Development of C LanguageDuring 60’s there were a number of programming languages developed but almost all were used for specific purpose only. For example FORTAN (Formula Translation) developed by IBM was used for engineering and scientific applications. COBOL (Common Business Oriented Language) developed in 1959 was used for commercial applications especially for business purpose. Due to those specific purpose languages the programmer had to learn more. I.e one language was not for sufficient for every field.Therefore computer scientist started to think for common language for all possible applications. As a result (ALGOL) Algorithm Language was developed by European and American, but ALGOL never really become popular because it seems to general purpose programming language only.To eliminate this problem CPL (Combined Programming language) was developed by the mathematical Laboratory at Cambridge University of London. This collaborative effort was responsible for combined in the name of the language. It was heavily influence by ALGOl. The new language CPL is developed with mixture of FORTAN and COBOL but this is not become more popular.The next efforts the Basic CPL is designed by Martin Richard of the University of Cambridge in 1966, was much simpler language primarily as a system programming language, particularly for writing compiler. At the same time the language B was developed at Bell Labs. It was mostly the work of Ken Thompson with contributions for Dennis Ritchie in 1969. But like BCPL was not become much popular one. At 1972 C was written and designed by Dennis Ritche at AT and Bell Lab for the use of UNIX operating system by inheriting the features of B and BCP language add more features. The origin of C is closely to the development of UNIX operating system. It was named “C” because many of its features were derived from an earlier language “B”. C is a general purpose, structure, procedural imperative language. Some of the most common C compilers are Turbo C/C++ IDE, Borland C/C++, and Microsoft visual C++ etc.

19

Page 20: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalImportance /Advantages of C Programming LanguageRobust Language: C is robust language because which rich set is of built in functions and operators can be used to write any complex program. C compiler combines the capabilities of an Assembly language with the features of high level language.Efficient and Fast: Programs written in C are efficient and fast due to its variety of data types and powerful operators.Highly Portable: C is highly portable; meaning that C program written for one computer can run on another computer with little or no modifications of source code.Structure Language: C is structured language as it has a fixed structure. C program can be divided into numbers of block or modules. Thus, the proper collection of modules would make complete program.Extensibility: C programs may contain a number of user defined functions. We can add our own user defined functions to the C library if required.Middle Level Language: C is middle level language because it combines the best part of high level language with low language. It is well suited for writing both user and machine oriented program.Rich System Library: There are large number of built in functions, keywords and operators in C system library supports.Execution of C Program1 Writing the Source Code Computer instructions are written in a text editor to perform certain jobs. These instructions written using the syntax of C is known as the source code of C program. The source code can be written using any text editor such as Notepad, Turbo C. However it should be saved with “.C” extension. For eg “first.c” is valid filename.2 Compiling and Linking the ProgramThe computer instructions written in the form of source code are translated into executable code with the help of compiler that is suitable for program execution. The translation is done by a special program called compiler that processor statements written in programming language and converts them into a machine level language. So compiling means creating an executable file for particular platform. The compiler first analyzes the entire language statements syntactically one after another and then build the output code called object code. The object codes are machine code that the processors can process or execute one instruction at a time.During compilation linking process takes place. Linking is the process of putting translated program and other objects from system library such as reading inputs, producing output and computing mathematical functions. To create an executable program the object program must be linked to system library subprogram.Compile-> Link3 Execution of ProgramWhile execution of program the loadder loads executable object code into the computer memory that executes the instruction. During execution, the program may require for some data to be entered through the keyboard. Run-> Run (Ctrl+F9)Basic Structure of C ProgramThe structure of C program implies composition of a program it describes main components to write in C program, how are they organized. The following table shows the parts are included in the structure of C program.

Documentation SectionLinking SectionDefinition SectionGlobal Decelerationmain() functionSub program()

1 Documentation SectionThis section contains a set of comments lines giving the name of program, the designer may write algorithm, methods used and other detail information related to the program. This will be useful in further for users and development teams. Documentation acts as a communication medium between members of development team

20

Page 21: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalworking in the same project. It helps while debugging and testing the program. * This program display natural numbers from 1 to 10*/Note: /*----- */ denotes comments in C Whatever the text written within comment if just ignore by the compiler.2 Linking SectionThis section provides instruction to the compiler to link functions with program from the system library. #include<stdio.h>#include<conio.h>/* It links system function library i/o that handles printf() and scanf()functions. They are preprocessors which provide the designer platform to design program.3 Definition Sections: In this section all symbolic constants are defined. #define PI 3.14164 Global Deceleration: The variables which are used in more than one function/block are called global variables. Those variables are defined in this section. This section also defined all the user defined functions.5 Main Functions: Every C program must have one main function through which program starts execution. The main function has deceleration and execution parts. Deceleration part declares all the variables used in the program execution part. In this section some sort of calculation and other functionality are to be kept. E.g.int i,k;/*deceleration of integer variable to store integer value*/i=90,k=4*i;/*execution part and assignment parts.*/6 Subprogram: This section contains all the user defined functions that are called in the main function.Write a program to print Welcome to C Programming!!!!

/*A C program display "Welcome to C Programming"*//* This program is prepared by Yagya Rimal*//* This Documentation line*/#include<stdio.h>#include<conio.h>void main(){clrscr();printf("Welcome to C Programming !!!!");getch(); }outputWelcome to C Programming!!!!

Explanation/*A C program display "Welcome to C Programming"*//* This program is prepared by Yagya Rimal*//* This Documentation line*/

The first three lines are comments lines. Comments are used for documentations purpose in C. While compiling the program the comments are not compiled and thus they are not verified for syntax checked. Thus we can write anything text as comment. Comments in C begins with and /* and ends with */ signs. The comments can be written any place in the program whenever it required.

#include<stdio.h>#include<conio.h>

Includes two header files <stdio.h> and <conio.h> are used to do some specific job, we have to used any number of functions they are kept already defined in C built in library, for example printf () function is to display the output to the screen, scanf () function to read data form keyboard, clrscr() function to clear computer screen, sqrt() to calculate square root of a number. They are header file form where we can get printf() and scanf() functionality to our program. Similarly functions related to mathematical calculation are kept under <math.h> header file. Each header files must start with # and enclosed with <and> signs. Thus it is concluded that we cannot use any library functions unless we include related header files. The number of header files to be included in the program depends upon on the functions used in our program.

void main(){ }The main function begins the program execution. All C programs must have at least one main function. It is the entry point of our program. Executing of any program starts from the main function and ends at main function. The void before main is return type but void means does not return any value after calculation.

21

Page 22: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThe opening curly brace ({) after main method represents the beginning of the function the body of main function is also closed by curly brace (}) represent the end of main function body. The statements written {inside main} are statements of main method. We must have to write all our code inside it.

clrscr ();This library function resides under <conio.h> header file. Thus function is used here to clear old content on the output screen. If this function is not used, the text Welcome to C Programming is displayed on the screen as appended text.printf(“Welcome to C Programming !!!!”); is used to display text message in computer screen. Thus anything written within double code is displayed in the screen without any changed. The compiler just displayed them.

getch();Is not compulsory here, if we do not use this function, we have to press Alt +F5 to see the output of the program. This statement holds screen such that we can easily observe the output. Actually getch () is input function it waits for a character form keyboard without echo.Write a program to add two numbers

#include<stdio.h>#include<conio.h>void main(){int a,b,sum; a=10,b=20;sum=a+b;printf("The sum is:%d",sum);getch();}outputThe sum is: 30

WAP to demonstrate sub program that calculate πr*r#include<stdio.h>#include<conio.h>#define PI 3.1416float area(float radius){return (PI*radius*radius);}void main(){ float r,a;clrscr();r=5.0;a=area(r);printf("Area of circle radius %f is %f",r,a);getch();}Output:Area of circle radius 5 is78.546

TURBO C/C++ IDETurbo C is Borland C compiler and Integrated Development Environment (IDE) for the C programming language. It was developed first in 1987 and was noted for its integrated development environment in may 1990 Borland replace Turbo C++. This section gives brief information about the Turbo C V3.0 application interface. Turbo C InterfaceMenu Bar: The menu bar consists of all the menu items. We can select a certain item either by using the keyboard, mouse. For example to save a file File-> SaveClose Window: The close window bottom [] can used to close current active window.File Unsaved: The file unsaved notification [*] appears when the file has been altered and not saved. It will automatically disappear once the file is saved.Filename: The filename appears in the middle of the window. By default, TC names each file as NOMAME<XXX>.C, Where XX stands for two digits number.Line x Column y: This shows the current line and column position of the cursor. Maximum/Restore:The maximize [] and [] button can be used to either maximize or restore the current window.Window Number:This show number respective to how many widows currently are open.Code Editing Area: This is the main body of TC where we code and edit all our programs.

22

Page 23: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalMessage Box: In the message box, messages invoked TC are shown. These messages depend on the kind of operation the user issue. Steps Guide : We start with a new editable area by selecting the menu sequence file-> new Once we have coded, we save the file. To do so we either use menu sequence file-> save or pres F2, then the following save file as dialogue box will appearThen change the default file name noname00.CPP to “hello.C”. We should follow the file naming conventions. We must always save the file with”.c” extension (not.cpp)Always Save in BIN Directory C :\TC\BIN\The file name should be less than 8 characters; otherwise TC will concatenate the file name. We must give any suitable name. Once we have saved our file name hello.c will appear at the middle top of the window at the file unsaved notification will disappear automatically.Compile the ProgramTo do so we either use the menu sequence.> compile or simply press ALT +F9. Then the following compiling box will appear. If an errors messages will appears those should have to resolve properly. After successful compilation two files will be created in BIN directory-> an executable object code (.obj) and executable file (.exe). Both file will have same name as our C file . The next step is to link the functions used in our program with the header files, however TC will automatically do the linking process during execution. Our final step is to run the executable file hello .exe. There are two modes to run hello. The auto exec files from the window mode by navigating the Bin directory. Other just hello.exe form TC itself. Run or (CTRL+F9 then the desired output will be shown).Character Set: The set of characters that used to form words, numbers, and expression in C is called character set. The combination of these characters form words, numbers and expressions in C. The characters in C are grouped into the following four categoriesLetters or Alphabets: Upper Case / Lower Cases (A-Z, a-z)Digits:0 to 9Special Characters :(,,;?,””,\,/-,>,^&,%,*,/=,+!,{()}>,<,[~,! etc)White Space: (Blank space, Horizontal tab, Carriage return, New line, Form feed)Keywords: Keywords are predefined words for C program. All keywords have fixed meaning and these meanings cannot be changed. They serve as basic building blocks for program statements. They are as: auto, double, int, void, struct, typedef, char, default, do, goto, if else, return, for, while, switch etc. These words are used for pre-defined purpose and cannot be used as identifiers to declare variable name. Thus the keywords are also called reserved words.Data Types: There are various data types for example 10 and 100.4 are data of different items. The data 10 is integer number where as 100.4 is fractional number. There are other varieties of data type supported by C, each may be represented differently within computers memory. The varieties of data type of C supports are: Primary data typeUser-defined data type and Derived data types The primary data types and derived are discussed in this section. The user defined data types such as arrays, functions, structures and pointers are discussed in next chapters. There are five primary data types they are:Integer (int)Floating point type (float)Double-precision floating type (float) Character Type (char) andVoid Type (void) Integer Type: The integers are whole numbers, non fractional numbers. Generally integer requires 16 bytes (2 bit) of storage area. C has further three types of integer they are int, short, and long inall three data types there are two sign and unsigned forms. The appropriate data types are used according to our requirements.

Signed Integer(signed int) Unsigned integer(unsigned int)It represents both positive and negative integers.

It represents only positive integers

23

Page 24: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThe data type qualifiers is signed int or intVariable are defined as signed int a, b;

The data qualifier is Unsigned int or unsigned. Variables are defined as unsigned int a,b;

By default all int are signed Unsigned int have to declared explicitlyIt reserves 16 bits(2 bytes) in memory It reserves 16 bits(2 bytes)in memoryInt represents values of range -32768 to +32767 (2-15 to 2 15 -1)

It represents integer values of range 0 to -2 16 -1 (0 to 65535)

Its conversion character is %d Its conversion character is %u1 bits 15 bits

Signed short Integer(signed short int) Unsigned Short integer(unsigned short int)It represents both positive and negative integers.

It represents only positive integers

The data type qualifiers is signed int or short intVariable are defined as signed short int a, b;

The data qualifier is unsigned short int or unsigned. Variables are defined as unsigned short int a,b;

By default all short int are signed. Unsigned short int have to declared explicitlyIt reserves 16 bits(2 bytes) in memory It reserves 16 bits(2 bytes)in memoryInt represents values of range -0 to 255( 8 bits) It represents integer values of range (-127 to 128)

bitsIts conversion character is %d or %i Its conversion character is %u

Signed long Integer(signed long int) Unsigned Long integer(unsigned long int)It represents both positive and negative integers. It represents only positive integersThe data type qualifiers is signed long int or long int . Variable are defined as signed long int a, b;

The data qualifier is unsigned long int or unsigned. Variables are defined as unsigned long int a,b;

By default all short int are signed. Unsigned long int have to declared explicitlyIt reserves 32 bits(4 bytes) in memory It reserves 32bits(4 bytes)in memoryInt represents values of range -2147483648 to +2147483647 (-2 31 to +2 31 -1)

It represents integer values of range 0 to +2 32 -1 (0 to 4294967295)

Its conversion character is %id Its conversion character is %luFloating Point Types: Floating point types are factional numbers. They are defined in C with keyword float. Floating numbers reserve 32 bytes (4) bytes of storage with 6 digits of precision.Float It reserves 4 bytes in memoryIt represents fractional numbers of range 3.4* 10-38 to -3.4 1+38

The data type qualifier is float variable declaration as float a;Its conversion character is % f.Double Precision Floating Point Type : When accuracy provided by a float number is not sufficient, the type double can be used to define the number. A double data type number used 64 bits (8 bytes) giving a precision of 14 digits. There are double expression numbers. To extent the precision further long double can be used which use 80 bits (10bytes) giving 18 digits of precision.Character Type: A single character can be defined as a character type data. Characters are stored in 8 bits (1 byte). The qualifier is char. The qualifier signed and unsigned may be used with char. The unsigned char has values between 0 to 255. The sighed char has values form -128 to 127. The conversion character for this type is % c.Void Data Type: The void type has no return values. This is usually used to specify a type of function when it does not return any value to the calling function. User Defined Data Types: C supports type definition which allows defining an identifier that would represent and existing data type. The typedef statement is used to give new name to an existing data type. It allows user to define new data types that are equal to existing data types. It takes the general formtypedef int integer;Here integer symbolizes int data type. Now we can declare int variable a as integer a instead of int a.

24

Page 25: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimaltypedef float decimal;Here float f is equivalent to decimal f. Thus typedef statement is used to alias existing data types as convenient.Constants: Constant is quantity that does not change during the execution of program. C supports constant can be divided into different category. They are: Integer Constants: Integer constant refers to a sequence of digits with not decimal point either positive or negative. If no sign precedes an integer constant, it is assumed to be positive. No commas or blank spaces are allowed within the integer constant. Example 345,456,-8765.There are three type of integer namely decimal, octal and hexadecimal.Decimal Integer Constant: The decimal integer constant are the set of digits 0 to 9 proceeded by an optional – or + signs. Here decimal does not imply fractional numbers. It represent numbers having base of 10.Octal Integer Constants: An octal integer constant consists of any combination of digits for the set form 0 to 7, with leading 0. Valid example are 074, 0676.Hexadecimal Integer Constants: A hexadecimal integer constant consists of any combination of digits form the set of 0 to 9 and ABCDEF with leading) 0X examples are 0x345, 0x123, 0xaA.WAP to demonstrate integer constant of Decimal, Octal and Hexadecimal

#include<conio.h>void main(){int a,b,c;a=10; b=010; c=0xe1;printf("Decimal integer is %d and num is%d",a,10);printf("\n Octal equivalent is %d\t%o",b,8);printf("\n Hexadecimal representation %d\t%0x",c,225);getch(); }Output Decimal integer is 10 and num is 10Octal equivalent is 8 10Hexadecimal representation 225 e1

Real Constant: Real constants are often called floating point constants. They can be written into two forms- fractional form and exponential form. Real constants are two types.Fractional Constant: Fractional form of constants must have at least one digit and a decimal point. It can either be positive or negative but default sing is positive. Commas or blank space are not allowed within a real constant. For example _23.56, 45.9,-67.5003 are in fractional form.Exponential Constant: In exponential represention, the real constant is represented in two parts mantissa and exponents. The digit before is called mantissa and after is called exponent. The mantissa part may be positive or negative sign but default is positive. Similarly, the exponents must have at least one digit which can either positive or negative for eg. +3.2e5, 9.1e6.Character Constant: A character constant is single character alphabet digit or special symbol enclosed within single ‘ ‘ marks. For example ‘A’ is a valid character. The maximum length of a character constant can be only one character. It must enclose by single code for example: ‘a’,’g’.WAP to demonstrate character constant

#include<stdio.h>#include<conio.h>void main(){ int n=4; char c='4';n=n+5;//n=9c=c+5; // 52+5=57 here char starts from 48 ,49,50,51 ..for.,0,a,b,c,d so onprintf("integer is %d",n); //9printf("\n character =%d",c); //57 if you used %c then 9 will display bacause c is9 beforegetch();}Outputinteger is 9character 57

25

Page 26: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalString Constant: A string constant is a sequence of characters enclosed in double quotes. It may contain letters numbers or special characters or blank space. However it does not have an equivalent ASCII value. For example “Hello good morning”. This must be enclosed by double coated(“”).

Variables: A variable is a symbolic name which is used to store data items. Variables are defined in a computer program to represent an item of data input by the user, any intermediate calculations results. Unlike constant the value of variable can change during the execution of a program. The same variable can store different values at a different portion of program.

Variable name may constant of letters, digits, or underscore characters. Since a variable is an identifier, the rules for naming variables are similar to those of identifiers Some valid examples data type nepal, first name, num1,x2, email_id etc can be used Some invalid example: data type, 1nepal, (total), first name, %male, etc are not allowed.

Need for Variable Declaration : The declaration of variable associates the variable with a specific data type. This means each variable must be declared or defined as what type it is. By doing this the compiler will allocate a memory space in the computer as required by data type.Thus variables are assigned with specific data type according to the values to be stored. If we have integer values to store, we need to define a variable of type int .It gives the name of variable and its types should have matched properly, when we declared it. It allocates appropriate memory space according to the data types declared infornt of it.Rules for Variable Declaration

The variable should be stored with only letters or underscore.(itn i; int_p;) The variable name should not be any keyword.( int auto,int int, int do;) The variable name is case sensitive characters.(if you declared a variable x then while accessing it

donot use X: these two are different representation) No two variables of the same name are allowed.(int i; int i are not allowed in same program) It must starts form letters/alphabets.( int a1, char p2 not but int 1a are not allowed)

Preprocessor Directives: Preprocessor directive is a collection of special statements that are executed in the beginning of compilation process. They are written in source program before the main program. Preprocessor directives follows special syntax rules that are different form normal C syntax. They all begins with the symbol # (Hash) and donot require semicolon at end. Preprocessor provides the plateform for each program.

#include<stdio.h>/*used for standard input and output*/#include<conio.h>#define PI 3.1416/*defining symbol*/#define TRUE 1 /*used for defining TRUE as 1*/#define FALSE 0/*used for defining FALSE as 0*/

These statements are called preprocessor directives as they preprocessed source prograam before compilation of any source code in the program. The other codes in the program are compiled sequentially line –by line. The stdio.h and conio.h are pre-requistite preprocessors for every program.Escape Sequence: An escape sequence is non-printing characters used in C. It is character combination of backslash followed by latter or by combination of digits. Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal represents of characters that have special meanings such as double quotation mark (“”).

#include<stdio.h>#include<conio.h>void main(){printf (“Hello\n I am testing escape sequence”);getch(); }Output: HelloI am testing escape sequence

Generally, any text written within double quotes (“”) in printf () function will be displayed on the screen. There are some more escape sequences .

\a Alert purpose by an auditable alert or beep sound\b To delete one character to the left of current cursor position

26

Page 27: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal\f Form feet to feed a blank page when the user prints the document\n Line feed next line\r Carriage return move cursor to the next line during typing\t Horizontal tabs to move cursor to next tab stop position\0 For null characters

WAP to demonstrate Escape sequences used in C program#include<stdio.h>#include<conio.h>void main(){printf("Hello\t World\n");printf("He said,\"Hello\"");getch(); }Output:Hello WorldHe said “Hello”

Symbolic Constant: A symbolic constant is a name that is used in place of sequence of characters. The character may represent numeric, a character constant or a string constant. When a program is compiled, each occurrence of symbolic constant is replaced by its corresponding character sequences.WAP to demonstrate symbolic constant then calculate area of circle form user input

#include<stdio.h>#include<conio.h>#define PI 3.1416void main(){float r1,r2,r3,a1,a2,a3; clrscr();printf("Enter three radius of different circle");scanf("%f%f%f",&r1,&r2,&r3);a1=PI*r1*r1; a2=PI*r2*r2; a3=PI*r3*r3;printf("\n Area of first circle is%.2f",a1);printf("\n Area of second circle is%.2f",a2);printf("\n Area of third circle is%.2f",a3);getch(); }OutputEnter three radius of different circle 3 4 5Area of first circle is 28.27Area of second circle is 50.27Area of third circle is 78.54

Write a program to add two numbers and display their products#include<stdio.h>#include<conio.h>void main(){float a,b,sum; clrscr();printf("Enter two numbers");scanf("%f%f",&a,&b);sum=a*b;printf("\n the sum is%f",sum);getch();}Output:Enter two numbers 5 6the sum is 30.000000

Write a program that will convert temperature in Centigrade into Fahrenheit#include<stdio.h>#include<conio.h>void main(){float centi, fah; clrscr();printf("Enter Temperature in Centigrade");//37

27

Page 28: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalscanf("%f",&centi);fah=(9.0/5)*centi+32;/*centi=(5.0/9)(fah-32)* for centigrade/printf("\n the equivalent temperature in fre is%f",fah);//98.599998getch();}

Write a C program to ask the name of student and marks obtained in seven subjects. Display the percentage of student assuming full marks 100 for each subject.

#include<stdio.h>#include<conio.h>void main(){ char name[10];float math,phy,bio,eng,comp,nepali,che, total ,percentage;clrscr();printf("Enter name of student");scanf("%s",name);printf("Enter marks of seven subjects");

scanf("%f%f%f%f%f%f%f",&math,&phy,&bio,&eng,&comp,&nepali,&che);total=(math+phy+bio+eng+comp+nepali+che);percentage=total/7;printf("the percetage of %s is%.2f",percentage);getch();}Output:Enter name of student ShyamEnter marks of seven subjects 90 23 56 89 65 44 65The percentage of Shyam is 61.71

Write a program that ask three coefficient of quadratic equation and calculate its roots.#include<stdio.h>#include<conio.h>#include<math.h>void main(){float a,b,c,discr, root1,root2; clrscr();printf("Enter the coefficient of x^2:"); scanf("%f",&a);printf("Enter the coefficient of y^2:"); scanf("%f",&b); printf("Enter the coefficient of z^2:"); scanf("%f",&c);discr=b*b-4*a*c;root1=(-b+sqrt(discr))/(2*a); root2=(-b-sqrt(discr))/2*a;printf("root1%f and root2%f",root1,root2);getch(); }Output:Enter the coefficient of x^2: 2Enter the coefficient of x^2: 3Enter the coefficient of x^2: 1root1=-0.50000 and root2=-4.00000

Write a program to convert the Cartesian coordinate to polar coordinate#include<stdio.h>#include<conio.h>#include<math.h>#define PI 3.1416void main(){float x,y,r,q,angle; clrscr();printf("Enter Cartesian coordinate x&y:");scanf("%f%f",&x,&y);r=sqrt(x*x+y*y); q=atan(y/x); angle=180*q/PI;printf("r=%f and angle in degree =%.2f",r,angle);getch(); }Output:Enter Cartesian coordinate x&y 1 1R=1.4142 and angle in degree=45.00

28

Page 29: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalWrite a program to find total amount when simple interest and compound interest are used after T years and principle p entered by user also find their differences

#include<stdio.h>#include<conio.h>#include<math.h>void main(){float p,t,r,si,sa,ca,ci; clrscr();printf("Enter principal in Rs"); scanf("%f",&p);printf("Enter Time in years"); scanf("%f",&t);printf("Enter rate per anum"); scanf("%f",&r);si=(p*t*r)/100; ci=p*(pow(1+r/100,t)-1);sa=p+si; //simple amountca=p+ci; // compound amountprintf("\nsimple interest=%.2f\n simple amount=%.2f,",si,sa);printf("\n compound interest =%.2f\n compound amount=%.2f",ci,ca);printf("\nthe differences is %.2f",ca-sa);getch();}output:Enter principal in Rs 1000Enter Time in years 2Enter rate per anum 20simple interest=400.00simple amount=1400.00compound interest=440.00compound amount=1440.00the differences is 40.00

The length and breadth of a rectangle are input from user write a program to calculate area and perimeter. #include<stdio.h>

#include<conio.h>#include<math.h>void main(){float l,b,a,p;clrscr();printf("Enter length breadth");scanf("%f%f",&l,&b);a=l*b;p=2*(l*b);printf("\nthe area of rectangle is %f",a);printf("\nthe perimeter of rectangle is %f",p);getch();}OutputEnter length breadth 2.5 1.5the area of rectangle is 3.750000the perimeter of rectangle is8.0000

WAP to read height and base of triangle and find area#include<stdio.h>#include<conio.h>void main(){ float h,b,a; clrscr();printf("Enter height breadth"); scanf("%f%f",&h,&b);a=0.5*h*b;printf("\n the area of triangle is %f",a);getch();}Output:Enter height breadth 5 3.5the area of triangle is 8.750

29

Page 30: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalRead three sides of triangle and calculate the area of triangle

#include<stdio.h>#include<conio.h>#include<math.h>void main(){float a,b,c,s,area; clrscr();printf("Enter three sides of triangle a,b,c");scanf("%f%f%f",&a,&b,&c);s=(a+b+c)/2 ; area=sqrt(s*(s-a)*(s-b)*(s-c));printf("\nthe area of triangle is %.2f",area);getch();}Output:Enter three sides of triangle a,b,c 3 4 5the area of triangle is 6.00

WAP to interchange two variable form users#include<stdio.h>#include<conio.h>void main(){ int a,b, temp;clrscr();printf("Enter two numbers");scanf("%d%d",&a,&b);printf("before interchange a=%d\tb=%d",a,b);temp=a; a=b; b=temp;printf("after interchange a=%d\tb=%d",a,b);getch();}OutputEnter two numbers 5 6 before interchange a=5 b=6after interchange a=6 b=5

WAP to demonstrate numbers system#include<stdio.h>#include<conio.h>void main(){ int a=10,b=5,c; c=a+b;printf("\n Hexadecimal is:\t%x",c);printf("\nLarge Hexadecimals \t%X", c);printf("\nDecimal \t%d",c);printf("\n Octal\t%o",c);getch();}Output:Hexadecimal is fLarge Hexadecimal FDecimal 15Octal 17

Operators: An operator is a symbol that operates some sort of calculation. Operators are used in programming to perform certain mathematical or logical manipulations. For example, in a simple expression 9+67 the symbol + is called an operator which operates on two items 9 and 67 are operands. The data items that operate through operator are called operands. Here 9 and 67 are operands. According to the number of operands required for an calculation, we can classify operators into unary, binary and ternary.Unary Operators: The operator which requires only one operand is known as unary operators. For example: ++ increment – decrement, a++,--a,++a, Here only one variable is used.Binary Operators: The operators which requires two operand are known as binary operators for example + - * / >, < , a+b, a/b etc are binary operator.Ternary Operators: The operators that require three operands are known as ternary operators for example?: is conditional operator. C operators can be classified into a number of categories

Arithmetic operators

30

Page 31: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal Relational operators Logical operators Assignment operators Increment and decrement operator Conditional operators Conditional operators Bitwise operators Special operators

Arithmetic Operators: An arithmetic operator performs arithmetic operations. There are five arithmetic operators in C.

Operator Meaning Example Output int A=20 , B=6 c=6;+ Addition A+B 26- Subtraction A-B 14* Multiplication A*B 120/ Division A/B 3% Modulo A%C 2(gives remainder)

The +,-,*, / all work in the same way in usual mathematics. The modulo operator (%) calculates remainder after division of one integer operand by another integer operand. So the remainder of 20 divided 6 will give remainder 2but 8%2=0 gives zero as remander. Integer Arithmetic: When the operands in a single arithmetic expression such as a+b are integer, the expression is called an integer arithmetic expression. Integer arithmetic always yields an integer value. That is why the operation 20/6 in the above example yields 3. The factional positions of actual results (3.333333) are truncated.

Division Rulesint/int=int float/float=floatint/float=float float/int=float

During integer decision if both operands are of same sign, the results truncated towards zero.4/7=0. However if one of the operands is negative then the direction of truncated is machine dependent. This is -4/7 may be 0 or 1 depending upon the machine. Similarly during modulo, the sign of the result is always the sign of the first operand. 20% 3=2, -20%3=-2, the modulo division operation cannot used on floating point data.WAP to demonstrate Arithmetic operators

#include<stdio.h>#include<conio.h>void main(){int a,b,c; float d,e,f;a=10; b=3; c=5; d=20.5; e=10.25; f=3.5;printf("a/b=%d\t a/c=%d\n",a/b,a/c);printf("d/e=%f\t d/f=%f\t d/a=%f",d/e,d/f,d/a);getch();}Output:a/b=3 a/c=2 d/e=2.0000 d/f=5.857571 d/a=2.0500

Relational Operator: Relational operators are used to compare two similar operands, and depending on their relation, take some actions. The relational operators compare their left hand side operand with the right hand side operand by using lesser than, greater than, lesser than or equal to relations. The value of relational expression is either 1 or 0 (if conditions is false 0 will produce where as if condition is true result become 1).

Operator Meaning Example Output(int a=20,b=6)< Less Than A<b 0> Greater than a>b 1<= Less than or equal A<=b 0>= Greater than or equal a>=b 1

31

Page 32: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal== Equal to A==b 0!= Not equal to A!=b 1

WAP to Demonstrate Relational Operators#include<stdio.h>#include<conio.h>void main(){int a=14,b=33,c=14;clrscr();printf("a<b=>%d\t a>b=>%d",a<b,a>b);printf("\na==c =>c>%d\t a<=c=c=>%d\ta>=c =>%d",a==c,a<=c,a>=c);getch();}Outputa<b=>1 a>b=>0a==c=>1 a<=c=>1 a>=c=>1

Logical Operator : Logical operators are used to compare or evaluate logical and relational expressions. The operands of these operators must produce either 1 or 0. The whole result produce by these operators is also either true or false. There are three logical operators used in C programming.

(&&) Logical AND (||) Logical OR(! )Logical NOT

The logical and produces produce true if both of operands are true.A B A&&b A||

b!a !b

0 0 0 0 1 00 1 0 1 1 01 0 0 1 0 11 1 1 1 0 1

If (student has passed in intermediate level and passed in entrance exam) {They are eligible to admit in BE.WAP to demonstrate logical operators

#include<stdio.h>#include<conio.h>void main(){int a=10,b=5,c=40;clrscr();printf("\n a<b&&a<c=>%d",(a<b&&a<c));printf("\n a>b&&b<c=>%d",(a>b&&b<c));printf("\n a<b||a<c=>%d",(a<b||a<c));printf("\n a>b||b<c=>%d",(a>b||b<c));printf("\n a>c||b>c=>%d",(a>c||b>c));getch();}Outputa<b&&a<c=>0a>b&&b<c=>1a<b||a<c=>1a>b||b<c=>1a>c||b>c=>0

Assignment Operator: Assignment operators are used to assign the result of an expression to a variable. The common assignment operator is =. There are other various shorthand’s assignments they are:

a+=b// equivalent to a=a+b;a-=b// equal to a=a-b;a*=b// a=a*ba/=b//a=a/ba%=b=a=a%b

If two operands in assignment expressions are different data type, then the value of expression on the right will automatically be converted to the type of identifier on left.

32

Page 33: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal A floating-point value may be truncated if assignment to an integer. A double precision value may be rounded if assignment to floating point value. An integer quantity may be altered if assignment to a shorter integer variable.

Increment and Decrement Operators: The increment operator is to increase the variable of an operand by 1, and the decrement operator is used to decrease the value of an operand by 1. They take only one operand, so called unary operator.The increment/decrement operators are prefix or postfix in prefix notation, the value of variable is first incremented or decremented and then the value is assigned to the variable.Similarly, the postfixes, first the previous value of variable is used and then the value is incremented or decremented.WAP to demonstrate increment and decrement operators

#include<stdio.h>#include<conio.h>void main(){int a=10;clrscr();printf("a=%d\n",a); //10printf("a=%d\n",++a); //11printf("a=%d\n",a++);// 11printf("a=%d\n",a); //12getch();}

Conditional Operator: The conditional operator that takes three operands so it is also called ternary operator. The syntax of this operator is Expression1? Expression2: Expression 3.Here, expression 1 is evaluated first, if Expression 1 is true, the value of Expression 2 is assigned to the large variable. Else Expression 1 is false then value of Expression3 is assigned to the large variable.WAP to demonstrate conditional operators and find out largest among two numbers

#include<stdio.h>#include<conio.h>void main(){int n1,n2,larger;clrscr();printf("Enter two numbers");scanf("%d%d",&n1,&n2);larger = n1>n2?n1:n2;printf("The largest number is %d",larger);getch();}OutputEnter two numbers 35 90The largest number is 90

Comma Operator: The comma operator can be used to link related expressions together. Comma linked lists of expressions are evaluated from left to right and the value of the rightmost expression is the value of the combined expression.

N2=(n1=50, n2=10,n1+n2)This will first assign the value 50 to n1, then again 10 is assign to n2 variables. The finally the sum is calculated then assigned to N2 variable (n1+n2 ie 60). Since comma operator has lower precedence of all operators.Sizeof Operator: The sizeof operator is used with an operand to return the number of bytes it occupies. It is a compile time operand. The operand may be a constant, value or data type qualifier as following. The syntax sizeof(argument). Here sizeof operator gives its argument size.WAP to demonstrate sizeof operators

#include<stdio.h>#include<conio.h>void main(){ int n1;

33

Page 34: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("Integer Variable=>%d\n",sizeof(n1));printf("Double Constant=>%d\n",sizeof(15.11));printf("Long Int data =>%d\n",sizeof(15L));getch();}OutputInteger Variable =>2Double Constant =>8Long Int data=>4

Operator Precedence: The precedence is used to determine how an expression is evaluated and which order it will start to evaluation among various operators used. There are distinct levels of precedence and an operator may belong to one of these levels. The operators at the higher level of precedence are evaluated first. The operators of same precedence are evaluated either form left to right or right to left depending to the level . This is known as associatively property of an operator.

Precedence Operator Description Associatively1 (Highest) ()[] Function call Left to right

2 +,-,++,--,!,~,*,&,sizeof, type

Unary, increment/decrement, address, pointer, type cast

Right to left

3 *,/,% Multiplication/ division/modulo l-R4 +,- Addition/division L-R5 <<,<=<>,>= Relational L-R6 ==,!= Relational L-R

7 &,|<&&,||?: Logical L-R8 =,*=,/=,+= Assignment Right to Left9(Lowest) , Comma L-R

Example: 9-12/(3+3)*(2-1)9-12/6*19-2*19-27

The parenthesis may also be nested. In such case the evaluation of expression will precede form the innermost set of parenthesis to outwards9-(12/(3+3)*(2-1)=49-((12/3)+3*2)-1=-2if(x==10+15&&y<10)Similarly the relational operators of which has a higher priority than the logical operator (&&) and the relational operators (==and<). So the addition of 10 and 15 is executed first then it become like as if(x==25&&y<10) The next step is to evaluate the relational operators, of which == operator has higher priority. Suppose x=20 and y=5.if(20==25&& true)if(false&&true) False output ie 0 will be display.

Type Conversion in Expression: C allows mixing of constants and variables of different types in single expression. In such situation, one type must be converted to another before evaluation can be done. This kind of conversion is called type conversion. The common type conversion are two types implicitly or expectedly.

34

Page 35: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalImplicit Type Conversion : When there are constants and variables of different types in an expression, C automatically converts any intermediate values to the proper type. This conversion assures that the expressions can be evaluated without losing any digits inside. This automatically convert typed is known as implicit type conversion.During evaluation if operands are of different types, the lower type is automatically converted into the higher type before the operation proceeds. The conversion takes place according to rule called the conversion hierarchy. The final result of an expression is converted to the type of variable on the left of the assignment signs before assignment the value to it. However the following changes are introduced before the final assignment.Float to int causes truncation of the fractional partDouble to float causes rounded of digitsLong int to int causes dropping of the excess higher order bits.Explicit Type ConversionInstance where the type can be converted forcefully by the user himself is called explicit type conversion or casting value. The general rule to cast is (type name) expression.

N1=(int)9.50 9.50 is converted to integer by truncationN2=(int)16.9/(int)6.5 Evaluation is done 16/6, resulting 2N3=(double)sum/n Sum is calculate to double and division is done in floating modeN4= (int) (a+b) The results is converted then assignN3=sin((double)x) X is converted to double and the sin value is calculated and assign

WAP to demonstrate implicit and explicit data type conversion#include<stdio.h>#include<conio.h>void main(){int male,female; float ratio1,ratio2;printf("Enter male numbers");/*45scanf("%d",&male);printf("Enter female number");/*7scanf("%d",&female);ratio1=male/female;/6 ratio2=(float)male/female;/6.425871printf("By using implicit:\t%f",ratio1);printf("\nBy using explicit:\t%f",ratio2);getch();}OutputEnter male numbers 45Enter female number 7By using implicit: 6.00000By using explicit: 6.425871

Case 1: If we supply the integer values of both male and female but their output may be in fractional precisions (45 and 7) this gives 6.00000 which is incorrect for the calculation however we designed floating values to be hold by our variable ratio1.Case 2: If we supply the same value but explicitly cast this calculation into float this produce another results 6.425871 this is accurate one.Input and Output Operations/Management of Formatting scanf() and printf() functionsA program without any input or output has not meaning; generally a program reads input data form keyboard or other files. The program then processes input data and result is displayed on the screen or monitor. Let’s consider program to create mark sheet of student then program must take marks of five subjects then after getting some information the percentage and division will be calculated. Finally the required results is shown in the screenC has number of input and output functions, when a program needs data. We take the data through input functions and results to output devices through output functions. As keyboard is standard input devices, the input functions used to read data form keyboard are called standard input function. The standard input functions which are scanf(), getchar (), getche (), getch(), gets(). Similarly output functions are printf(),

35

Page 36: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalputchar(), putch(), puts (). The standard library <stdio.h>provides functions for input and output. The instruction include<stdio.h> tells the compiler to search <stdio.h>from the standard i/o directory and place its contents in the program. The content of header files become part of source code. The input and output factions are two types Formatted functions andUnformatted functionsFormatted Function: Formatted functions allow to give input/ read form the keyboard and output displayed on screen to can be formatted according to user requirements. The input function scanf() and printf() are fall under this category. While displaying certain data on screen we can specify the number of digits after point, number of spaces before the data, and position where output is to be displayed are handled through there functions. Formatted Input/Scanf(): Formatted input refers to an input data that has been arranged in a particular format for example 50,30.4, puja. This line contains three types of data and must be read according to its format. The first part should move into variable int, the second must be variable in float and the third into char. This is possible in C by using scanf() function.The built in function scanf() can be used to enter input data to the computer form the standard input devices. The functions can be used to enter any conditional or numerical values, single characters or string. In other word, it is used for runtime assignments of variables.Syntax: scanf(“control string”,args,arg2,args); The address of location where the data is stored signifies in control string. It represents pointer that indicates the address of data items within computer memory (&). The control string consists of individual groups of data format with one group for each input data items. Each data format must begin with a percentage sign (%). Syntax: scanf(“[whitespace character][ordinary character]%[field width][conversion character]”);Whitespace Characters [Optional]: In function scanf() encounters a white space characters in control string, it reads but does not store the whitespace characters till the next non white space character in the input.Example of White Space

#include<stdio.h>#include<conio.h>void main(){ int n1; char ch; clrscr();printf("Enter a number:"); scanf("%d",&n1);printf("Enter character");scanf(" %c”,&ch);/*scanf(“%c",&ch);*/printf("\n number is%d \t the character is %c",n1,ch);getch();}Output:Enter a number: 4Enter character a

Then the compiler abnormally terminate because after supplying numbers in first input the compiler again behaves int as the second character inputAfter entering the data of integer values the second line does not print because integer values does not terminate after value supplied by users there for white space characters are used to skip certain input. This will be not the case if we take character at first then integer at second will not produce the same information. Ordinary Characters [Optional]: The ordinary characters are those characters that are not white space characters. They may be included in scanf function to take in a certain pattern. The user should input data as stated by the ordinary characters; however they are not stored in input string.WAP to take data of date DD-MM-YY format

#include<stdio.h>#include<conio.h>void main(){int day, month,year; clrscr();printf("Enter day, months and years in DD-MM-YY");scanf("%d-%d-%d",&day,&month,&year);/*(“%d%d%d”, &dat,&month,&year)*/printf("\n Day:%d\t Month:%d\year:%d",day,month,year);getch(); }OUTPUT

36

Page 37: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalEnter day, months and years in DD-MM-YY 12 3 2011Day: 12 month: 3 Year: 2011The sigh – dash restrict the pattern to input data.If we supply the data 12 3 2011 then the output display the garbage values will be assign

to variables months and year.Field Width [Optional]: The field width limits the number of input characters. It sets the maximum numbers of characters to be read. It is placed in between % and the conversion character. It will accept the fewer character then prescribed but it cannot exceed the specified width. Any characters that extend beyond the specified field width will be skipped.

WAP to take specified digits form the users#include<stdio.h>#include<conio.h>void main(){ int num; clrscr();printf("Enter 5 digits number"); scanf("%5d",&num);printf("\nNumber is%d",num);getch();}OutputEnter 5 digits numbers 12345Number is 12345Enter 5 digits numbers 123Numbers is 123Enter 5 digits numbers 12345678Number is 12345 only

Conversion Character: The conversion character tells the compiler what data type the variables needs to store. This should match exactly toits width and type of variable as declared. The commonly used conversion characters are %c,%d,%e,%f,%f,%g,%i,%o.WAP to display your first name

#include<stdio.h>#include<conio.h>void main(){ char string[30]; clrscr();printf("Enter your name");scanf("%s",&string);/*scanf(“%s”,string);*/printf("Your name is%s",string);getch(); }OutputEnter your name Yagya RimalYour name is Yagya

Some version of scanf() function supports the following conversion specifications for strings%[characters]: Is only the character specified within brackets are allowed.%[^characters]:The character specified after ^ caret are not allowed in the string and reading will terminated.WAP to take specific user defined string on capital letter

#include<stdio.h>#include<conio.h>void main(){char string[30]; clrscr();printf("Enter our name"); scanf("%[A-Z]",string);printf("Your name is%s",string);getch();}OutputEnter your name Yagya RimalYour name is Y

WAP to take whole line in a string#include<stdio.h>#include<conio.h>

37

Page 38: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalvoid main(){ char string[30]; clrscr();printf("Enter your name"); scanf("%[^\n]",string);printf("Your name is%s",string);getch();}OutputEnter your name Yagya RimalYour name is Yagya Rimal

Formatted Output: The formatted output refers to the output of data that has been arranged in particular format. The printf() is a built in function which is used to output data from the computer output devices on screen. The printf statements can be used to control the alignment and spacing. Syntax: printf (“control string”, args,args,args);The control string consists of four type items

Characters that will be printed on the screen Format specification that define output format for display of each items Escape sequences that define output format for display Any combination of characters, format specification and escape sequences

The control string has as form: printf (“ %[flag][field][.precision] conversion character”);Flags [Optional]: The flag affects the appearance of the output. They must be placed just after percentage sign. -+,0, o, x or blank space are symbol . – indicates the left justified. + indicates +ve or –ve numbers. A blank space will precede each positive signed numerical data. o it refers octal similarly x refers hexadecimal numbers.Output of Integer Numbers: %wd is used to display in a desired width of integer values. Where w is the minimum field width for the output and d specifies that the value printed is an integer.Output of Single Character: A single character can be designed in a desired position using format %wc.Precision [Optional]: The operation of precision field depends on data type of conversion. It must start with period (.).Output of Real Numbers: The precision can further be extended using field width of form w.pf where w is field width and p is precision. The conversion character is %f.Output String: The format specifies for output string is form of %w. p s where w is width for display and p instruct that only the first p character of string are displayed, it count white space too.WAP to demonstrate output function

#include<stdio.h>#include<conio.h>void main(){ int n1=1234; char p='A'; float q=12.3456;char string[10]="My Nepal";printf("%d\t",n1);printf("\n%2d\t",n1);printf("\n%-6d\t",n1);printf("\n%6d\t",n1);printf("\n%06d\t",n1);printf("\n%o\t",12);printf("\n%.4o",12);printf("\n%x\t",556);printf("\n%c",p);printf("\n%2c",p);printf("\n%6c",p);printf("\n%.4d\t",12);printf("\n%c",p);printf("\n%.2f",q);printf("\n%7.4f\t",q);printf("\n%7.2f",q);printf("\n%6.4f",q);printf("\n%6f",q);printf("\n%s\t",string);

38

Page 39: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n%10s",string);printf("\n%10.6s",string);printf("\n%-10.6s",string);getch(); }

Unformatted Functions: Unformatted function do not allow user to read or display data in desired format. These library functions are available in the header files they are: getchar (), putchar (),gets(), puts(), getche(), getch() are unformatted functions.getchar() and putchar(): The getchar function reads character form standard input devices. It takes the following format char p=getchar ();. Similarly putchar () function display a character to standard out devices. It takes flowing format putchar (character variable);WAP to demonstrate getchar and putchar function.

#include<stdio.h>#include<conio.h>void main(){ char gender; clrscr();printf("Enter gender M: F"); gender=getchar();printf("Your gender is:"); putchar(gender);getch(); }OutputEnter gender M: F fYour gender is: f

getch(), getche() and putch(): The function getche() and getch() reads single character of instant of time, it is type without waiting for enter key to be hit. The difference between them is that getch () reads the character typed without echoing it on the screen, while getche () reads the character and echoes display it onto the screen. getch () format is char variable=getch(); the function putch() prints a character onto the screen. It has the form putch (char variable name);WAP to demonstrate getch() putch() function

#include<stdio.h>#include<conio.h>void main(){ char ch1,ch2; clrscr();printf("Enter 1 char"); ch1=getch();printf("Enter 2 char"); ch2=getche();printf("\n1st character is:"); putch(ch1);printf("\n2st character is:"); putch(ch2);getch(); }outputEnter 1 charEnter 2 char b1st character is: a2 st characters is: b

Since the first input takes input and put char1 in character type when the entered character is not echo. However using getche() function we can see in second case displayed on screen.gets() and puts(): The gets () function is used to read a string of text, containing whitespace, until a newline character is encountered. It offers an alternative function of scanf() function for reading strings. Unlike scanf() function it does not skip white spaces.gets(string variable name); It takes string form user and store in string variable. Puts() function is used to display string onto terminal. It has the form puts (string name).WAP to take your name

#include<stdio.h>#include<conio.h>void main(){ char name[30]; clrscr();printf("Enter your name"); gets(name);printf("Your name is"); puts(name);getch(); }Output

39

Page 40: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Statement1

Statement2

Statement3

Statement 1Statement 2…………..…………..Statement 3Statement n…………….Fig: Pseudocode

FT

BE Computer Programming in C Yagya RimalEnter your name Bishal AdhikariYour name is Bishal Adhikari

Control StatementsThe statements which alter flow of execution of the program are known as control statements. In the absence of control statements, instructions are executed in same order in the program. Such instructions are called sequential statements. In sometime we have to perform certain task depending on outcome of logical test. Similarly sometimes it is necessary to perform repeated action or skip some statements. For these cases we need control statements. They control flow of program. So that it is not necessary to execute statements in the same order in which they appear in program.Any program logic, no matter how complex, could be expressed by using only the following three simple control structures:

a. Sequence Logicb. Selection Logic andc. Iteration (or Looping) Logic

Sequence Logic: Sequence logic is used to perform instruction to be followed after another in sequential order. The logic of flow the instruction from top to bottom. In this type of instruction the instruction starts top most instruction execute first then sequentceial statements will execute in top down hierarchy.

Selection Logic/Decision Making StatementsSelection is a special kind of branching, in which one group of statements is selected from several alternatives groups, i.e., it allows alternative actions to be taken according to conditions that exist at particular stage in program execution. The conditions are normally in the form of expressions that are evaluated test results (true or false). Selection logic are following types.

a. if … b. if … … elsec. nested ifd. switch statemente. goto

Since decision making statements control the flow of execution, they also fall under the category of control statements.If …statement: The if statement is a powerful decision making statement is used to control flow of execution of the program. It is basically a two way decision statements and it is within expression. The if evaluates the expression first then if the value of expression is true, it executes the statements within its block. Otherwise it skips statements within its block and continues form first statement outside the if block.if (test expression){statement block; }statement x;The statement block can be a single statement or group of statements. If the test expression is true the statements block within if is executed; otherwise the statement block will be skipped. The execution will jump

40

Fig: Séquentiel State ment

Page 41: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Start

READ NUM

IsNUM<0

Negative

END

Y

IF (CONDITION)Statement1ELSEStatement2Statement2

Read Num

Start

Display Even

Remainder =0

Display Odd

Calculate remainder

End

BE Computer Programming in C Yagya Rimalto the statement x are executed in sequence order. The brace {} can be omitted if there is only one statement following the true condition of if statement.

WAP to ask a number form user and test whether the number is positive or negativeAlgorithm:1: Start2: Read number3: If the read in step 2 is less than zero, display message the number is –ve4: Stop

#include<stdio.h>#include<conio.h>void main(){int num;clrscr();printf("Enter number to be tested");scanf("%d",&num);if(num<0)printf("%dthe number is negative",num);getch();}

if .. else StatementThe if.. else statement is an extension of simple if statement. It is used when there are two possible actions are to be evaluated. When a condition is true it executes statements inside if condition. Else the statement inside else is executed.The general form of if else is:

If the test condition is true, then true block statement, immediately following if statements are executed, otherwise, false block statement are executed. In either case true or false block will be executed, not both at the same time. This is best suit in only two choices or alternative.Write a program to ask a number form user and find whether the number is even or odd

#include<stdio.h>#include<conio.h>void main(){int num, remainder;clrscr();printf("Enter number to be tested");scanf("%d",&num);remainder=num%2;if(remainder==0){printf("%d is even number",num); }else {printf("%d is odd number",num); }

41

Statement1

FT

IF condition

Page 42: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

IF (CONDITION) Statement 1ELSE IF (CONDITION)Statement 2Else If (condition)Statement3ELSEStatement 4

No

No

Yes

Yes

IFCondition1 Statement 1

IF Condition2 Statement 2

IFCondition n Statement n

Yes

Condition1

Condition 2

Condition 3

Condition n

Default Statement

Statement n

Statement 3

Statement2

Statement1

Statement X

F

F

F

F

T

T

T

BE Computer Programming in C Yagya Rimalgetch(); }

else..if StatementThe else.. if statement is used when there are more than two possible actions depending upon outcome of test condition. When specific action is satisfied the specific action only is executed, no other action will be executed. In such situation if.. elseif.. elseif. else structure is used. If the elseif statement is satisfied then else if condition is executed else last else statement is executed.

The condition is evaluated from top to button. As soon as true condition is found, the statements associated within it are executed and the control is transferred to statement X, at last the others are skipping the structure. When all conditions become false then final else containing default statement will be executed. The elseif structure is like this.

WAP that reads the marks of a student in seven subjects. Then calculate the percentage and determine the division. Use these conditions%>= 80 distinction%>60<79 first

42

Page 43: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Is per>=80&& <100

per>=60&&<80

per>=40 & per<60

perc>=32 && per<40

F

F

F

F

T

T

T

per=Total/7

Read 7 subjects

Start

T

Distinction

First

Second

ThirdFail

END

BE Computer Programming in C Yagya Rimal%>45<59 second%>32<44 passElse failAlgorithmStep 1: StartStep2: Read marks in seven subjectsStep 3: Add all the marks to calculate the total marks by dividing total marks by subjects 7.Step 4: If percentage is greater than or equal to 80 display message to DistinctionStep 5: If percentage is between 60 and 79, display message to FirstStep 6: If percentage is between 45 and 59, display message to SecondStep 7: If percentage is between 32 and 44, display message to ThirdStep 8: If percentage is less than or equal to 31, display message failStep 9 : Stop

#include<stdio.h>#include<conio.h>void main(){float nep,eng,math,phy,bio,comp,che,percent;printf("Enter seven subjects marks");scanf("%f%f%f%f%f%f%f",&nep,&eng,&math,&phy,&bio,&comp,&che);percent=(nep+eng+math+phy+bio+comp+che)/7;if(percent>=80)printf("You score%f in distinction",percent); else if(percent>=60) printf("You score%f in first division”, percent); else if(percent>=50) printf("You score%f in second division”, percent); else if(percent>=40) printf("You score%f in passed”, percent); else if(percent>=32 &&percent<40) else printf("You score%f in failed”, percent); getch();}

Nested if .. else StatementIf an entire if..else construct is written under either the body of an if statement and the body of an else statement, then such type of construction is called nested if…. else statement. In other words nested if else is

43

Page 44: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Read Num A,B,C

Start

Ais Largest

End

Is A>B

B is Largest

A>C B>C

C is Largest

T TF

F

BE Computer Programming in C Yagya Rimalsuch type of construction in which there is an if..else statement within another if.. else statement. One if..else is nested into another if.. else statement in nested form. In nested form the condition of inner statement is evaluated only if the condition of outer if is satisfied. Otherwise it is skipped and the else part of outer if is evaluated. The syntax is

Write an algorithm and draw a flowchart to find the largest numbers among three numbersAlgorithm

Step 1: StartStep 2: Display “Enter Three Numbers”Step 3: Read Num A, B, CStep 4: If A is greater than b then test if A>CStep 5: If A is greater than C then display A is largest

If A is not greater than C is largestStep 6: If A is not greatest than test if B is > CStep 7: If B is greatest than C then display B is largest

If B is not grater then C then display C is largestStep 8: Stop

#include<stdio.h>#include<conio.h>void main(){int n1,n2,n3;scanf("%d%d%d",&n1,&n2,&n3);if(n1>n2){ if(n1>n3) printf("Largest=%d",n1);else printf("largest=%d",n3); }else{ if(n2>n3) printf("Largest=%d",n2);

else printf("Largest=%d",n3); }getch(); }

Similarly this problem also solved without nested elseif#include<stdio.h>#include<conio.h>void main(){ int a,b,c;printf("Enter Three numbers do you want to test");scanf("%d%d%d",&a,&b,&c); if(a>b&&a>c) printf("a is largest and value of a is:%d",a);else if(c>b&&c>a) printf("C is largest%d",c);else printf("b is largest:%d",b);getch(); }

Dangling else Problem: One of the most common problem of nested if.. else statement is dangling else. This occurs when a matching else is not available of an if statement. The solution to this is to always match an else to the most recent unmatched if in the current block.WAP to ask the user for three numbers then determine the largest number among them using nested if else structure.

#include<stdio.h>#include<conio.h>void main(){ int n1,n2,n3;printf("Enter 3 numbers");scanf("%d%d%d",&n1,&n2,&n3);if(n1>n2){

44

if(CONDITION1) Statement 1

if (CONDITION2)Statement 1

elseStatement2

elseStatement 3

Page 45: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

1 2 4

3

for( counter initialization; test condition; increment/decrement)

{}

False

TRUE

Counter Initialization

Test ExpressionExit

Body of Loop

Update Expression

BE Computer Programming in C Yagya Rimalif(n1>n3)printf("Largest is%d",n1);else printf("largest=%d",n3); }

else {if(n2>n3) printf("Largest=%d",n2);else printf("Largest is%d",n3); }

getch();}Loop Operation: Loop may be defined as block of statements which are repeatedly executed for a certain number of times or until a particular condition is satisfied. When an identical task is to be performed for a numbers of times, then loop is used. The loop is executed repeatedly until an expression is true. When expression become false, the loop terminates and then control is passes to the another statements followed by the loop. A loop consists of two segments, one is known as the control statement and other is body of loop. The control statement in loop decides whether the body is to be executed or not.Types of loopsFor LoopWhile loopDo. While loopfor Loop: The for loop is useful to execute a statement for a number of times. When number of repetition action is required we use for loop is more efficient and reliable. Thus, this loop is also known as a determinant of definite data.syntax: for (counter initialization, test condition; increment or decrement){statements; or body of loop;}Counter Initialization: The counter variable is initialized using assignment statements such as i=0,i=10 and count=0. Here the variable i, j, count are known as counter control variable whose value controls the loop execution. This expression or statement is executed only once prior to the statements within the for loop.Test condition: The value of counter variable is tested using test condition. If the condition is true, the body of the loop is executed, otherwise the loop is terminated and execution continues with the statements that immediately follows the loop structure.Update Expression/ Increment or Decrement: When body of loop is executed, the control is transferred back to statement after evaluating last statement in the body of loop. The counter variable is updated either increment or decrement and then only it is to be tested with that conditions and the same process is repeated until the condition become false.Working Rules

The different components in for loop are executed in direction sequence as above.At first the counter is initialized to some value. Then counter variable is tested with test condition. If test is true, body of loop is executed. After finishing body, the counter variable is incremented or decremented and then again update counter variable is tested with the condition. The same process repeated as long as the condition is true. If the result with test condition becomes false the control passes outside the loop.

45

Page 46: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

While Expression

Body of Loop

Exit

Start

Next_time=y

Is next_time=y

Read A and B

sum=A+B

Display sum

Stop

BE Computer Programming in C Yagya Rimal

WAP to calculate factorial of a number #include<stdio.h> #include<conio.h>void main(){int num,i; long fact=1; clrscr();printf(" Enter number whose factorial is to be calculate"); scanf("%d",&num);for(i=1;i<=num;i++)fact=fact*i;printf("\n the factorial is:%d",fact);getch(); }

WAP to that ask an integer number n and calculate sum of all natural numbers from 1 to n.#include<stdio.h>#include<conio.h>void main(){ int num,i,sum=0; clrscr();printf("Enter number \t "); scanf("%d",&num);for(i=1;i<=num;i++) sum+=i;printf("\n the sum is:%d",sum);getch();}

while LoopThe syntax iswhile(test condition){body of loop ;}

The test condition is evaluated and if the condition is true then body of the loop is executed. After execution of data once, test condition is again evaluated and if it is true, the body is executed one again. This process of repeated execution of body continues until test condition finally becomes false and control is transferred out of loop. On exit, the program continues with the statement immediately after the body of loop.Flow chart

WAP to add two numbers and display their sum. The program must ask next two numbers and add till user wants.Algorithm

1. Start2. Initialize a character variable next time to y3. Compare the value next time is equal to y4. If the value of variable next time is equal to y read two numbers a and b otherwise go to step 95. Calculate sum and sum=a+b6. Display sum7. Read user’s choice for next time or not read y for yes and other for no8. Repeat step 3 to 7 until next time is equal to y9. Stop

#include<stdio.h>#include<conio.h>void main(){int a,b,sum;char nexttime;clrscr();

46

Page 47: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Body of Loop

Test condition

Exit

False

TRUE

Start

Sum=0 and count=0

Read NUM

Sum=sum+num andCount=count+1

Is Num>0

Sum=sum+numAverage=sum/(count-1)

BE Computer Programming in C Yagya Rimalnexttime='y';while(nexttime=='y') {printf("\n enter two numbers to be added\t");scanf("%d%d",&a,&b);sum=a+b;printf("\n the sum is \t%d", sum);printf("\n Do you want to do more");printf("\n Then press y for another try and other character for exit\t");scanf(" %c",&nexttime); }getch(); }

do while LoopSyntax:

do{ statement or body of loop }while (condition);

In do while loop body of loop is executed first without testing condition. At the end of loop, test condition in the while statement is evaluated. If condition is true, program continues to evaluate the body of t he loop once again. This process continues as long as condition is true. When condition becomes false, the loop is terminated and then control goes to the statements that appears immediately after the while statement. Since the test condition is evaluated at bottom of the loop do while loop construct provides an exit controlled, or bottom of the loop and therefore body of loop is always executed at least once.Flow chart

WAP to read numbers form keyboard until zero or negative number is keyed, finally calculate the sum and average numbers.AlgorithmStep 1: StartStep 2: Initialize two variables count sum then sum=0 and count =0Step 3: Read NumStep 4: Add enter number to previous sum and increase count variable by oneStep 5: If the entered number is greater than zero repeat step 3 to step 5 other wise step 6Step 6: Calculate average of the numbered entered, here the last enter number is only for termination hence it is exclude form the average.Sum=sum-NumAverage = sum(count-1)Step 7: display average and sumStep 8: stop

#include<stdio.h>#include<conio.h>void main(){int num,count=0;float sum=0.0,avg;clrscr();do{printf("\nEnter numbers:\t");scanf("%d",&num);sum=sum+num;count++;}while(num>0);

47

Page 48: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

InitializationWHILE (Condition)Statement1.Increment Or DecrementENDWHILE

Do{Statement 1Statement 2…………………………}while(condition);

Initialization

Statements

LogicalExpression

T

F

Increment/Decrement

Statement 1

Statement n

Condition?

START

I=5

BE Computer Programming in C Yagya Rimalsum=sum-num;avg=(sum)/(count-1);printf("\t the sum is:\t%f",sum);printf("\t the average is: %f",avg);getch();}

Fig: Flowchart and Pseudocode for WHILE and DO WHILE selection structureWhile Do whileWhile loop is entry control loop ie test condition is evaluated first and body of loop is executed only if test is true

Do while loop is exit control loop ie the body of the loop is executed first without checking condition and at the end of body of loop, the condition is evaluated.

The body of the loop may not be executed at all if the condition is not satisfied at the very first attempt.

The body of loop is always executed at least once

Syntax: while(text condition){Body of loop }

Syntax is Do{ Body of loop }while(text condition);

Show flowchart of while loop Show flowchart of do loopNested Loop: When the body part of the loop contains another loop then the inner loop is said to be nested within the outer loop. Since a loop may contain other loops within its body, there is no limit of the number of loops that can be nested. In the case of nested loop, for each value of outer loop, inner loop is completely executed. Thus inner lop operates fast and outer loop operate slowly.WAP to display multiplication table of 5 to 10

#include<stdio.h>#include<conio.h>void main(){int i,j;clrscr();for( i=5;i<=10;i++){for(j=1;j<=10;j++) {printf("%d*%d=%d\t",i,j,i*j);}printf("\n"); }getch();}

48

Page 49: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Initialization

Test Condition

Body of Loop

Condition for break

Update Expression

Break

ExitF

T

T

F

Start

I=2

is I<NUM

Read NUM

is Remainder==0

Display not prime

Is I==NUM

Display PRIME

F

FT

Remainder=num%I

F

BE Computer Programming in C Yagya Rimal

Break and continue Statementbreak StatementThe brake statement terminates the execution of loop and controls are transferred to the statement immediately following the loop. Generally the loop is terminated when its test condition becomes false. But if we have to terminate the loop instantly without testing loop termination condition, the statement is useful. The syntax: break;Break statement is also used in switch statement which causes a transfer of control out of the entire switch statement. To the first statement following the switch statement to the first following the stitch statement. The switch statement will be discussed later.

What is the output of the following program?#include<stdio.h>#include<conio.h>void main(){int a;clrscr();for(a=1;a<10;a++){printf("\t%d",a);if(a==5) break;}getch();}

WAP, algorithm and Flowchart to determine whether the number is prime or not

Algorithm Step 1: Start Step2: Initialize a variable I to 2 Step 3: Read a number which is to be checkedStep 4: Compare I with NUM

A) If I is less than NUM calculate REMAINDER dividing the number NUM by I. If Remainder is equal to zero, display the number as not prime and it is not necessary t divide the number by further of value of I and hence go to step 5 if remainder is not zero, Increase 1 by one and repeat step 4

B) If I is not less than NUM then check whether I is equal to NUM or not. If they are equal , display the number is as prime

Step 5: Stop

#include<stdio.h>#include<conio.h>void main(){int i,num;clrscr();printf("Enter number");scanf("%d",&num);for(i=2;i<num;i++){if(num%i==0){printf("Not a prime");break;}}if(i==num){printf("\n Prime number"); }getch(); }

49

Page 50: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

F

Statement of body

Initialization expression

test expression

Body of statement

Condition for continue

Update

Continue

T

T T

F

Stop

I=1

is I<=N

Calculate Remainder

is remainder==0

I=I+1

T

T T

F

Read N

Start

Stop

Display I

BE Computer Programming in C Yagya Rimal

continue StatementThe continue statement is used to bypass expression of current process through a loop. The loop does not terminate when a continue statement is encountered. Instead of termination, it skipped some portion some part of program and the computation proceeds directly to the next stage through the loop. syntax is: continue;

WAP that ask a number n form user and then display only even numbers from 2 to n use continue statement.

#include<stdio.h>#include<conio.h>void main(){int i,num;clrscr();printf("Enter number");scanf("%d",&num);

printf("The even form 2 to %d are\n",num);for(i=2;i<num;i++){if(i%2!=0)continue;printf("\t%d",i);}getch();}

goto StatementThe go to statement is used to alter normal sequence of program execution by unconditionally transferring control to some other part of program. The go to statement transfer control to the labeled statement somewhere in current function. The go to statement has the following syntax : goto label; Here label is an identifier used

50

Page 51: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Is Switch variable equal 1st constant?

Is switch variable equal to 2 nd constantstant

Body of DEFAULT

Body of 2nd Case

Body of 1 st case

EXIT

T

TF

F

BE Computer Programming in C Yagya Rimalto the target statement to which control would be transferred. The target statement must be labeled using syntax: label statements:Generally use of go to statement is avoided as it makes program illegiable. This statement is used in unique statements like.

Branching around statements or groups of statements under certain condition. Jumping to end of a loop under certain condition, thus passing remainder of loop during current pass. Jumping completely out of loop under certain conditions, Termination executions of a loop.

WAP to ask two numbers to display message “Enter number is negative” if either number is negative; otherwise display message “Both numbers are positive or negative”.

#include<stdio.h> #include<conio.h>void main(){int i,num,num1;clrscr();printf("Enter first number");scanf("%d",&num);if(num<0) goto negative;printf("Enter second Number");scanf("%d",&num1);if(num1<0)goto negative;printf("THe both are positive");getch(); return;negative:printf("Either number is negative");getch();}

switch StatementWhen there are number cases to be handled, switch statement is another way of representing this multi way selection. A switch statement allows user to choose a statement among several alternatives. The switch statement is useful when a variable is to be compared with different constants and in case it is equal to a constant a set of statements are to be executed. The constants in case statement may be either char or int type only. syntax:

switch (variable name) {case statements; break;case statements; break;default statements; }

WAP a program to make Menu

1 File2 Edit3 Save

#include<stdio.h> #include<conio.h>void main(){int choice;clrscr();printf("Select 1 for File/t Select 2 for Edit/t Select 3 for Save");printf("1===>File\n2===> Edit\n3===> Save\n");scanf("%d",&choice);switch(choice){case 1:printf("\nYou have choosen File"); break;case 2:

51

Page 52: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Start

Read two operands OP1 and OP2

is OPR ==+

Is OPR==-

is OPR==*

is OPR==/

Default

Result=OP1+OP2

Result=OP1-OP2

Result=OP1*OP2

Result=OP1/OP2

STOP

BE Computer Programming in C Yagya Rimalprintf("\nYou have choosen Edit");break;case 3:printf("\nYou have choosen Save");break;default:printf("\n Invalid input");}getch(); }

WAP that asks operands and operator among +-* and / Depending upon the entered operator two operas ands and display the result and also draw flowchart use switch statement

#include<stdio.h>#include<conio.h>void main(){float op1,op2,result;char oprator;clrscr();printf("Enter two Operands");scanf("%f%f",&op1,&op2);printf("Enter the operator do you want to calculate");scanf(" %c",&oprator);switch(oprator){case '+':result=op1+op2;printf("\nthe sum is %f",result);break;case '-':result=op1-op2;printf("\nthe sum is%f",result);break;case '*':result=op1*op2;printf("\nthe sum is%f",result);break;case '/':result=op1/op2;printf("\nthe sum is%f",result);break;default:printf("Invalid input operator");}getch(); }

WAP to that ask a number form keyboard and tests whether it is multiple of 5 or not#include<stdio.h>#include<conio.h>int main(){int num,rem; clrscr();printf("Enter numbers");scanf("%d",&num);rem=num%5;if(rem==0) printf("\n is multiple of 5");else printf("\n is not multiple of 5");getch(); return 0;}

WAP to red form keyboard and test whether the number is exactly divisible by 5 but not by 11#include<stdio.h>#include<conio.h>int main(){int num,rem5,rem11; clrscr();printf("Enter numbers"); scanf("%d",&num);rem5=num%5;rem11=num%11;if(rem5==0&&rem11!=0)

52

Page 53: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n number is \divisible by 5 but not by 11");else printf("\n the number is not \"dividable by 5 but not by 11"");getch(); return 0;}

WAP to read a character form keyboard and convert it into uppercases if it is lowercase and vice versa#include<stdio.h>#include<conio.h>int main(){ char c; clrscr();printf("Enter character"); scanf(" %c",&c);if(c>=65&&c<90){printf("\nThe character is upper case");c=c+32;printf("\nThe equivalent lowercase is%c",c); }else if( c>97&&c<122){printf("\nThe character is lowercase ");c=c-32;printf("\n The equvalent uppercase is %c",c); }else printf("Invalid character");getch(); return 0;}

Write a program to examine the value of char type and print one of the following messages depending upon the variable (RED if either r or R assigned to the variableGreen if either g or G assigned to the variableBlue if either b or B assigned to the variableWhite if either w or W assigned to the variable)

#include<stdio.h>#include<conio.h>void main(){ char c; clrscr();printf("Enter a character(r/R for red,b/B or Blue,g.G Green,w/W for White)");scanf("%c",&c);switch(c){case 'r':case 'R': printf("RED");break;case 'b':case 'B': printf("BLUE");break;case 'g':case 'G': printf("GREEN");break;case 'w':case 'W': printf("White");break;default: printf("not valid character"); }getch();}

WAP to read the values of coefficient a, b, c of a quadratic equations ax2+bx+c=0 and find roots of equations (real or imaginary, complex whether they may be supply by user)

#include<stdio.h>#include<conio.h>#include<math.h>void main(){ float a,b,c,x1,x2,d,real,img; clrscr(); printf("Enter the value of a,b,c in ax^2+bx+c\t"); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<0){ printf("Roots are imaginary"); d=sqrt(fabs(d));//calculate absolute value real=-b/(2*a); img=d/(2*a); printf("x1=%.2f+i%.2f",real,img); printf("x2=%.2f+i%.2f",real,-img); } else { printf("The roots are"); d=sqrt(d); x1=(-b+d/(2*a)); x2=(-b-d)/(2*a); printf("x1=%.2f\tx2=%.2f",x1,x2);}

53

Page 54: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal getch();}

A bank has decided to provide interest rate in fixed deposit account as: 5% for less than or equal to 2 yrs 6% for greater than 2 yrs and less than equal to 5yrs and 7% for more than 5 yrs . Write a program to read principle, time period form keyboard and calculate that will be after specified period according to policy.

#include<stdio.h>#include<conio.h>void main(){ float p,t,r,i,amount; clrscr(); printf("Enter the value of Principal time period in yrs\t"); scanf("%f%f",&p,&t); if(t<2) r=5; else if(t>2&&t<=5) r=6; else if(t>5) r=7; else r=0; i=(p*t*r)/100; amount=p+i; printf("The amount will be \t%f",amount); getch(); }

A bank has introduced in incentive polity. A bonus of 2% of the balance is given to everyone, irrespective of their balances and 5% is given to female account holder if their balance is more than rs 5000. Write a program to represent this polity and calculate balance after bonus.

#include<stdio.h>#include<conio.h>void main(){ float balance; char sex; clrscr(); printf(" Old balance:\t"); scanf("%f",&balance); printf("Ehter gender M:?F"); scanf(" %c",&sex); if(sex=='f'){ if(balance>5000) balance=balance+0.05*balance; else balance=balance+0.02*balance;} else balance=balance+0.02*balance; printf("The balance is%f",balance); getch(); }

WAP to read n and calculate sum of the series (1+2+3+4..n)#include<stdio.h>#include<conio.h>void main(){ int n,sum=0,i; clrscr(); printf("\n Enter n: "); scanf("%d",&n); for(i=1;i<=n;i++){ sum+=i;} printf("The sum is:%d",sum); getch(); }

WAP program to calculate ( 2+4+6+8----n)#include<stdio.h>#include<conio.h>void main(){ int n,sum=0,i,term; clrscr();printf("\n Enter n: "); scanf("%d",&n);for(i=1,term=2;i<=n;i++,term+=2){sum+=term;}printf("The sum is:%d",sum);getch(); }

WAP to calculate 12+22+32+42+52--- +n2

#include<stdio.h>#include<conio.h>void main(){ int n,sum=0,i; clrscr();printf("\n Enter n: "); scanf("%d",&n);for(i=1;i<=n;i++){ sum+=i*i;}printf("The sum is:%d",sum);getch();}

54

Page 55: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalWAP to calculate 23+43+63+83---+n3

#include<stdio.h>#include<conio.h>void main(){ int n,sum=0,i,term; clrscr();printf("\n Enter n: "); scanf("%d",&n);for(i=1,term=2;i<=n;i++,term+=2){sum+=term*term*term;}printf("The sum is:%d",sum);getch();}

WAP to calculate 1+1/x +1/x2+1/x3………1/xn

#include<stdio.h>#include<conio.h>void main(){ int n,i; float sum=1,term=1,x; clrscr();printf("\n Enter n: and x"); scanf("%d%f",&n,&x);for(i=1;i<=n;i++){ term*=1/x;sum+=term;}printf("The sum is:%f",sum);getch();}

WAP program to read two integer n1 and n2 whether n1<n2. Display all even numbers between these two numbers. Also count the frequency of these even numbers.

#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){ int n1,n2,count=0, i; clrscr();printf("\n Enter n1: and n2"); scanf("%d%d",&n1,&n2);if(n1>n2){printf("enter number n1<n2");exit(1);}if(n1%2==0) i=n1;else i=n1+1;printf("Even numbers are");for(;i<=n2;i+=2){count++;printf("the number of even between %d and%d is :%d",n1,n2,count);}getch();}

WAP to find the numbers and sum of all integers greater than n1 and less than n2 and divisible by 7 where n1<n2 and n1 and n2 are given form user.

#include<stdio.h>#include<conio.h>void main(){ int n1,n2,count=0,i,sum=0; clrscr();printf("\n Enter n1: and n2"); scanf("%d%d",&n1,&n2);if(n1>n2){ printf("Enter number n1<n2\t");}else{for(i=n1+1;i<n2;i++){if(i%7==0){ count++; sum+=i; }}printf("the sum is%d",sum);printf("the number of int grater then %d, Less than %d and divisible by 7 is%d",n1,n2,count);}getch();}

WAP to find cubes and square of first 10 natural numbers#include<stdio.h>#include<conio.h>void main(){ int i;printf("\n The square and cubes ");for(i=1;i<=10;i++){printf("\n%d\t%d\t%d",i,(i*i),(i*i*i));}getch(); }

WAP to display prime numbers from n1 to n2 where n1<n2 and n1 and n2 are read form keyboard#include<stdio.h>#include<conio.h>void main(){ int i,num,n1,n2; clrscr();

55

Page 56: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\nEnter n1 and n2 whwew n1<n2");scanf("%d%d",&n1,&n2);printf("\n prime numbers are");for(num=n1;num<=n2;num++){for(i=2;i<num;i++){ if(num%i==0)break;}if(i==num) { printf("\t%d",num); }}getch();}

Wap to use goto statements to act as loop#include<stdio.h>#include<conio.h>void main(){ int i=0,num; clrscr();printf("Enter number"); scanf("%d",&num);check: if(i>=num)goto stop;else{ i++;printf("\n%d",i);goto check;}stop:printf("\n this is end");getch();}

WAP to read m an n from user them calculate (m power n) without library built in functions#include<stdio.h>#include<conio.h>void main(){ int i,m,n,result=1; clrscr();printf("\n Enter base m and power n"); scanf("%d%d",&m,&n);for(i=1;i<=n;i++){result=result*m;}printf("\n the result is%d",result);getch();}

WAP program to read a numbers form keyboard and checked palindrome #include<stdio.h>#include<conio.h>void main(){ long n,num,rev=0; int digit; clrscr();printf("\n Enter to be checked"); scanf("%d",&num);n=num;do {digit=num%10; rev=rev*10+digit; num/=10;}while(num!=0);if(n==rev) printf("\n is palindrome");else printf("Not palindrome");getch();}

WAP to convert decimal number to binary numbers#include<stdio.h>#include<conio.h>void main(){int decinum,sum=0,q,r,i=1; clrscr();printf("\n Enter to be checked");scanf("%d",&decinum);do { q=decinum/2;r=decinum%2; decinum=q;sum+=r*i; //to reorder the binary bitsi*=10;}while(q!=0);printf("\n correspond\t%d",sum);getch();}

WAP to print in reverse digits from user (1234 to 4321)

56

Page 57: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<stdio.h>#include<conio.h>void main(){ long num,rev=0; int digit; clrscr();printf("\n Enter to be checked"); scanf("%ld",&num);do {digit=num%10; rev=rev*10+digit; num/=10;}while(num!=0);printf("\n revrsed\t%ld",rev);getch();}

WAP to calculate sum of digits of given integer#include<stdio.h>#include<conio.h>void main(){ int num,r,q,sum=0; clrscr();printf("\n Enter to be checked"); scanf("%d",&num);do { q=num/10; r=num%10; num=q; sum+=r;}while(q!=0);printf("\n sum of digits\t%d",sum);getch();}

WAP to calculate HCF ot two numbers#include<stdio.h>#include<conio.h>void main(){ int m,n,rem,temp,hcf; clrscr();printf("\n Enter two number"); scanf("%d%d",&m,&n);if(m<n){ temp=m; m=n; n=temp;}do{rem=m%n; m=n; hcf=n; n=rem;}while(rem!=0);printf("The HCF%d",hcf);getch();}

WAP program to display Pyramid of numbers#include<stdio.h>#include<conio.h>void main(){ int i,j,n=5; clrscr();for(i=1;i<=n;i++){ for(j=1;j<=n-i;j++)printf("\t"); //to print spacefor(j=i;j<=2*i-1;j++) printf("\t%d",j);for(j=2*i-2;j>=i;j--) printf("\t%d",j);printf("\n");}//to change linegetch();}

Reverse pyramid of numbers#include<stdio.h>#include<conio.h>void main(){ int i,j,n=5; clrscr();for(i=0;i<n;i++){ for(j=n-i;j<=2*n-2*i-1;j++) printf("\t%d",j);for(j=2*n-2*i-2;j>=n-i;j--) printf("\t%d",j); printf("\n");for(j=0;j<=i;j++) printf("\t");}getch();}

Floyd’s Triangle#include<stdio.h>#include<conio.h>void main(){ int i,j=1,k,n=5; clrscr();for(i=1;i<=n;i++){ for(k=1;k<=i;j++,k++)printf("\t%d",j); printf("\n");}getch();}

Display following outputs#include<stdio.h>#include<conio.h>void main(){ int i,j,n=6; clrscr();

57

WAP to checked Armstrong number#include<stdio.h>#include<conio.h>void main() {int num,sum=0,r,a;

printf("Enter a number");scanf("%d",&num);a=num;while (num!=0){r=num%10;sum=sum+r*r*r;num=num/10; }if(sum==a)printf("armstrong");else

Page 58: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfor(i=1;i<=n;i++){ for(j=1;j<=i;j++){printf("\t*",j); } printf("\n");}getch();}#include<stdio.h>#include<conio.h>void main(){ int i,j,n=7; clrscr();for(i=1;i<=n;i++){ for(j=1;j<=(n+1-i);j++){printf("\t*"); } printf("\n");}getch();}

#include<stdio.h>#include<conio.h>void main(){ int i,j,n=4; clrscr();for(i=1;i<=n;i++){ for(j=1;j<=i;j++)printf("\t*"); printf("\n"); }for(i=1;i<=n-1;i++){ for(j=1;j<=n-1;j++)printf("\t*"); printf("\n");}getch(); } #include<stdio.h>#include<conio.h>void main(){ int i,j,n=4; clrscr();for(i=1;i<=n;i++){ for(j=1;j<=i;j++)printf("\t%d",i); printf("\n"); }getch(); }#include<stdio.h>#include<conio.h>void main(){ int i,j,n=4; clrscr();for(i=1;i<=n;i++){ for(j=1;j<=i;j++)printf("\t1"); printf("\n"); }getch(); }

What is output of this program#include<stdio.h>#include<conio.h>void main(){ int a=10,b; clrscr();for(b=1;b<=10;b++){ a++;}printf("\na=%d\tb=%d",a,b);getch();}#include<stdio.h>#include<conio.h>void main(){ int i,x=0; clrscr();for(i=1;i<10;i*=2){ ++x;printf("\tx=%d",x++);} printf("\n\ti=%d",i);getch();}#include<stdio.h>#include<conio.h>void main(){ int i,x=0; clrscr();for(i=1;i<10;i++){ if(i%2==0) continue;++x;printf("\tx=%d",x++);} printf("\ni=%d",i);getch();}#include<stdio.h>#include<conio.h>void main(){ int x=10; clrscr();while(1){printf("\nx=%d",x++);}getch();}#include<stdio.h>#include<conio.h>

58

#include<stdio.h>#include<conio.h>void main(){int i,j;clrscr();for(i=1;i<=5;i++){for(j=1;j<i;j++)printf("%d\t",i*j);printf("\n");}getch();}

WAP to checked Armstrong number#include<stdio.h>#include<conio.h>void main() {int num,sum=0,r,a;

printf("Enter a number");scanf("%d",&num);a=num;while (num!=0){r=num%10;sum=sum+r*r*r;num=num/10; }if(sum==a)printf("armstrong");else

Page 59: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalvoid main(){ int i,j; clrscr();for(i=0,j=10;i<10;i++,j--){printf("i=%d\tj=%d\n",i,j);}getch();}

ARRAYS and STRINGSAn array is a group of related data items that share common name. In other word an array is a data structure that store number of data items as a single entity (Object). The individual data items are called elements and all of them must have same data type. Array is used when multiple data items that have common type and format. Therefore an array is a collection of individual data elements that is ordered (0, 1, 2, 3….), fixed size of homogenous elements. Suppose we have to require 10 numbers of integer type and we have to sort ascending. If we have no array we must have declared 10 integer of elements like int a1, b1, c1, c2, c3 up to 10 times of int type to store these data .When defining different variables to be stored for different numbers of times are very tedious jobs. In such case, we use array to store multiple numbers of same type to be stored at single time. The individual elements are seperated by array name followed one or more subscript or index enclosed in square bracket. The individual data item can be character, integer, floating numbers. However they must be the same type and same storage class. We may used auto, register, static keyword just before deceleration variable of array type.One Dimensional Array: There are several forms of an array in C, they are one dimensional and multi dimensional array. In one dimensional array, there is a single subscript or index whose value refers to individual array element which ranges from 0 to (n-1) where n is size of array e.g. int A [5] is a declaration of one dimensional array of int type. Its elements can be illustrated as:

1st element 2nd element 3rd element 4 the element 5th elementA[0] A[1] A[2] A[3] A[4]2001 2002 2003 2004 2005

The elements of an integer array A [5] are stored in continuous memory locations. It is assured that the starting memory location may be 2001. As each integer element requires 2 bytes, subsequent elements appears after gap of 2 locations. (Here int A[5] occupy 10 bytes memory area).Declaration of 1 D Array: Syntax: storage class data type array name [size];

1. Storage class refers to the storage class of array. It may be auto, static and register. It is optional.2. Data type declares of array variable hold. It may be int, float, and char. The array elements are all

values of same data type. If int is used, this means that array store all data items of integer types.3. Array name is name of array. It is user defined name for array. The name of array may be any name

valid for name of variable deceleration.4. Size of the array is the number of elements in the array. The size is mentioned within [] bracket. The size

must be in int, constant like 10, 5. Or constant expression likes symbolic constant SIZE. #define SIZE 20, the array can be defined as int a [SIZE]. The size of an array must be specified (i.e. should not be blank) except in array initialization. Example: int num [5]; This statement tells to the compiler that num is an array of int type; num can store five integers’ values. The compiler reserves 2 bytes of memory of each integer array element. Thus total memory size allocated by an integer is 10 bytes. It is individual elements are recognized by num [0], num [1], num [2], num [3], num [4]. The integer value within square bracket [] is called index of array. Index of an array always starts form 0 to size of array minus one. Similarly, char name [10]; Here name is a character variable of size 10, it can store 10 characters.float salary [20]; here salary is variable name having float data type array of size is 20. It can store 20 factorial values.Initialization of 1 D array: If array elements are not given any specific values, they are supposed to contain garbage values. The values can be assigned to element at time of array declaration, which is called array initialization. Since an array his multiple elements, braces are used to denote the entire array and commas are used separate the individual values assigned to the elements in the array initialization statements. The syntax: storage class data types array name [size] = {value1, value2, value3};Where value1 is first elements value 2 is second element and value3 is last element. This array size is 2.

59

Page 60: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThe Array Initialization May be Three Types:int a [5] = {1, 2, 3, 4, 5}; Here “a” is integer type array which holds 5 elements. Their values are assigned as 1,2,3,4,5(a[0]=1,a[1]=2,, a[2]=3,a[3]=4 ,a[4]=5).The array elements are stored sequentially in memory location. int b [] = {1, 2, 3};Here size of array is not given; the compiler automatically sets its size accordingly to number of values present in braces. The size of array is 2 in this array initialization as three values 1,2,3 are assigned at time of initialization (a[0]=1,a[1]=2,a[2]=3). In this way, int a [10] = {1, 2, 3, 4, 5};In this example the size of array has set 10 but only five elements are assigned at the time of initialization. In this situation all individual elements that are not assigned explicitly contains 0 as initialization values, as a[0]=1,a[1]=2,a[2]=3,a[3]=4,a[4]=5,a[5]=0,a[6]=0,a[7]=0,a[8]=0,a[9]=0.Accessing Array Element: The single operation that could not include entire array is not permitted in C. Thus if num and list are two similar array (data type and dimension), assignment and comparison operation of those two arrays must be carried out on the basic of element by element operation. All elements of an array can neither be set at once or one array is assigned to another.int a [5], b [5]; then a=0; b=a; wrong if (a<b) {…}/wrongThe particular array elements in an array are accessed by specifying the name of array, followed by sequence bracket enclosing an integer, which is called array index. The array index indicates particular elements of array which we want to access. The number of index starts form zero and ends to number one less than the size of array. For example float marks [5]; Then array elements are mark [0] marks [1], mark [2], mark [3], mark [4]. We can assigned float value to these individual elements directly or a loop can be used to input and output from the elements of array location.WAP that reads 10 integers from keyboard and display entered numbers in the screen.

#include<stdio.h>#include<conio.h>void main(){int a[10],i;clrscr();printf("Enter 10 numbers");for (i=0;i<10;i++) scanf("%d",&a[i]);printf("Printing these");for(i=0;i<10;i++)printf("\ta[%d]=%d",i,a[i]);getch();}

WAP to illustrate the memory location by each array elements#include<stdio.h>#include<conio.h>void main(){float a[]={10.7,20.5,30.6,40.4,60.3};int i; clrscr();printf("memory location");for(i=0;i<5;i++)printf("\t%d",&a[i]);getch();}

WAP that reads marks percentage in an examination of 5 students calculate and display average percentage and deviation percentage from average of each student

#include<stdio.h>#include<conio.h>void main(){float marks[5], avg,dev,sum=0; int i; clrscr();printf("\nEnter percentage of 5 subjects\n");for(i=0;i<5;i++) {printf("\t marks[%d]=",i);scanf("%f",&marks[i]);sum=sum+marks[i];}avg=sum/5;printf("\nThe average is%f",avg);printf("the deviation of marks are\n");

60

Page 61: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfor(i=0;i<5;i++){ dev=marks[i]-avg;printf("\nthe marks[%d]=%.2f\t devition of marks%f",i,marks[i],dev); }getch();}

WAP to sort n numbers in ascending order#include<stdio.h>#include<conio.h>void main(){int num[40],i,j,n,temp;clrscr();printf("\n How many");scanf("%d",&n);printf("\n Enter number%d number",n);for(i=0;i<n;i++){scanf("%d",&num[i]); }for(i=0;i<n-1;i++){for(j=i+1;j<n;j++){if(num[i]>num[j]){temp=num[i]; num[i]=num[j]; num[j]=temp;}} }printf("the number in ascending order\n");for(i=0;i<n;i++){printf("\t%d",num[i]); }getch();}

Characteristics of Array: The deceleration int a[5] is nothing but creation of 5 variables of integer type in memory . Instead of declaring five variables for five values, the programmer can define them in array of any order..

All elements of an array share same name and they are distinguished form one another with the help of array index.

The element number or array index in the array plays an important role for calling each element. Any particular element of an array can be modified separately without disturbing other elements. The single operations, which involve entire array, are not permitted in C. Thus if num and list are

two similar array(same data type dimensions and size), then assignment operations comparison operators etc, involving these tow arrays must be carried out on comparison through element by element basic.

Any element of an array can be assigned to another ordinary variable or array variable. int b, a[10], c=9; then b=a[2];a[5]=a[3];a[6]=c; are valid conditions.Multidimensional Arrays: Multidimensional array are those which have more than one dimension. Multidimensional arrays are defined as same manner as one dimensional array, except that a separate pair of square brackets is required for each subscript or dimensional or index. Thus two dimensional array will require two pairs of square brackets, similarly, the three dimensional arrays will require three pairs of square brackets and so on. The two dimensional array is also called matrix. Multidimensional array can be defined as. storage class data type array name [dim1] [dim2];Here dim1 and dim2 are positive value integer expression that indices the numbers of array elements associated with each sub-script. An m*n two dimensional array can be tabular form of value having m rows and columns. For int p [3][3] ;

col1 col2 col3row1 p[0]

[0]p[0][1]

p[0][2]

ow2 p[1][0]

p[1][1]

p[1][2]

row3 p[2][0]

p[2][1]

p[2][2]

61

Page 62: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalDeclaration of Two Dimensional Arrays : Like one dimensional array two dimensional arrays must also be declared before using it. The syntax for declaration is: storage class data type array name [row size][column size](/f}sf}For int matrix [2][3]; It contains 2 rows and 3 columns it contains 6 elementsInitialization of 2 D Array: Like one dimensional array multidimensional array can be initialized at the time of array defend or declaration. A few example of 2-d array initializations are:int marks[2][3]={2,4,6},{8,10,12}; Is equivalent to mark[0][0]=2; marks[0][1]= 4 , mark[0][2]=6; marks[1][0]= 8, mark[1][1]=10; marks[1][2]= 12int marks[2][3]={2,4,6,8,10,12}; is equal to above.The first dimension may be empty like this.int mark3[][3]= {2,4,6,8,10,12}; int p[][3]={2,4,6,8,10}; p[0][0]=2,p[0][1]=4,p[0][2]=6, p[1][0]=8,p[1][1]=10,p[1][2]=0Note: if value provided while initializing are less than an array, zero is assigned to remaining elements.All above example are valid while initializing array, it is necessary to mention second dimensional column where as first dimension row is optional. This following are invalid initializationsint marks[3][]={2,4,6,10,12};//wrong int marks3[][]={2,4,6,8,10};//errorAccessing 2d Array Elements: In 2d array first dimension specifics number of rows and second specifies columns. Each row contains elements of many columns. Thus 2d array contains multiple rows. Thus 2 d array is an array of 1 d array. As each size row will contain elements of many columns, the columns index ranges from 0 to size-1 inside every row in one dimensional representation. So columns index changes faster than row index as one dimensional representation of array inside computer is traversed. 2 d array is traversed row by row (every columns elements in first row are traversed first and then columns elements of second row are traversed and so on. The nested loop is used to traverse the 2 d array. Let's consider following 2 d array marks, size of 4*3 matrix having 4 row and 3 columns35 10 11 34 90 7613 8 5 76 4 135 10 11 34 90 76 13 8 5 76 4 1To access a particular elements of 2 d array we have to specify array name followed by two square brackets with row and columns number inside it for example marks[0][0] represent 35,marks[0][1]=10

WAP to read a matrix if size if 2*3 finally display it screen#include<stdio.h>#include<conio.h>void main(){int matrix[2][3],i,j; clrscr();for(i=0;i<2;i++) for(j=0;j<3;j++){printf("\t Enter matrix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]); }printf("The entered matrix:\n");for(i=0;i<2;i++) for(j=0;j<3;j++){printf("%d\t", matrix[i][j]);printf("\n");}getch();}

WAP to read two m*n matrix and displays their sum#include<stdio.h>#include<conio.h>#define m 3#define n 3void main(){int a[m][n],b[m][n],i,j,sum[m][n]; clrscr();printf("Enter first martix %d and %d",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",&a[i][j]);

62

Page 63: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("Enter secod of martix %d and %d",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",&b[i][j]);for(i=0;i<m;i++) for(j=0;j<n;j++)sum[i][j]=a[i][j]+b[i][j];printf("\the sum matix is:\n");for(i=0;i<m;i++) { for(j=0;j<n;j++){printf("\t%d",sum[i][j]); }printf("\n") ; }getch();}

Arrays and Strings: Strings are array of characters they are arranged one after another in memory. Thus character array is also known as string. Each character within string will be stored within each element of the array. Strings are used by %c to manipulate text such as word and sentences. A string is always terminated by a null character (\0). The terminating null character is important because it is only way string handling functions can known where string ends. Normally each character is stored in one byte, and successive characters of the string are stored in successive bytes.Initialization Strings: char name[]={‘R’,’A’,’M’};Then string name is initialized to “RAM”. This technique is also valid but offers special way to initialize the sting as char name[]={“RAM”};The characters of string are enclosed within the double quotes.

WAP to illustrate string initializing#include<stdio.h>#include<conio.h>void main(){char name[]="Shyam Bhadur Sharma";int i=0;printf("\nthe name of\n");while(name[i]!='\0'){printf("\t%c",name[i]);i++;}getch();}

Arrays of Strings: String is array of characters. Thus an array of string is 2D array of characters. This is explained with the help of following example.WAP to read name of 5 different person using array of strings and display them.

#include<stdio.h>#include<conio.h>void main(){char name[5][10]; int i;printf("enter name of 5 students");for(i=0;i<5;i++) scanf("%s",name[i]);printf("The enter name are");for(i=0;i<5;i++)printf("\nThe%d name is%s",i,name[i] );getch();}

String Handling Functions: The library built in functions strlen (), strcpy (), strcat (), strcmp () strrev () etc are used for string manipulation in C. These functions are defined in header file string.h they are described as bellow.strlen ()The strlen () function returns integer which denotes length of string passed. The length of string is number of characters presented in it, excluding terminating null character. Its syntax is: integer variable=strlen (string);WAP to find the length of Input from user using function.

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char name[10]; int len;clrscr();printf("\n Enter our Name");gets(name);len=strlen(name);

63

Page 64: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n the number of character in our name is%d",len);getch();}

strcpy(): The strcpy () function couies one string to another. The function accepts two strings as parameters.The first string copies the string of second string character by character into first one up to and including the null character of second string. Syntax: strcpy (destination string, sources string);WAP to copy one string to another

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char name[]="Rimal sir"; char s[25]; clrscr();strcpy(s,name) ;printf("\n the Value s=%s\t name =%s",s,name); getch();}

stcat (): This function concatenates two string i.e it appends one string at the end of another. This function accepts two strings as parameter and stores the contents of the second string at end of the first string.as strcat (string1, string2);WAP to concatenate two strings

#include<stdio.h>#include<conio.h>#include<string.h>void main(){char fname[20]="Yagya",lname[14]="Rimal";clrscr();strcat(fname,lname) ;printf("\n full name is%s",fname);getch();}

strcmp(): This function compares two strings to find out whether they are same or different. This function is useful for searching string as arranged in a dictionary order. This function accepts two strings as parameters and returns an integer whose value is ,Less than 0 if first string is less than second stringEqual to 0 if both are sameGreater than 0 if the first string is greater than secondTwo strings are compared character by character until there is a mismatch or end of strings. When two characters in two strings differ, the string which has the character with a higher ASCII values is displayed. WAP to illustrate to use of strcmp () function

#include<stdio.h>#include<conio.h>#include<string.h>void main(){char fname[20],lname[14];int diff;printf("enter first name"); gets(fname);printf("Enter second naame"); gets(lname);diff=strcmp(fname,lname);if(diff<0)printf("%s is greater than %s by value of %d",fname,lname,diff);else if(diff<0)printf("%s is less than %s by value of %d",lname,fname,diff); else printf("%s is sammmmelength %s ",fname,lname);getch();}

strrev(): This function is used to reverse all characters in string except null character at the end of string. The reverse of string “abc” is “cba” its WAP to illustrate strrev function

#include<stdio.h>#include<conio.h>#include<string.h>void main(){char name1[15]="Shyam Sharma", name2[15];

64

Page 65: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalstrcpy(name2,name1);strrev(name1);printf("The reversed string of original string %s is%s",name2,name1);getch();}

Some ExamplesWAP to read n numbers from keyboard and find average

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ float nums[50],sum=0,avg; int i=0,n; clrscr();printf("Enter (c<50)");scanf("%d",&n);printf("\n%dRead numbers",i+1);for(i=0;i<n;i++){ scanf("%f",&nums[i]); }for(i=0;i<n;i++) sum=sum+nums[i]; avg=sum/n;printf("\n the average is%f",avg);getch();}

WAP to that ask for n numbers for user and find maximum and minimum of them#include<stdio.h>#include<conio.h>void main(){int nums[50],max,min,i,n; clrscr();printf("How many");scanf("%d",&n);printf("Enter numbers"); for(i=0;i<n;i++) scanf("%d",&nums[i]);max=nums[0];min=nums[0];for(i=0;i<n;i++){ if(max<nums[i]) max=nums[i];if(min>nums[i]) min=nums[i];}printf("\n the max number is%d",max);printf("\n the minimum is%d",min);getch();}

WAP program to read marks of n students and print out the top five #include<stdio.h>#include<conio.h>void main(){int nums[50],i,j,n,temp;clrscr();printf("How many Students");scanf("%d",&n);printf("Enter Marks%d",n);for(i=0;i<n;i++)scanf("%d",&nums[i]);for(i=0;i<n-1;i++){for(j=i+1;j<n;j++){ if(nums[i]<nums[j]){temp=nums[i]; nums[i]=nums[j]; nums[j]=temp;}}} printf("\n top 5 are"); for(i=0;i<5;i++) printf("\t%d",nums[i]);getch();}

WAP to read n numbers form keyboard and find third highest and second lowest numbers

#include<stdio.h>#include<conio.h>void main(){

65

Page 66: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalint nums[50],i,j,n,temp;clrscr();printf("How many Students");scanf("%d",&n);printf("Enter Marks%d",n);for(i=0;i<n;i++)scanf("%d",&nums[i]);for(i=0;i<n-1;i++){for(j=i+1;j<n;j++){ if(nums[i]<nums[j]){temp=nums[i]; nums[i]=nums[j]; nums[j]=temp;}}} printf("\n third highest is%d",nums[2]); printf("\n second highest is%d",nums[2-1]); getch();}

WAP to read an array of length n display total count for positive numbers, negative numbers and zero separately

#include<stdio.h>#include<conio.h>void main(){int nums[50],i,n,pos=0,neg=0,zero=0;clrscr();printf("How many numbers");scanf("%d",&n);printf("Enter Marks%d",n);for(i=0;i<n;i++)scanf("%d",&nums[i]);for(i=0;i<n;i++){ if(nums[i]>0) pos++; else if(nums[i]<0) neg++; else zero++;} printf("\nthe numbers positive is%d",pos); printf("\nthe numbers -ve is%d",neg); printf("\nthe numbers 0 is%d",zero); getch();}

WAP program to read n numbers form keyboard and all even sum numbers and all odd sum separately and display results.

#include<stdio.h>#include<conio.h>void main(){int nums[50],i,n,evensum=0,oddsum=0;scanf("%d",&n);printf("Enter Marks%d",n);for(i=0;i<n;i++)scanf("%d",&nums[i]);for(i=0;i<n;i++){if(nums[i]%2==0)evensum=evensum+nums[i];elseoddsum=oddsum+nums[i];}printf("\nthe evensum is%d",evensum);printf("\nthe odd sum is%d",oddsum);getch();}

WAP to calculate mean variances and standard deviation for n numbers#include<stdio.h>

66

Page 67: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<conio.h>#include<math.h>void main(){float nums[50],avg,sum=0,variance,sd,sumofsquare=0; int i,n;printf("How manu numbers"); scanf("%d",&n);printf("Enter numbers%d",n);for(i=0;i<n;i++) {scanf("%f",&nums[i]);sum=sum+nums[i]; }avg=sum/n;for(i=0;i<n;i++)sumofsquare=sumofsquare+(avg-nums[i])*(avg-nums[i]);variance=sumofsquare/n; sd=sqrt(variance);printf("\nthe variance is%f",variance);printf("\n average isis%f",avg);printf("\n the sd is%f",sd);getch(); }

WAP which ask for order of two matrixes and read two matrixes as given order. Subtract second matrix form first and display the resultant matrix.

#include<stdio.h>#include<conio.h>void main(){int a[10][10],b[10][10],result[10][10],i,j,m,n;printf("\nEnter size of matrix\t"); scanf("%d%d",&m,&n);printf("\nEnter first matix%d*%d\n",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",&a[i][j]);printf("Enter sedxond matrix%d*%d\n",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&b[i][j]);for(i=0;i<m;i++) for(j=0;j<n;j++)result[i][j]=a[i][j]+b[i][j];printf("\nThe resultant\n");for(i=0;i<m;i++){ for(j=0;j<n;j++){printf("\t%d",result[i][j]); }printf("\n");}getch();}

WAP which multiplies each element of matrix of order m*n by 3#include<stdio.h>#include<conio.h>#define m 2#define n 3void main(){int matrix[m][n],i,j; clrscr();printf("\norder of %d*%d\n",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++) {printf("\n matrix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]);}for(i=0;i<m;i++) for(j=0;j<n;j++)matrix[i][j]=3*matrix[i][j];printf("\nThe resultant matrix is\n");for(i=0;i<m;i++){ for(j=0;j<n;j++)printf("%d\t",matrix[i][j]);printf("\n");}getch(); }

WAP find the row sum and column sum of matrix#include<stdio.h>#include<conio.h>void main(){

67

Page 68: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalint matrix[10][10],p,q,sum=0,i,j; clrscr();printf("\nEneter order of less than 10*10\n");scanf("%d%d",&p,&q) ;if(p>9||q>9) { printf("\n the order is out of range"); getch(); exit();}printf("Entre matix order%d*%d",p,q);for(i=0;i<p;i++) for(j=0;j<q;j++) { scanf("%d",&matrix[i][j]);}printf("\orer input of matixis:\n"); for(i=0;i<p;i++){ for(j=0;j<q;j++) printf("%d\t",matrix[i][j]); printf("\n");} for(i=0;i<p;i++){ for(j=0;j<q;j++) { sum+=matrix[i][j]; }matrix[i][j]=sum; sum=0;}for(j=0;j<q;j++){ for(i=0;i<q;i++) { sum+=matrix[i][j]; } matrix[i][j]=sum;sum=0;}printf("the matrix with row and column\n");for(i=0;i<p;i++){ for(j=0;j<q;j++){printf("%d\t",matrix[i][j]);}printf("|");printf("%d",matrix[i][j]);printf("\n"); }printf("--------------\n");for(j=0;j<q;j++)printf("%d\t",matrix[i][j]); getch(); }

WAP to read square matrix form keyboard and find the sum of diagonal elements #include<stdio.h>#include<conio.h>void main(){int matrix[10][10],i,j,p,q,sum=0; clrscr();printf("\nEneter order of less than 10*10\n");scanf("%d%d",&p,&q) ;if(p>10||q>10) { printf("\n the order is out of range");getch(); exit();}if(p!=q){printf("the order is not of square");printf("system going to exit");getch(); exit();}printf("Entre matix order%d*%d\n",p,q);for(i=0;i<p;i++) for(j=0;j<q;j++) {printf("\nmatrix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]);if(i==j)sum=sum+matrix[i][j]; }printf("ypour matrix is:\n");for(i=0;i<p;i++){ for(j=0;j<q;j++)printf("%d\t",matrix[i][j]);printf("\n"); }printf("the trace of matrix is\t%d",sum);getch(); }

WAP to read a string and check for palindrome#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char c[40]; int len,i,pal=1; clrscr();printf("Enter string of your choice");gets(c);len=strlen(c);for(i=0;i<(len/2);i++){if(c[i]!=c[len-i-1]) pal=0;}if(pal!=0) printf("\n is palindrome");else printf("not palindrome");

68

Page 69: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalgetch();}

WAP to that reads a string form keyboard until enter key and count the vowels, constants semi constant, and commas separately

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char input[200]; int len,i=0,vowel=0,cons=0,comma=0,semi=0; clrscr();printf("Enter some texts"); gets(input);len=strlen(input);for(i=0;i<len;i++){if(input[i]=='a'||input[i]=='e'||input[i]=='i'||input[i]=='o'||input[i]=='u')vowel++ ;else if(input[i]==',')semi++;else if(input[i]==';')comma++;else cons++;}printf("\nthe numbers of vowel\t%d",vowel);printf("\nthe numbers of constant\t%d",cons);printf("\nthe numbers of comma\t%d",comma);printf("\nthe numbers of semivowel\t%d",semi);getch();}

WAP to read name of five persons and sort them to display in ascending order#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char name[5][10]; int i,j; char temp[11]; clrscr();printf("Enter 5 names\n");for(i=0;i<5;i++) gets(name[i]);for(i=0;i<5;i++){ for(j=i+1;j<5;j++){if(strcmp(name[i],name[j])>0){strcpy(temp,name[j]);strcpy(name[j],name[i]);strcpy(name[i],temp);}}}printf("\n the name in assending orde3ri are:");for(i=0;i<5;i++){ printf("\n%s",name[i]); }getch();}

WAP to read string form user and reverse it without using string related library functions

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char input[40],rev[40]; int length=0,i,j; clrscr();printf("Enter string of your choice\t"); gets(input);i=0;while(input[i]!='\0'){length++; i++;}i=length-1;for(j=0;j<length;j++,i--){ rev[j]=input[i];}rev[j]='\0';printf("the rev string is:%s", rev);getch();}

WAP program to concatenate two strings. Don’t used library files#include<stdio.h>#include<conio.h>#include<string.h>void main(){char st1[20],st2[20],con[40]; int lenst1=0,lenst2=0,i,j; clrscr();printf("Enter first string"); gets(st1);

69

Page 70: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("Enter second string"); gets(st2); i=0;while(st1[i]!='\0'){lenst1++; i++;} i=0;while(st2[i]!='\0'){lenst2++; i++;}for(i=0;i<lenst1;i++)con[i]=st1[i]; j=0;for(i=lenst1;i<(lenst1+lenst2);i++,j++)con[i]=st2[j]; con[i]='\0';printf("\n the concanate string %s and %s is %s",st1,st2,con);getch();}

WAP to red form keyboard and output a list of ASCII code which represent your name#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char name[40]; int len,i; clrscr();printf("Enter our name\t"); gets(name);len=strlen(name);printf("\n the ascii value use in %s\n",name);for(i=0;i<len;i++) printf("\t%d",name[i]);getch();}

WAP to read string and search specific word in given string.#include<stdio.h>#include<conio.h>#include<string.h>#define size 50void main(){ char input[size]="", search[size]="";char temp[size]="", isfound='N';int i,i1,i2,j,k; clrscr();printf("Enter string\t"); gets(input);printf("Enter choice to be searched");gets(search);i1=strlen(input);i2=strlen(search);for(i=0;i<=(i1-i2);i++){ for(j=i,k=0;j<(i2+i);j++) {temp[k]=input[j]; k++; }if(strcmp(temp,search)==0){ isfound='Y';break; } }if (isfound=='Y')printf("\nstring is found");else printf("\n not found"); getch(); }

WAP that takes string form the user and convert the all the character to upper case if they are in lowercase and vice versa

#include<stdio.h>#include<conio.h>#include<string.h>#define size 50void main(){ char input[size]; int i,nn; clrscr();printf("Enter character"); gets(input);nn=strlen(input);for(i=0;i<nn;i++){ if(input[i]>=65&&input[i]<=90)input[i]=(input[i]+32);else if(input[i]>=97&&input[i]<=122)input[i]=(input[i]-32);}printf("The string after changing case is\t%s",input);getch(); }

70

Page 71: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalFUNCTIONWhat is Function: A function is defined as a self contained block of statements that performs particular task/jobs. This is a logical unit composed of a number of statements grouped into a single unit. It is defined as a section of a program performing a specific task. The function main is always present in each program which is executed first and other function are optional.The separate program segment is called functional that is called main program when ever required. For example to calculate prime numbers we should have to calculate each number generated form loop should have to test to be prime or not, in such case we have to repeat same logic of finding prime numbers up to defined times. Instead of such case we have to make general function which calculates factorial of a given number and this function is called function which calculates prime of a given numbers by passing them to the function to be tested. Therefore function is a special code block that has some functionality . it is called inside main methods when it required.Advantage of Functions: Manageability: Using function for specific job, it is easier to write programs and keep track of what they are doing. It makes programs significantly easier to understand and maintain by breaking them into easily manageable subunits. The code for each job or activity is placed in individual functions such that testing and debugging because easy and efficient. Thus use of functions in a program helps to manage the code.Code Reusability: A single function can be used multiple times by a single program form different places or different programs. It avoid re writing same code again that recuce large efforts and reuse code of computer designer. Thus it helps to reuse code once written and tested. The C standard library is an example of functions being reused.Avoid Redundant: While using function same function is called whenever needed inside main program. Thus particular job or activity is to be accessed repeatedly form several different place within or outside the program. The repeated activity can be placed within a single function, which can then be accessed whenever it is needed. If the function is not used in such situation the code must have to redesign for same activity is to be rewritten the same instruction again and again.Logical Clarity: When single program is decomposed into various well-defined functions, the main program consists of a series of function calls rather than rewrite lines of code so that size of main program seems smallre and becomes logical clarity understandable. Easy to Divide the Work Among Different Programmers: Different programmers working at large project can divide the working by writing different functions easily.WAP to calculate factorial difference of user supply numbers

#include<stdio.h>#include<conio.h>void main(){ int f=1,f2=1,n,n2,i; clrscr();printf("\n Enter two numbers to calculate difference in factorial"); scanf("%d%d",&n,&n2);for(i=1;i<=n;i++){ f=f*i;}for(i=1;i<=n2;i++){ f2=f2*i; }printf("he factorial difference is%d",f2-f);getch();}

Here to compute combination we have to calculate factorial of n1 and n2 are calculated logical code are similar to each case. This is not good idea to write same code in more time for same action therefore function is best idea to calculate as bellow.

#include<stdio.h>#include<conio.h>float factorial(int n){ float fact=1; int i;for(i=1;i<=n;i++) fact=fact*i;return fact;}void main(){ float f1,f2,d; int n,m; clrscr();printf("\n Enter two numbers to calculate difference in factorial");scanf("%d%d",&n,&m);f1=factorial(n);f2=factorial(m);d=f2-f1;

71

Page 72: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("the difference is%f",d); getch();}

In this example a function called factorial () is defined once and it is called three times to calculate the factorial of n1 and n2. The detail of defining function will called when ever the value of function is changed and all the calculation are done inside function.User Defined Function and Library FunctionsLibrary Functions (Built in Functions): There are some functions which are already written compiled and placed in C library. They are not required to be re-written by a developer. The function name its return type and their arguments number and types have been already defined. We can use these functions whenever we are required them. For example printf (), scanf (), sqrt(), getch() are library functions generally used.User Defined Function: These are functions which are defined by user at time of writing a program. The user has choice to choose its name, return type, arguments and their types. In case of above example the function factorial () is user defined function. The job of each user-defined function is as defined by user. A complex program can be divided into a number of user defined functions.About main () Function: The function main is a user defined function except that name of function is defined or fixed by the language. The return type arguments and body of function are defined by programmer as required. This function is executed first, when the program starts execution.Function Definition: The collection of program statement that describes specific task to be done by function is called a function definition. It consists of function header which defines functions name its return type and arguments list and body of function which are the block of code enclosed in parenthesis.Syntax: return type function name ( data type variable name, data type variable name){….; .; }The first line of function definition is known as function declaration or header. This is followed by function which is composed of statement that makes up function, delimited by braces.float areaof circle(float radius){ return(3.14*radius*radius);}void display(int a){ printf(“%d”,a);}The return type is optional the default is int type. The arguments variable 1, variable 2, variable 3 presents in function definition are called arguments or parameters because they represent name of data items that are transferred into function from calling function/program. There are local variable for function.Function Declaration/Prototype: The function declaration or prototype is model or blueprint of function. If function are used before they are defined, then function declaration or prototype necessary which provides following information to computer.Name of function type of value returned by functionThe number and type of argumentsWhen a user defined function is defined before used there The syntax return type function name (arguments, arguments);Here return type specifies data types of value returned by function. A function can return value of any data type. If there is not return value, the keyword void is used. The function deceleration and in header function must use the same function name, numbers of arguments and its type and returned types.int add (int a, int b), here int add (int, int) is the function having return type int fname add are two paramenters.void display (int a) here void type function display having int type parameters.Note: It is important to note that the function prototype has semicolon at the end and to specify the same name of formal arguments is not mandatory but type is mandatory.Return Statement : It is statement that is executive just before function completes its job and control is transferred back to the calling function. The job of return statement is to hand over some value given form where the call was called. The return statement serves mainly two purposes. They are:

It immediately transfers control back to the calling program after executed after the return statement i.e. no statement within function body is executed after return statement.

It returns the value to calling function. return (expression); When expression must evaluated to value of type specified in function header from the return value.

The expression can be any desired expression as long as it ends up with value of required type. The value of expression is returned is omitted, return statement simply cause control to revert back to

72

Page 73: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalcalling portion of return statement each containing a different expression, but a function can return only one value to calling portion of the program via return statement.

Function may or may not return any value. If a function doesn’t return a value type in the function definition and deceleration is specified as void. Otherwise return type is specified as a valid data type. A return statement at end is optional for function without return value.Accessing Function: A function can be called or accessed by specifying its name, followed by a list of arguments enclosed in parentheses must separate by comma. For example, function add () with two arguments is called by add (int a, int b) to add two numbers. If function call does not required any argument it has empty pair of parenthesis must followed the name of function. The arguments appearing in function call are referred as actual argument. In function call there will be one argument for each formal argument. The value of each argument is transferred into function and assignment to corresponding formal argument. If functions a value returned value can be assigned to a variable of type same as return type of function. When a function is called the program controls is passed to function. Once the function completes its task, program control is passed back to the calling function. The general form of function call statement is:

If function has parenthesis but it doesnot return value If function has no arguments and it does not return value If function has parameters and it returns value If function has do not parameters but returns value The following points to be taken into consideration wish function calls statement are used. The function name type & number of variable listed in function statements must that of function

deceleration statement and the header of function definition. The names of the variables in the function deceleration function call statement and that in the header of

definition may be different. By default arguments are always passed by value in C function call. This means that local copies of the

values of arguments are passed function. Arguments presents in the form of expression are evaluated and converted to the type of formal

parameters at the beginning body of the function. A variable may be assigned value returned by function after it is executed using function call statement,

provided return type where the function is not void type.Define function grater to find out the greatest number among two numbers

#include<stdio.h>#include<conio.h>int grater(int x,int y){ if(x>y)return (x); else return (y); }void main(){ int a,b,c,d,e; clrscr();printf("Enter numbers"); scanf("%d%d%d%d",&a,&b,&c,&d);d=grater(a,b);e=grater(d,c);printf("THe greater number is%d",e);getch(); }

Define the function greatest to find out greatest among here numbers#include<stdio.h>#include<conio.h>int grater(int x,int y){ if(x>y)return (x);else return (y); }void main(){int a,b,c,d,e; clrscr();printf("Enter numbers");scanf("%d%d%d%d",&a,&b,&c,&d);d=grater(a,b);e=grater(d,c);printf("THe greater number is%d",e);getch(); }

73

Page 74: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalFunction Parameters: Function parameters are means for communication between calling and called functions. They can be classified into formal parameters and actual parameters. The formal parameters are the parameters given in the function declaration and function definition, the actual arguments or permanents are specified in the function are called. In above example a and b are actual arguments which are used in calling unction while parameters of x and y are formal arguments which are defined in function definition. The name arguments or parameters which must be same in function definition. The name of formal and actual arguments need not be same but data type and numbers of them must be matched.Category of Function According to Return Value and Arguments: According to the arguments and return type present in function definition and design can categoried function in three type.

Function with no arguments and no return value Function with arguments and no return type The function with arguments and return values

Function with on Arguments and No Return Values: When a function has not arguments it does not receive any data from calling function similar when it does not return a value. The function do not receive any data from the calling function. Thus in such function there is not data transfer between the calling function and called function. This type of function is defined as: void function name () { }They keyword void means the function does not return any values there is not arguments within the parenthesis which implies function has no argument and it does not receive any data for the called function.WAP to illustrate function with no arguments and no return value

#include<stdio.h>#include<conio.h>void addition(){ int a,b,sum;printf("Enter two numbers"); scanf("%d%d",&a,&b);sum=a+b;printf("the sum is%d",sum);}void main(){ clrscr();addition();getch();}

Function with Arguments but has Arguments but No Return Value: The function has argument and reveries the data from calling function. The function completes task and does not return any values to calling function. Such type of functions are defined as: void function (arguments) { }WAP to illustrate the functions with arguments but no return type

#include<stdio.h>#include<conio.h>void addition(int a,int b){ int sum; sum=a+b;printf("the sum is%d",sum);}void main(){ int a,b; clrscr();printf("Enter two numbers");scanf("%d%d",&a,&b);addition(a,b);getch(); }

Function with Arguments and Return Value: The function of this category has arguments and reveries data from calling function. After completing its task, it returns results to calling function through return statement. Thus there is data transfer between called function and calling function using return values and arguments. These types of functions are defined and return types function names (arguments) { body}WAP to illustrate the function with arguments and return values.

#include<stdio.h>#include<conio.h>int addition(int a,int b){int sum; sum=a+b;return sum; }void main(){ int a,b; clrscr();printf("Enter two numbers"); scanf("%d%d",&a,&b);printf("the sum is%d",addition(a,b));getch(); }

74

Page 75: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalDifference Type of Function Calls: The arguments in function can be passed in two ways: pass arguments by value and pass arguments by address or references for pointer:Function Call by Value (Pass Arguments by Value)When values of actual arguments are passed to function as argument it is known as function call by value. In this call, value of each actual argument is copied into corresponding formal arguments of the function definition. The content of arguments int calling functions are not altered even if they are changed into called function.WAP to illustrate function call by value

#include<stdio.h>#include<conio.h>void swap(int,int);void main(){ int a,b; clrscr(); a=90;b=89;printf("\nbefroe swap a and b are %d and %d",a,b);swap(a,b);printf("\nafter swap are %d and %d",a,b);getch();}void swap(int x,int y){int temp; temp=x; x=y; y=temp;printf ("\nthe value within function %d and %d",x,y);}

In this program the value a and b are copy to void swap(int x , int y) then calculates inside function only, when again original value s are not changed in the main program so this process is sililar to pass argument by value.Function Call by Reference (Pass Arguments by Address): In this type of function call, address of variable or arguments is passed to the function as arguments instead of actual value of variable.Pointer: A pointer is a variable that store a memory address of a variable. Pointer can be any name that is legal for other variable and it is declared in same fashion like other variable but it always proceeded by*(asterisk) operator. Thus pointer variables are defined as: int *s; float *b; char*c;Here int *a, int *b, int *c is pointer variables which stores address of another integer, float and character variables. Thus the following are valida=&p;b=&y,c=&y.WAP to swap the values of two variables using call by reference

#include<stdio.h>#include<conio.h>void swap(int*,int*);void main(){int a,b;clrscr();a=99;b=9;printf("\nbefroe swap a and b are %d and %d",a,b);swap(&a,&b);printf("\nafter swap are %d and %d",a,b);getch(); }void swap(int *x,int *y){int temp;temp=*x;*x=*y;*y=temp;}

Recursive Function: Recursive is a technique for defining a problem in terms of one or more smaller subunit of same problem. The solution of problem is built on result from the simpler versions. The rexcursive function is one that calls itself directly or indirectly to solve a smaller version of its task until a final call which does not require a self call. Thus function is called recursive function if it calls to itself. Recursion is a process by which a function calls itself repeatedly until some specified condition will be satisfied. Thus process is used for repetitive calculation in which each action is stated in term of previous result. Many iterative or repetitive problems can be written in this form.

To solve problem using recursion methods two conditions must be satisfied therefore: Problems could be written or defined in term of its previous result.

75

Page 76: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal Problems statement must include a stopping condition. We must have an if statement somewhere to

force the function to return without the recursive call being executed otherwise the function will never return.

WAP to find the factorial of number using recursive method#include<stdio.h>#include<conio.h>int factorial(int n){if(n==1) return(1); else return(n*factorial(n-1));} void main(){ int num; clrscr(); printf("Enter a number"); scanf("%d",&num); printf("the factorial is%d", factorial (num)); getch(); }

WAP to generate Fibonacci series using recursive method.#include<stdio.h>#include<conio.h>int fib(int n){if(n==1) return (1); else if(n==2) return (1); else return(fib(n-1)+fib(n-2));} void main(){ int num,i; clrscr(); printf("Enter many number"); scanf("%d",&num); for(i=1;i<=num;i++) printf("\nthe first %d is%d",i,fib(i)); getch(); }

Recursive IterationA function is called for definition of same function to do repeated task

Loop is used to do repetited action.

Recursion is the top down approach to problems solving it divides the problem int pieces.

Iteration is like a bottom up approach; it begins with what is known and form this if constructs the solution step by step procedure.

In recursion a function calls to itself until some condition will be satisfied.

Iteration a function does not call to itself

Problem could be written or defined in term of its previous result to solve a problem.

It is not necessary to define a problem in terms of its previous result to solve in iteration

All problems cannot be solved using recursion All problems cannot be solved uing iterationConcept of Local, Global, Static and Register VariablesLocal /Automatic Variables: The automatic variables are always declared within a function/block. They are local to the particular function /block in which they are declared. As local variables are defined within body of function / block, other functions cannot access the variables. The compiler shows errors in case other function cannot access the variables. The local variables are created when function is called and destroyed automatically when the function exit. The keyword auto may be used for storage class specification while deceleration of variable. A variable declared inside a function without storage class specification auto is by default, an automatic local variable.Default initial value of localvariable is unpredictable value which is often called garbage value. The scope of it local to the block in which variable is defined. Again its life is till the control remains within in which the variable is declared. The system supply the garbage value to it.Initial Value: The initial value assigned to a variable if no value is assigned to local variable. Scope: Scope of variable can be defined as region open which variables are visible.Lifetime: The period of variable availableity function on time duration which memory is associated with as variable. Its life time as availabel only inside function block only. WAP to illustrate local variable.

#include<stdio.h>#include<conio.h>

76

Page 77: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalint fact(int n){int f=1; int i;for(i=1;i<=n;i++) f*=i;return (f); }void main(){ int num=5;clrscr();printf("the factorial of 5 is%d",fact(num));getch(); }

Global Variable Variable that are both are available and active thorough entire program are known as external variable. They are also known global variable. The external variable or global variable are declared outside the block of functions. Unlike local variables, global variables can be accessed by any functions in the program. The default initial variables of variables are zero. The scope of variable is within whole program. The life times are as long as the program’s executions. For example, external deceleration of integer variable roll and float variable are available up to getch function only.void main () { }WAP to illustrate global variables

#include<stdio.h> #include<conio.h>void fun();int a=10;void main(){printf("\t%d",a); fun();printf("\t%d",a);getch(); }void fun(){ a=20;printf("\t%d",a++);}

Static VariableThis is another class of local variable. A static variable can only be accessed from function in which it was declared, like a local variable. The static variable is not destroyed on exit from function termination instead its value is preserved and becomes available again when the function is next called. Static variables are declared as local variables, but declaration is preceded by word static. Static variable can be initialized as normal; the initialization is done once only when program starts. The default initial value for this type of variables is zero (if user doesn’t initialize its). The scope is similar local variable is only available to block in which variable is defined. But life time is global i.e. its value can not be reserve between different function calls.WAP to illustrate static variable.

Register VariableRegister variables are special type of automatic variables. Automatic variables are allocated storage in memory of computer however for most computers accessing data in memory is considerably slower than processing in

77

#include<stdio.h>#include<conio.h>void staticc(void);void main(){staticc();staticc();staticc();staticc();getch();}void staticc(void){static int i=1;printf("\nthe value of %d",i);i++;}OutputThe vaalue of 1The vaalue of 2The vaalue of 3The vaalue of 4

#include<stdio.h>#include<conio.h>void staticc();void main(){staticc();staticc();staticc(); staticc();getch();}void staticc(){int i=1;printf("\nthe value of %d",i); i++;}OutputThe vaalue of 1The vaalue of 1The vaalue of 1The vaalue of 1

Page 78: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalthe CPU. Those computers often having small amount of storage within CPU itself. Where data can be stored and accessed quickly. Theses storage calls are called register. Normally the computer determines what is to be stored in register of CPU at what times .However C language provides the storage class register so that the programmer can suggest to the compiler that particular automatic variables should be allocated to CPU register. Thus register variable provide a certain control over efficient of program execution is faster aqccessed. Variables which are used repeatedly and have good access times are critical may be declared to register.Register variables behaves way just like automatic variables. The storage block and storage is freed when block is exite. The scope of register variable is local to block where they are declared. Rule for initialization for register variables are same as for automatic variables. void main () { }Difference between Local, Global and Static Variables

Local Global Static The variables are declared within function /block. the scope is only within the function in which they are defined

Floral variables are defined outside the function so that their scope is through the program

Static variables are special case of local variables thus static variables are also defined inside the functions or block

The initial calls is unpredictable or garbage value

The initial value is zero The initial value is zero

The lifetime is till the control remains within the block or function in which the variable is defined. The variable is destroyed when function returns to the calling functions or block ends

The lifetime is till programs execution does not come to an end variables are created when n program starts and destroyed when program ends

The value persists between different function calls. Thus lifetime is same as global variables

The keyword auto is used The keywords extern is used The keyword static is used.WAF which receives a float and an int form main () finds the product of hose two and return product which is passed through user

#include<stdio.h>#include<conio.h>float product(float ,int);void main(){ float first,pro;int sec; clrscr();printf("\n Enter float number");scanf("%f",&first);printf("Enter secod int");scanf("%d",&sec);pro=product(first,sec);printf("%f",pro);getch(); }float product(float a, int b){float product;product=a*b;return(product);}

WAP area of circle which accepts radius of loath value and circles having different radii.#include<stdio.h>#include<conio.h>#define pi 3.1416float areaof(float r){return(pi*r*r); }int main(){float r1,r2,a1,a2;clrscr();printf("\n Enter radius");scanf("%f",&r1);printf("Enter secod radius");scanf("%f",&r2);a1=areaof(r1);a2=areaof(r2);printf("\n first are is%f",a1);printf("\n the second area is:%f",a2);getch();return 0;}

78

Page 79: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalWAP which has three user-defined function read data process data and display data use read data function to read two numbers form key board and process data() to sum those numbers and display the sum.

#include<stdio.h>#include<conio.h>float a,b;void readdata(){printf("Enter numbers");scanf("%f%f",&a,&b); } float process(float x, float y){ return (x+y); } void display(float value){ printf("\n the value isi%f",value); } void main(){ float sum; readdata(); sum=process(a,b); display(sum); getch(); }

WAP name factorial(x) which accepts an int x and returns long value which a program to valuate permutation of numbers (i.e. not using factorial function.)

#include<stdio.h>#include<conio.h>int factoral(int x){int i, fact=1;for(i=1;i<=x;i++)fact*=i;return fact;}void main(){long f1,f2;int perm;int n,r;clrscr();printf("\nEnter n and r");scanf("%d%d",&n,&r);f1=factoral(n);f2=factoral(n-r);perm=(int)f1/f2;printf("\n perm is%d",perm);getch(); }

WAP that will evaluate y=x2 where y and x are floating points variables and n is an integer variables iterative methods recursive methods.

#include<stdio.h>#include<conio.h>float power(float ,int);int main(){float x,y;int n;clrscr();printf("\n enter base in x \t");scanf("%f%d",&x,&n);y=power(x,n);printf("The %.2f raised to power is %d is %.2f",x,n,y);getch();return 0;}float power(float x,int n){float result=1;int i;for(i=1;i<=n;i++)result*=x;return result;}

#include<stdio.h>#include<conio.h>#include<process.h>float power(float base,int exp){if(exp<0){printf("cannot raised to -ve\n");exit(1);}else if(exp==0){return 1.0;}elsereturn (base*power(base,exp-1));}void main(){ float x,y; int n;clrscr();printf("\n enter base in x \t");scanf("%f",&x);printf("Enter exp");scanf("%d",&n);y=power(x,n);printf("The result is%f",y);getch();}

WAP to define the largest among six numbers without using array79

Page 80: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<stdio.h>#include<conio.h>#include<process>float grater(float x,float y){if(x>y) return x;else return y;}void main(){ float f1,f2,f3,f4,f5,f6; float fs1,fs2,fs3,fs4,fs5,fs6;clrscr();printf("Enter six numbers");scanf("%f%f%f%f%f%f",&f1,&f2,&f3,&f4,&f5,&f6);fs1=grater(f1,f2);fs2=grater(fs1,f3);fs3=grater(fs2,f3);fs4=grater(fs3,f4);fs5=grater(fs4,f5);fs6=grater(fs5,f6);printf("\n the greatest is%.2f",fs6);getch();}

WAP to convert lowercase character into uppercase character using call by reference#include<stdio.h>#include<conio.h>void conversion(char *c){if(*c>=65&&*c<=90) *c+=32;else if(*c>=97&&*c<=122) *c-=32;}void main(){ char c; clrscr();printf("\n Enter character\n"); scanf("%c",&c);conversion(&c);printf("\n the equivalent character\t%c",c);getch(); }

Wap recursive function to generate particular term in Fibonacci series.#include<stdio.h>#include<conio.h>int fib(int n){if(n==1) return (1); else if(n==2) return (1); else return(fib(n-1)+fib(n-2));} void main(){ int num,i; clrscr(); printf("Enter many number"); scanf("%d",&num); i=fib(num); printf("\nthe first %d is%d",num,i); getch(); }

WAP to calculate sum of digits of number without using recursive function using recursion#include<stdio.h>#include<conio.h>int sumof(long num){ int r,q,sum=0;do{ q=num/10;r=num%10;num=q;sum+=r;} while(q!=0);return sum;} void main(){ long int n; int sum; clrscr(); printf("Enter numbers"); scanf("%ld",&n); sum=sumof(n); printf("\nthe is%ld",sum); getch(); }#include<stdio.h>#include<conio.h>int sumof(long);void main(){long int n;int sum;clrscr();printf("Enter numbers");scanf("%ld",&n);sum=sumof(n);

80

Page 81: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\nthe is%ld",sum);getch(); }int sumof(long num){ static int i=1,sum=0;int digit;if(i<=5){ digit=num%10;sum+=digit;num/=10; i++;sumof(num);}return sum;}

Find out the errors in the following code#include<stdio.h>#include<conio.h>void add(int a, int b){ int sum; sum=a+b; return sum;} void main(){ int x,s; float y; x=30; y=80; s=add(x,y); printf("the sum is\t%d",s); getch();}

Passing Pointer to a FunctionA pointer can be passed to a function as an argument. Passing a pointer means passing address of

variable instead of value to a function. As address is passed in this case, this mechanism is also known as call by address or call by reference. When pointer is passed to a function the formal argument of the function must be compatible with the passing pointer i.e. if integer is being passed, the formal argument in function must be pointer of type. As address of variable is passed in mechanism, if value in passed to address is changed within function definition, the value of actual variable also changed.WAP to illustrate the use of passing pointer to a function

#include<stdio.h>#include<conio.h>void add(int *m){*m=*m+10; }void main(){int marks;clrscr();printf("Enter actual marks\t");scanf("%d",&marks);add(&marks);printf("\n the grace marks is\t%d",marks);getch();}

WAP program to covert lowercase t upper case by reference pointer to a function.#include<stdio.h>#include<conio.h>void read(int,int, int [][10]);void display(int,int,int [][10]);int i,j;void main(){ int matrix1[10][10],matrix2[10][10],product[10][10],k;int m,n,p,q,sum=0;clrscr();do{printf("Entre first order");scanf("%d%d",&m,&n);printf("Entre second order");scanf("%d%d",&p,&q);}while(n!=p);printf("\nElements of first\n");read(m,n,matrix1);printf("\nElements of secondt\n");read(p,q,matrix2);for(i=0;i<m;i++) for(j=0;j<q;j++){for(k=0;k<n;k++){sum+=matrix1[i][k]*matrix2[k][j];}product[i][j]=sum; sum=0;}printf("\nfirst inputare\n"); display(m,n,matrix1);printf("\nsecond inputare\n"); display(p,q,matrix2);printf("\nproduct are\n"); display(m,q,product);getch(); }void read(int x,int y,int mat[][10]){ for(i=0;i<x;i++) for(j=0;j<y;j++) scanf("%d",&mat[i][j]);}void display(int x,int y,int mat[][10]){ for(i=0;i<x;i++){ for(j=0;j<y;j++)

81

Page 82: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\t%d",mat[i][j]);printf("\n");} }

Passing Arrays to FunctionLikewise ordinary variables it is possible to pass value of an array elements i.e entire array argument to

a function. To pass entire array to a function array name must appear by itself, without brackets or subscript, an actual argument in function call statement. The corresponding formal argument in function definition is written in same manner. When declaring a one dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of array is not specified within pair of empty square brackets. The size of array is not specified within the formal argument deceleration.

syntax: function name (array name) for function call.Return type function name (data type array name) for function prototype;Return type function name (data type* pointer variable);

When an array is passed to function the value of array elements are not passed to the function. Rather the array name is interperated as the address of element. This address is assigned to the corresponding formal argument when the function is called. The formal argument therefore becomes a pointer to first array element. Thus array is passed using call by reference. WAP to illustrate passing array to a function

#include<stdio.h>#include<conio.h>void display(int n){printf("\n%d",n); }void main(){ int num[5]={40,50,60,70,80},i; clrscr();printf("The content before are");for(i=0;i<5;i++)display(num[i]);getch();}

WAP to illustrate to passing an entire array to a function.#include<stdio.h>#include<conio.h>void change(int a[]){ int b[]={1,2,3,4,5}; int i;for(i=0;i<5;i++) a[i]=b[i]; }void main(){int num[5]={40,50,60,70,80},i; clrscr();printf("The content before are");for(i=0;i<5;i++) printf("\t%d",num[i]);change(num);printf("the elements of before change are");for(i=0;i<5;i++) printf("\t%d",num[i]);getch();}

WAP to read 10 numbers and reorder them m in ascending order.#include<stdio.h>#include<conio.h>void sort(int[]);void read(int []);void display(int []);void main(){ int num[10]; clrscr();printf("Enter 10 numbers"); read(num);sort(num);printf("\tthe numbers in ascending are\n");display(num);getch(); }void sort(int num[]){ int i,j,temp;for(i=0;i<9;i++) for(j=i+1;j<10;j++){if(num[i]>num[j]){ temp=num[i];num[i]=num[j];num[j]=temp; } }}void read(int num[]){int i;

82

Page 83: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfor(i=0;i<10;i++)scanf("%d",&num[i]);}void display(int num[]){ int i;for(i=0;i<10;i++) printf("\n%d",num[i]);}

WAP to read array to two dimensional than double the content of each element of the array and display the result. Out program must have three user defined function for processing and display matrices.

#include<stdio.h>#include<conio.h>#define m 2#define n 3void process(int [][n]);void read(int[][n]);void display(int [][n]); int i,j;void main(){ int matx[m][n]; clrscr();printf("Entre matrix of order%d*%d",m,n);read(matx);process(matx);display(matx);getch(); }void process(int matrix[][n]){for(i=0;i<m;i++) for(j=0;j<n;j++)matrix[i][j] =2*matrix[i][j];}void read(int matrix[][n]){for(i=0;i<m;i++) for(j=0;j<n;j++){printf("\nmatrix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]);} }void display(int matrix[][n]){for(i=0;i<m;i++){ for(j=0;j<n;j++)printf("%d\t",matrix[i][j]);printf("\n");}}

WAP to read n numbers in an array. Pass this array to a function which finds and display the sum of even numbers only and the products of odd numbers only.

#include<stdio.h>#include<conio.h>void calculate(int n[]);void calculate(int [],int );void main(){ int num[50],n,i;printf("\n How many numbers"); scanf("%d",&n);printf("\n Enter %d numbers\t",n); for(i=0;i<n;i++)scanf("%d",&num[i]);calculate(num,n);getch();}void calculate (int ns[],int n){ long sum=0, product=1; int i;for(i=0;i<n;i++){ if(ns[i]%2==0)sum+=ns[i];else product*=ns[i];}printf("\n the sum of even numbers are\t%ld",sum);printf("\n tht products of odd numbers are\t%ld",product);}

WAP to read matrix of order m*n. pass this matrix to a function which increase each element by 2.#include<stdio.h>#include<conio.h>#define m 3#define n 3void increase(int mat[m][n]){ int i,j;for(i=0;i<m;i++) for(j=0;j<n;j++)mat[i][j] =mat[i][j]+2;}void main(){ int matrix[m][n],i,j; clrscr();

83

Page 84: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("Enter matrix of order %d*%d\n",m,n);for(i=0;i<m;i++) for(j=0;j<n;j++){printf("\nmarix[%d][%d]=",i,j); scanf("%d",&matrix[i][j]);}printf("\nYour input marix is\n");for(i=0;i<m;i++) { for(j=0;j<n;j++)printf("%d\t",matrix[i][j]); printf("\n");}increase(matrix);printf("\n the resultant marix is:\n");for(i=0;i<m;i++){ for(j=0;j<n;j++)printf("%d\t",matrix[i][j]);printf("\n"); } getch();}

WAP to ask order of matrix and read a matrix of the order raise the power of each elements of a given matrix by 3 and display the resultant matrix.

#include<stdio.h>#include<conio.h> int i,j;void display(int m,int n,int mat[][10]){for(i=0;i<m;i++){ for(j=0;j<n;j++)printf("%d\t", mat[i][j]);printf("\n"); } }void main(){int matrix[10][10],p,q; clrscr();printf("Enter matrix of order "); scanf("%d%d",&p,&q);printf("the order is %d*%d",p,q);for(i=0;i<p;i++) for(j=0;j<q;j++){printf("\nmarix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]);}printf("\nYour input martix is:\n");display(p,q,matrix); for(i=0;i<p;i++) for(j=0;j<q;j++)matrix[i][j]=matrix[i][j]*matrix[i][j]*matrix[i][j];printf("\nthe resultant matrix\n");display(p,q,matrix);getch();}

WAP to find transpose matrix of matrix.#include<stdio.h>#include<conio.h>#include<process.h> int i,j;void display(int m,int n,int mat[][10]){for(i=0;i<m;i++){ for(j=0;j<n;j++)printf("%d\t", mat[i][j]); printf("\n"); } }void main(){ int matrix[10][10], tmatrix[10][10],p,q; clrscr();printf("Enter matrix of order "); scanf("%d%d",&p,&q);if(p>9||q>9){ printf("\n the order is out of range");getch(); exit(1);}printf("the order is %d*%d",p,q);for(i=0;i<p;i++) for(j=0;j<q;j++){printf("\nmarix[%d][%d]=",i,j);scanf("%d",&matrix[i][j]);}printf("\nYour input marix is:\n");display(p,q,matrix);for(i=0;i<p;i++) for(j=0;j<q;j++)tmatrix[j][i]=matrix[i][j];printf("\nthe transpose matrix\n");display(q,p,tmatrix);getch();}

84

Page 85: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalWAP to ask order of matrix and read those matrixes. Find multiplication matrix of is suitable for multiplication.

#include<stdio.h>#include<conio.h>void read(int,int, int [][10]);void display(int,int,int [][10]); int i,j;void main(){int matrix1[10][10],matrix2[10][10],product[10][10],k;int m,n,p,q,sum=0; clrscr();do{ printf("Entre first order"); scanf("%d%d",&m,&n);printf("Entre second order"); scanf("%d%d",&p,&q);}while(n!=p); printf("\nElements of first\n");read(m,n,matrix1);printf("\nElements of secondt\n");read(p,q,matrix2);for(i=0;i<m;i++) for(j=0;j<q;j++){ for(k=0;k<n;k++){sum+=matrix1[i][k]*matrix2[k][j];}product[i][j]=sum;sum=0;}printf("\nfirst inputare\n");display(m,n,matrix1);printf("\nsecond inputare\n");display(p,q,matrix2);printf("\nproduct are\n");display(m,q,product);getch(); }void read(int x,int y,int mat[][10]){for(i=0;i<x;i++) for(j=0;j<y;j++)scanf("%d",&mat[i][j]);}void display(int x,int y,int mat[][10]){for(i=0;i<x;i++){ for(j=0;j<y;j++)printf("\t%d",mat[i][j]);printf("\n");}}

POINTERMemory is important area where data/information are stored. As computers have primary memory also

known as RAM (Random Access Memory). RAM holds currently running program along with data variables. All variables used in a program reside in memory when the program is executed. Computer memory RAM is divided into various of small units locations. Each location is represented by some unique number known as memory address. Each memory location is represented by some unique number which is known as byte. A char data is one byte in size and hence needs one memory location, similarly integer data is two bytes in size so it requires two memory locations. The smaller unit of memory address is byte(0 or 1).

Each byte in memory is accessed with unique address. An address is an integer labeling bytes in memory. The integer is always positive values that range from zero to some positive integer constant corresponding to location in memory. Thus a computer having 1 GB has 1024*1024*1024 i.e. 1073741824 bytes. The memory address 65524 represents bytes in memory and it can store data of one byte.

Each variable in C program is assigned space in memory. When a variable is declared, it tells computer to hold in memory in appropriate size variable. According to type of variable declared, the required memory locations are reserved. int a=30; float b; char c. here a reserve 2 bytes similarly char c holds 1 bytes.

WAP to display memory location reserved by variables#include<stdio.h>#include<conio.h>void main(){int a; a=20;printf("\n the address is\t%u",&a);printf("\n the vlaue of a \t%d",a);getch(); }

Here &a denote address of variable. The variables takes two bytes data in memory. As it’s of type is int. It takes two memory area locations 1245066 and 1245067 although it takes a block of two bytes memory

85

Page 86: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalconsisting two different addresses, this memory is accessed by first address. The first address is only shown which known as base address. Again control string %u is used to display address of variables as value of address is always positive number.WAP to illustrate address reserved by different data types

#include<stdio.h>#include<conio.h>void main(){ int a=10,b=20;float c=10.5; char d='M'; clrscr();printf("\n The base address of a\t%u",&a);printf("\n The base address of b\t%u",&b);printf("\n The base address of c\t%u",&c);printf("\n The base address of d\t%u",&d);getch();}Output: The base address of a 1045064The base address of b 1045060The base address of c 1045056The base address of d 1045055

Introduction to PointerA pointer is a variable that contains a memory address of another variable. Normally a pointer variable

is declared some way like other variables in C. So that it will work only with address of another variable. Just as integer variable can hold only integer, a character variable can hold only character type. Each pointer variables can point only to one specific type (int ,float, char). Pointer can have name that is legal for other variable and it is declared in some fashion like other variable but while decelaration we preceded by * asterisk operator infornt of variable name. int num; Here num is normal variable of integer it can store only integer value. int *p; It signifies p is pointer variable it can store address of integer variable. The address of float variable cannot be stored in p. int *p; float num; p=&num//not validPointer Deceleration

Pointer variable can be declared as: data type *variable name;int *s; char *p; the first s is an integer pointer and it tells compiler that holds address of any int variables. In same way char pointer that store address of any char variable.

WAP to demonstrate pointer variables#include<stdio.h>#include<conio.h>void main(){int v=10,*p; //*p is pointer variablep=&v; //the address of variable v is assigned to pprintf("\n address of v is\t%u",&v); // display address of v directlyprintf("\n the address v is\t%u",p); // display address of v indirectlyprintf("\n value of v is\t%d",v); // display value directlyprintf("\n value of address v is \t%d",*p); //display value of p indirectlyprintf("\n address of p=%u",&p); // display address of *pgetch(); }

Indirection or Dereference Operator :The * operator is used inform of a variable, is called pointer or indirection of dereference operator. Normal variable provides direct access to their own values where as a pointer provides indirect access to variables. The indirection operator* is used in two distinct ways within pointers deceleration. When the pointer is dereferenced inform of variable the indirection operator indicates the values at the memory location stored in pointer.* is the same operator that can be used as multiplication operator. The compiler knows automatically which operator to call based on the context of is used.Address Operator: &operator is known as address operator thus “&a” denotes address of normal to pointer variable.Initialization Pointers: Address of some variable can be assigned to a pointer variable at the time of deceleration of pointer variable. int num; int * ptr=&num; These two statements are equivalent to following statements. int num; int *p;p=&num;Bad Pointer : When a pointer variable is first declared it does not have a valid address, the pointer is uninitialized or bad. The dereference operation on a bad pointer is a serious run time error. Each pointer must

86

Page 87: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalhave be assigned a valid address before it can support dereference operators. Before that the pointer is bad and must not be used.

In fact every pointer contains garbage value before assignment of some valid address. Correct code override the garbage value with a correct reference to an address and thereafter the pointer work fine. There is nothing automatic that gives a pointer valid address. Void Pointer: A void pointer is special type of pointer. It can point to any data type from an integer float or string of characters. Using void pointer the pointer data can +ve referenced directly. Type casting or assignment must be used to change void pointer to concrete data type to which we can refer.WAP to illustrate the void pointer

#include<stdio.h>#include<conio.h>void main(){int a=40; double b=4.5;void *v; clrscr();v=&a;printf("\n a=%d",*(int*)v);/* not simple*/v=&b;printf("\nb=%lf",*((double*)v));getch();}

Null Pointer: A null pointer is a special pointer value that points nowhere or nothing. That is no other valid pointer to any other variable or array cell or anything else will ever be which is defied a header files stdio.h stdio.h string.h int *ptr=NULL;To test a pointer for null before inspect value pointed to code such as the following can be used.

If(ptr!=NULL) printf(“value =%d”,*ptr);Pointer to Pointer (Double Pointer): C allows use of pointer that point to other pointer and theses in turn, point to data for pointer to do that we only need to add asterisk for each level of reference. int a=30; int *p; int **q; p=&a; q=&p;

**q is double pointer it requires double pointing to refer to variable address.Double pointer variable requires two label of indirection while assigning the value we use double

address to q variable. As both *p and **q display 30 if they are pointing to the same address.Arrays of Pointers: An array of pointers can be declared as data type *pointer (size); int *p [5];

This declares an array of 5 elements each of which pointes to an integer, the first pointer is called p [0];Initially these pointers are uninitialized and they can be used as int a=10,b=100,c=1000; p[0]=&a; p[1]=&a; p[2]=&c;Relationship Between 1d Array and Pointer

Array name by itself is an address of pointer. It points to address of first element. Thus if x is one dimensional array then address of first array element can be expressed as either &x [0] or simple x [0]... in general the address of the array element i+1 can be expressed as either &x+i. In the expression x+i, x represents array name whose elements may be integers, characters, float, etc, and I represents integer quantity. Thus x+i specifies address that is a certain number of memory calls beyond the address of first element. Thus x[i] and *(x+i) both represent same content of that address.WAP to display elements with their address using name as pointer.

#include<stdio.h>#include<conio.h>void main(){int x[5]={20,40,6,8,100},k; clrscr();printf("\n aray elements\t elements \t address");for(k=0;k<5;k++)printf("\ns[%d]\t%d\t%u",k,*(x+k),x+k);getch();}

Similarly#include<stdio.h>#include<conio.h>void main(){ int x[5]={20,40,6,8,100},k; clrscr();printf("\n aray elements\t elements\t address");

87

Page 88: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfor(k=0;k<5;k++)printf("\ns[%d]\t%d\t%u",k,x[k],&x[k]);getch();}

From the above it can be concluded that in case of array &x[k] is same as x+k and x[k] is same as *(x+k).One Dimensional Array

#include<stdio.h>#include<conio.h>void main(){int a[5]={1,2,3,4,5};int i;for(i=0;i<5;i++) {

printf("add is\t%d\tand \t value \t%d\n",&a[i],a[i]);/*for Normalprintf("add is\t%d\tand \t value \t%d\n",(a+i),*(a+i));/*for pointer type

printf("\n"); }getch();}

WAP to calculate average marks of 10 students in a subject using pointer. Read marks of each student form keyboard.

#include<stdio.h>#include<conio.h>void main(){ int marks[10],i,sum=0; float avg; clrscr();printf("Enter marks of each sub");for(i=0;i<10;i++){ scanf("%d",marks+i);sum+=*(marks+i);}avg=sum/10;printf("The avrage is%f",avg);getch ();}

Pointer and 2d ArraysMultidimensional array can also be represented with an equivalent pointer single dimensional array. A

two dimensional array is actual a collecting of one dimensional arrays, each indicating a row. It is stored in memory of row form. For eg:

a=

1 2 34 5 67 8 9 is store b in row wise order in memory

a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2]1 2 3 4 5 6 7 8 91245032 1245036 1245040 - - - - - 1245064

#include<stdio.h>#include<conio.h>void main(){ int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};int *b[3][3],i,j;clrscr();for(i=0;i<3;i++){ for(j=0;j<3;j++){b[i][j]=&a[i][j];printf("The value is%d and addressed\n",*b[i][j],&*b[i][j]); }}getch(); }

It is possible to access two-dimensional array elements using pointers same way in one dimensional array. Each row of the two dimensional array is treated as a one dimensional array. Each row of two dimensional array as a pointer to a group of contiguous one dimensional array. Syntax:

data type (*pt variable) [size2]; instated data type array [size1] [size2];Suppose x is two dimensional integer array having 4 row and 5 columns. We can declare x as

int (*x) [4];Rather than int x [4] [5]; it can be concluded that x pointer to first row.

Here in first deceleration x is defined to be a pointer to a group of continuous one dimensional element integer array. The x points to first 5 elements array which is actual first row of two dimensional arrays.

88

Page 89: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalSimilarly x+1 points to the second row 5 elements which is second row of the two dimensional array. It is illustrate as

*x ([0][0]) *x+1 ([0][1]) *x+2 ([0][2]) *x+3 ([0][3]) *x+4 ([0][4])*(x+1) ([1][0]) *(x+1)+1 ([1][1]) *(x+1)+2 ([1][2]) *(x+1)+3 ([1][3]) *(x+1)+4 ([1][4])*(x+2) ([2][0]) *(x+2)+2 ([2][1]) *(x+2)+2 ([2][2]) *(x+2)+3 ([2][3]) *(x+2)+4 ([2][4])*(x+3) ([3][0]) *(x+3)+3 ([3][1]) *(x+3)+2 ([3][2]) *(x+3)+3 ([3][3]) *(x+3)+4 ([3][4])

Thus in 2d array as,&x[0][0]=*x &x[0][1]=*x+1 &x[2][0]=*x+2 &x[2][4]=(*x+2)+4

Two Dimensional Array#include<stdio.h>#include<conio.h>void main(){int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};int i,j;for(i=0;i<3;i++) {for(j=0;j<3;j++){

printf("add is\t%d\tand \t value \t%d\n",&a[i][j],a[i][j]);/*for normalprintf("add is\t%d\tand \t value \t%d\n",*((a+i)+j),*(*(a+i)+j));/*for pointer

printf("\n"); } }getch(); }

Illustrate 2d array represents in memory.#include<stdio.h>#include<conio.h>void main(){ int p[2][3]={{1,2,3},{4,5,6}}; clrscr();printf("\n%u and%u",p,*(p+1));printf("\n*p=%u\t*(p+1)%u",*p,*(p+1));printf("\n(*(p+0)+1)%u\t*(*(p+1)+1)%u",*(p+0)+1,*(p+1)+1);printf("\n(*(p+0)+1)%u\t*(*(p+1)+1)%u",*(*(p+0)+1),*(*(p+1)+1));getch();}

WAP to add to add two m*n matrices using pointer.#include<stdio.h>#include<conio.h>#define m 2#define n 3void main(){int(*a)[n],(*b)[n],*(sum)[n],i,j; clrscr();printf("firtst matrix");for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",*(a+i)+j); printf("second matrix");for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",*(b+i)+j);printf("sum is");for(i=0;i<m;i++){ for(j=0;j<n;j++) {*(*(sum+i)+j)=*(*(a+i)+j)+ *(*(b+i)+j);printf("\t%d",*(*sum+i)+j); }printf("\n"); }getch(); }}

WAP to multiply matrices of order m*n and p*q using pointer#include<stdio.h>#include<conio.h>#define m 2

#define n 3 #define p 3 #define q 2

void main(){89

Page 90: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalint(*matrix1)[n],(*matrix2)[q],pr[m][q],i,j,k; int sum=0; clrscr();printf("firtst matrix");

for(i=0;i<m;i++) for(j=0;j<n;j++)scanf("%d",(*(matrix1+i)+j));printf("second matrix");for(i=0;i<p;i++) for(j=0;j<q;j++) scanf("%d",*(matrix2+i)+j);

for(i=0;i<m;i++) for(j=0;j<p;j++) { for(k=0;k<n;k++)sum+=*(*(matrix1+i)+k)**(*(matrix2+k)+j);*(*(pr+i)+j)=sum;sum=0;}printf("\nproduct are\n:"); for(i=0;i<m;i++){ for(j=0;j<q;j++)printf("\t%d",(*(*pr+i)+j));printf("\n"); }getch(); }

Pointer OperationsTo illustrate operations let us consider following declaration of ordinary variable and pointer variables.

int a, b; float c; int *p1,*p2; float*f;a) A pointer variable can be assigned the address of ordinary variable. For example p1=&a;

p2=&b, f=&c;b) Content of one pointer can be assigned to other pointer provide they point to same data

type. p1=p2; where both of them are pointer type as above.c) Integer data can be added to pointer variable, p1+2; d) One pointer can be subtracted from other pointer they must point same elements of array

void main(){ int a[]={1,2,3,4,5},*pf,*p1;p1=a; pf=a+2; pritnf(“%d”,pf-p1);}

e) The two pointer variables cannot be compared both pointers point to objects of the same data type If(p1>p2){}//invalid

f) There is no sense in ascending an integer to pointer variable. p1=100;p2=200; //invalidg) Two pointer variables cannot be multiplied together.p1*p2;h) A pointer variable cannot be multiplied by constant. p1*3;i) A null value can be assigned to a pointer variable.(p1=NULL)

String and PointerAs strings are arrays and arrays are closed connected with pointers, we can say that string and pointers

are closely related for example: char name [5] =”Shyam”;As string variable name is an array of 5 characters. It is a pointer to first character of string and can be

used to access and manipulate characters of the string. When a pointer to char is pointed in format of string, it will start to print pointer character and then successive characters until end of string is reached. Thus name prints Shyam, name +1 prints Shyam and name +2 prints Shyam etc.Dynamic Memory Allocation (DMA)

The process of allocating and freeing memory at run time is known as Dynamic Memory Allocation. This reserves the memory required by the program and returns this valuable resources to the system then reserved space is utilizatied for variable dynamically.

Through arrays can be used for data storage, they are of fixed size. The programmer must know size of array or data in advance while writing programs. A variable cannot be used to define size of array while declaring an array. In most situations it is not possible to know the size for memory required until run time. For example the size of the array used to store marks of students is fixed. Suppose the size of array used to stored name in character in 100. The program wont work if the number of students is more than 100. If number of students is less than 100 say 10. The 10 memory locations are used and rest 90 locations are reserved but not used, this is wastage of memory occurs. In these situations DMA will very be useful.Since an array name is actual pointer to first element within the array, it is possible to define array as pointer variable rather than general array. While defining conventional array system reserve fixed block of memory at the beginning of program design which is inefficient but this does not occur if the array is represented in terms

90

Page 91: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalof a pointer variable. The use of a pointer variable to represent an array requires some type of initial memory assignment before array elements are processed. This is known as Dynamic Memory Allocation. At execution time a program the compiler request more memory to be free memory. Thus DMA refers allocating and freeing memory at execution time or run time for better memory managemet.There are four library functions malloc() calloc(),free() and realloc() for memory useful management. These functions are defined with header file stdlib.h and alloc.h.malloc () : It allocates requested size of bytes and returns a pointer to first byte of the allocated space. Syntax:prt=data type* malloc (size);Here ptr is a pointer type data. The malloc () returns a pointer to an area of memory with size specified in size.s= (int*) malloc (100*size of (int));A memory space equivalent to 100 times the size of a integer bytes is reserved and the address of the first bytes of allocated memorycalloc () : The function calloc () provides access to the C memory heap. Which is available for dynamics allocation of variable sized block of memory? Unlike malloc (),function calloc () accepts two arguments no of block and size of each block. The first parameter specifies the number of items to allocate and size of each block specifies size of each items. The function calloc () allocates multiple blocks of storage each of same size and then sets all bytes to zero. The difference between them is that calloc initializes all bytes in the allocated block to zero. Thus it is normally used for requesting memory space at run time for storing derived data types such as and structure. s= (int*) calloc (5, 10*size of (int));In above statement allocates continuous space for 5 blocks, each of size 20 bytes. We can store 5 arrays each of 10 elements of integer types.free (): This build in function free up previously allocated space by calloc () malloc and realloc () functions. The memory dynamically allocated is not return to the system until the programmer returns the memories explicitly. This can be done using free) function. This function is used to release the space when it is not required/reserved. free (ptr); Here ptr is pointer to a memory block which must already created.realloc (): This function is used to modify size of previouly allocated memory space. sometimes previously allocated memory is not sufficient, we need additional space and sometimes the allocated memory is much larger than necessary , in both situations we should change the memory size already allocated with the help of function realloc(). ptr=malloc (size); ptr=relock (ptr, new size);This function allocates the new space size to the pointer variable ptr and returns a pointer to the first byte of the new memory block of memory fails to allocate it return null.WAP to illustrate the use of realloc() function

#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){ char*name; clrscr();name=(char*)malloc(11);strcpy(name,"Sp. Sharma");printf("\nname=%s",name);name=(char*)realloc(name,23);strcpy(name,"Mr. Shyam Sharma");printf("\nname=%s",name);getch();}

WAP to read number of students and then marks of each student. Display entered marks and their average. Use pointer array instead of conventional array to represent marks of students.

#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){ int n,i; float *p,sum=0,avg; clrscr();printf("How many"); scanf("%d",&n);printf("\n Enter many each student");p=(float*)malloc(n*sizeof(float));for(i=0;i<n;i++){ scanf("%f",p+i); sum+=*(p+i);}avg=sum/n;

91

Page 92: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n the average is");for(i=0;i<n;i++)printf("\t%f",*(p+i));printf("is%.2f",avg); free(p); getch(); }

WAP to read array of n integer using dynamic memory allocation and display largest and smallest element.#include<stdio.h>#include<conio.h>#include<stdlib.h>int main(){ int n,i; int *num,max,min; clrscr();printf("Enter number\n");scanf("%d",&n);num=(int*)calloc(n,sizeof(int));printf("\n enter numbers are%d",n);for(i=0;i<n;i++) scanf("%d",num+i);max=*num;min=*num;for(i=0;i<n;i++){ if(max<*(num+i))max=*(num+i);if(min>*(num+i)) min=*(num+i);}printf("Enter numbers%d",max);printf("\n Enter numbers are%d", min);getch(); return 0;}#include<stdio.h>#include<conio.h>#include<stdlib.h>void record (int n,int *x) ;void main(){ int i,n,*x; clrscr();printf("how many\n"); scanf("%d",&n);x=(int *) malloc(n*sizeof(int));for(i=0;i<n;i++) scanf("%d",x+i);record(n,x);for(i=0;i<n;i++)printf("%d\n",*(x+i));getch();}void record(int n,int *x){int temp,i,j;for(i=0;i<n-1;i++){ for(j=i+1;j<n;j++){if(*(x+i)>*(x+j)){ temp=*(x+i);*(x+i)=*(x+j);*(x+j)=temp;}}}}

Application of PointerThere are number of applications of pointer

1. Pointer is widely used in dynamic memory allocation. The functions used for allocation of memory at run time that return the address of allocated memory.

2. Pointer can be used to pass information back and forth between a function and its reference point. Pointer provides a way to return multiple values form arguments to function by reference address.

3. Pointers provide an alternative way to access individual array elements. They used to manipulate arrays more easily by using pointer nested of using array themselves.

4. They increase execution speed as they refer particular address directly.5. They are used to create complex data structure such as linked list, trees, and graphs.

Passing Pointer to FunctionA pointer can be passed to function as an argument. Passing pointer means passing address variable

instead of value. As address is passed in this mechanism is also known as call by reference. When pointer is passed to function while calling, formal argument of function must be compatible with the passing pointer. If integer pointer is being passed formal argument in function must be pointer of type. If value in the passed address is changed within function definition, the value of actual variable also changed.WAP to illustrarate user passing pointer to function

92

Page 93: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<stdio.h>#include<conio.h>void mul(int *m){*m=*m+10;}void main(){ int marks;clrscr();printf("the actual marks is"); scanf("%d", &marks);mul(&marks); printf("\n the numbers are %d", marks);getch();}

WAP to convert upper case case letter into lower case vice versa#include<stdio.h>#include<conio.h>void conversion(char *);void main(){ char input;clrscr();printf("Enter character\n"); scanf("%c", &input);conversion(&input);printf("\nthe correcsponding character %c",input);getch();}void conversion(char *c){if(*c>=97&&*c<=122) *c=*c-32;else if(*c>=65&&*c<=90) *c=*c+32;}

Structure and UnionA structure is a collection of variable under a single name. The variables may be of different type and

each has a name which is used to select it form structure. The variables are called member of structure. A structure is a convenient way of grouping several pieces of related information together. A structure combine several pieces of related information together. A structure is new name of heterogenous data type or user defined data type. It may use other structures arrays or pointers as some of its members in a single unit.

An array can be used only to represent a group of data items that must be same type. Such as int, float. However if we want to represents collection of data items of different type using same name. Array cannot do so. In this situation, structure is used, which is method for packing data of different items. For example name roll, fees marks are related information of student. To store information about a student we would require to store the name of student which is array of characters, roll of student which is int, fees of student is in float similarly marks of student may be float and character of students may be m or f. there attrtribues of students are grouped together into single entity, student. Here student is known as structure which organized different data items in more meaningful way.Defining a structure: Syntax: strut student name {

data type variable;date type variable; ;……; };Once structure name is declared as new data type then, variables of that type can be declared as strut

student name variable. Example: strut student { char name []; int roll; float marks; };

Here, student is structure name and its members are name, roll marks. The student is new data type and variable of structure student can be declared as : struct student st;

Here structure st is variable of type student. The multiple variables are declared as std2, std3, std3.Each variables of structure has its own copy of member variables. The member variables are accessed using dot (.) operator. For example std1.name std1.roll, std1.marks. There are some stypes to declare structure.

93

struct structure name {int marks;char name [45];float fees;char remarks;} str1, std2, std3;

strut {char name [45];float fees;char remarks;} std1, std2, std3;

strut book {char title [34];char author [45];int page;float price ;}b1, b2;

date {struct data {int day;int month;int year ;} dateofbirth;

strut employees { int id;char name [45]; float salary;float allowance;char sex;into age ;} employee;

strut department {int id;char name [23];char department [20]into noof staff; };

Page 94: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal

Structure InitializationLike standard data type, the members of a structure variable can be initialized. The values to be

initialized must appear in order as in the definition of structure within brace and separated by comma. C does not allow initialization of individual structure member within its definition syntax: strut structure name= {variable, variable, variable, variable};

strut student { char name []; int roll;float marks ;};the variable of this type can be declared as : strut student st= {“Yagya”, 100, 34.54}; orIs equivalent to strut student st; st.name=”Ram”, st. Marks=34.54;st.roll=45;

Processing a Structure and Accessing Member of StructureThe member of structure is usually processed individually, as separate entity. Therefore we must be able to access individual structure members. A structure member can be accessed by using period (.) operator. There syntax structure variable as : structure variable. member (std.name,std.id,std.marks).Precedence of Dot Operator (.)The dot operator is member of the highest precedence group and associates form left to right. Since it is an operator of highest precedence, dot operator will take first precede over various arithmetic, relational and logical assignment and unary operator. Thus ++st .marks is equivalent to ++(st. marks), implying that the dot operators acts first and then unary operator.Create structure name student that has name, roll, marks and remarks as members assume appropriate data types and size of member. Write program using structure to read and display data entered by user.

#include<stdio.h>#include<conio.h># include<string.h>void main(){ struct student{char name[30];int roll;float marks;char remarks;};struct student s; clrscr();printf("enter name");gets(s.name);printf("\nEnter roll");scanf("%d",&s.roll);printf("\nEnter marks");scanf("%f",&s.marks);printf("\nEnter character m or f\n");s.remarks=getche();printf("name of student roll marks and remarks as\n");printf("\n%s\t %d\t%.2f \t%c", s.name,s.roll,s.marks,s.remarks);getch();}

Structure Elements are Stored: The elements of structure are always stored in contiguous memory locations. A structure variable reverses number of bytes equal to sum of bytes needs to each of its members. For example int following structure students variable st takes 7 bytes in members are its member’s variable( roll, 2 bytes marks needs 4 bytes and remarks need 1 byte.)WAP to illustrate memory locations of each elements of structure

#include<stdio.h>#include<conio.h># include<string.h>void main(){ struct student{int roll;float marks;char remarks;};struct student s={200,60.78,'P'}; clrscr();printf("\naddress of roll is%u",&s.roll);printf("\naddress of makrs is%u",&s.marks);printf("\naddress of remarks is%u",&s.remarks);getch();}

94

strut book {char title [34];char author [45];int page;float price ;}b1, b2;

strut employees { int id;char name [45]; float salary;float allowance;char sex;into age ;} employee;

Page 95: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

Person

Name

DateofBirth

Id

Salary

Day

Month

Year

strut date {int day; int month; int year ;};

struct person {char name [40];int id;struct date date;float salary; }p;

BE Computer Programming in C Yagya RimalArray of StructureLike array of int, float or char type there may be array of structure. In this case, the array will have individual structure as its elements. In our previous structure example. If we want to keep record of 50 students, we have to make 50 structure variables like std1, std2. But this technique is not good. At this situation we can use array of structure to store records of 50 students. Similarly to declaring structure variable an array of structure can be declared in two ways: strut employee {

char name [];int id;float salary ;} emp [10];

Create a structure named student that has name, roll, marks and marks as members. Assume appropriate types and size of member. Use this structure to read and display records of 5 students.

#include<stdio.h>#include<conio.h># include<string.h>void main(){struct student{char name[23];int roll;float marks;char remarks;};struct student s[3]; int i;for(i=0;i<3;i++){printf("Enter %d information",i+1);printf("name:\t");scanf("%s",s[i].name);printf("roll:\t");scanf("%d",&s[i].roll);printf("marks:\t");scanf("%f",&s[i].marks);printf("remarks:\t");scanf("%s",&s[i].remarks);s[i].remarks=getche(); }for(i=0;i<3;i++){ printf("%s\t%d\t%.f\t%c\n", s[i].name,s[i].roll,s[i].marks,s[i].remarks);}getch();}

Initialization Array of StructureWe can initialize array of structure in same way as a single structure. This is illustrated as

strut book {char name [30];int page;float price; } ;strut book b[5]={“”,45,45.3,””,30,50.90,””,45,80.89,””,230,809.89,””,67,68.34};struct book[5] dimension means it reserve five location for each name, int page and float price.Structure within Another Structure/Nested Structure

One structure can be nested within another structure in C. In other words the individual members of structure can be nested other on structure as well. Let us consider structure date which has member day, month and year. The date structure can be nested within another structure say person. Structure date is member of another structure person. This can be done as follows.

This can be nested within another structure as its member.Here, structure person contain member date which is itself a structure with there members. The members within structure date are accessed as big structure variabel as p.date.day, p.date.month, p.date.year but the members within person suture are accessed as usual as big structure .name p.name,p.id,p.ssalary.

95

Page 96: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalCreate a structure named date that had day, month, and year as its members include this structure as member in another structure named employee which has name, id and salary as other members. Use this structure to read and display employee name id and date of birth and salary.

#include<stdio.h>#include<conio.h>void main(){struct date{ int day;int month;int year;};struct employee{char name[23]; int id; struct date sdate;float salary;} emp;printf("Enter name of employee\t");printf("name:\t");scanf("%s",emp.name); printf("id:\t");scanf("%d",&emp.id);printf("date of birth Day\t");scanf("%d",&emp.sdate.day);printf("month of birth\t");scanf("%d",&emp.sdate.month);printf("date of birth year\t");scanf("%d",&emp.sdate.year);printf("salary:\t");scanf("%f",&emp.salary);printf("the name and information are as\n");

printf("%s\t%d\t%d\t%d\t%d\%f\t",emp.name,emp.id,emp.sdate.day,emp.sdate.month,emp.sdate.year,emp.salary); getch();}Here, date is structure having day, month, and year that is also member of employee structure having object emp.

Pointer to Structure: Pointer can be used with structure to store address of structure type variable; we can define a structure type pointer variable as normal way. Let us consider a structure book that has members name, page and price. It can be declared as struct book{ char name[45];

int page; float price;}; struct book b; this is normal variable;struct book *bp; here bp is pointer variable of structure book.

To use structure members through pointer memory must be allocated for a structure by using function call malloc() or by adding declaration and assignment as given bp=&b;An individual structure member can be accessed in terms of its corresponding pointer variable by writing variable-> member. Here -> is called arrow operator and there must be structure on left side of this operator.

b.name or bp->name or (*bp).nameb.page or bp->page or (*bp).pageb.price or bp->price or (*bp).price

WAP book which has name, page and price as member variables read name of book its page number and price. Finally display their members’ value use pointer to structure instead of structure itself to access member variables.

#include<stdio.h>#include<conio.h>void main(){struct book{ char name[34]; int page; float price;};struct book b,*bptr;clrscr();printf("Enter name of book"); gets(b.name);printf("\nEnter no fof page"); scanf("%d",&b.page);printf("\nEnter price"); scanf("%f",&b.price);bptr=&b;printf("\nUsing arrow operator\n");printf("\n%s\t%d\t%f",bptr->name,bptr->page,bptr->price);printf("\nUsing * operator\n");printf("\n%s\t%d\t%f",(*bptr).name,(*bptr).page,(*bptr).price);getch(); }

96

Page 97: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalIn this example, first st we give data to book structure variable b then that value are passsed to pointer variable bptr the pointer structure can be accesssed by uisng -> object representtive variable.Function and Structure: Structure variable can also be passed to a function we may either pass individual structure elements or the entire structure.Passing Structure Members to Functions: A structure member can be treated just as normal variable of structure type. For example, integer structure variable can be treated just as integer. Thus structure members can be passed to function like ordinary variables.WAP to illustrate passing structure member to functions

#include<stdio.h>#include<conio.h>void display( char name[],int id,float sal){printf("\n name\t id\t salary\n");printf("....................") ;printf("\n%s\t%d\t%.f",name,id,sal); }void main(){struct employee{ char name[23]; int id; float salary;};struct employee emp; clrscr();printf("Employee name/t");scanf("%s",emp.name);printf("employee id\t");scanf("%d",&emp.id);printf("enter salary");scanf("%f",&emp.salary);printf("\n the entered informationm of employee");display(emp.name,emp.id,emp.salary);/* passsing structure values ot functiongetch();}

Passing Whole Structure to Functions: It is possible to send entire structures functions as arguments in the functions call structure variable is treated as any ordinary variable.WAP to illustrate passing whole structure to function

#include<stdio.h>#include<conio.h>struct employee{ char name[23]; int id; float salary;};void display( struct employee e){printf("\n name\t id\t salary\n");printf("....................") ;printf("\n%s\t%d\t%.f",e.name,e.id,e.salary); }void main(){struct employee emp;clrscr();printf("Employee name\t");scanf("%s",emp.name);printf("employee id\t");scanf("%d",&emp.id);printf("enter salary");scanf("%f",&emp.salary);printf("\n the entered informationm of employee");display(emp);

getch();}Here, display emp is the function having structure as arguments is passed whole structure to function.Passing Structure Pointer to Functions: In this case the structure pointer is passed to function. If the pointer to a structure is passed as an argument to a function, then any changes that are made in the function are visible in the caller.WAP to illustrate passing structure pointer to function.

#include<stdio.h>#include<conio.h>struct employee{ char name[23]; int id; float salary;};void display( struct employee e){printf("\n name\t id\t salary\n");printf("....................") ;

97

Page 98: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n%s\t%d\t%.f",e.name,e.id,e.salary); }void increasesalary(struct employee*ee){ee->salary=ee->salary+1000;}void main(){ struct employee emp; clrscr();printf("Employee name\t");scanf("%s",emp.name);printf("employee id\t");scanf("%d",&emp.id);printf("enter salary");scanf("%f",&emp.salary);printf("\n the entered informationm of employee\n");increasesalary(&emp);display(emp);getch();}

here, increasesalary(struct employee*ee) is the function that hold structure of pointer is passed in main method using 7emp object of structure after increase salary by 1000, display function is used to display the content.Passing Array of Structure to Function: Passing an array of structure to function involves same syntax and properties as passing array to a function. The passing is done using a pointer array structure in function if, any changes made in function to structure to the structure also visible in caller.Create a structure student that has name roll marks and remarks as members. Assume appropriate types and size of members use this structure to read and display records of 4 students. Create two functions read information and display information’s. Pass array of structure to these functions.

#include<stdio.h>#include<conio.h>#define size 4int i;struct student{ char name[23]; int roll; float marks;char remarks;};void display( struct student st[]){printf("\n name\t id\t \t marks\t salary\n");printf("....................::::;;");for(i=0;i<size;i++)printf("\n%s\t%d\t%.f\t%c",st[i].name,st[i].roll,st[i].marks,st[i].remarks);}void read(struct student stu[]){ float temp;for(i=0;i<size;i++){printf("\nEnter studentsdetail %d\t",i+1);printf("name\t");scanf("%s",stu[i].name);printf("roll\t");scanf("%d",&stu[i].roll);printf("\nmarks\t");scanf("%f",&temp);stu[i].marks=temp;printf("remarks\t");stu[i].remarks=getche();}}void main(){struct student s[size]; float temp; clrscr();printf("student information\t");read(s);printf("The details of inforatin are\t");display(s);getch();}

Solved Example:WAP to read name, roll and marks of 6 student using array of structure. Display the name and roll of those students whose m arks is grater that 50.

#include<stdio.h>#include<conio.h>#define size 3void main(){struct student{ char name[34];int roll; int marks;};

98

Page 99: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalstruct student s[size]; int i; clrscr();for(i=0;i<size;i++){printf("student information%d\t",i+1);printf("name\t");scanf("%s",s[i].name);printf("roll\t");scanf("%d",&s[i].roll);printf("makes\t");scanf("%d",&s[i].marks);}printf("the grater>50 marks scorrer are ;;;;;;;;;;;;\n");for(i=0;i<size;i++){if(s[i].marks>50)printf("\n%s\t\t%d\t\t%d",s[i].name,s[i].roll,s[i].marks);}getch();}

WAP to read name address and salary of 4 employee using array of structure. Display information of each employee in ascending aoprder of their name.

#include<stdio.h>#include<conio.h>#include<string.h>#define size 3void main(){struct employee{ char name[34];char address[23];float salary;};struct employee e[size],temp; int i,j;float sal; clrscr();for(i=0;i<size;i++){printf("student information%d\t",i+1);printf("name\t");scanf("%s",e[i].name);printf("address\t");scanf("%s",e[i].address);printf("salary\t");scanf("%f",&sal);e[i].salary=sal;}for(i=0;i<size-1;i++){ for(j=i+1;j<size;j++){if(strcmp(e[i].name,e[j].name)>0){temp=e[i];e[i]=e[j];e[j]=temp;}}}printf("\n list of ascending aorder are \n");for(i=0;i<size;i++)printf("%s\t\t%s\t\t%.2f\n",e[i].name,e[i].address,e[i].salary;getch();}

Create s structure named book which has members name, page and price. Write a program to read name, no of page, and price of 5 books using array of structure. Display the name, no of pages and price of most expensive book. Having highest price.

#include<stdio.h>#include<conio.h>#include<string.h>#define size 3void main(){struct book{ char name[34];int page;float price;};struct book b[size],temp; int i,j;float pt;clrscr();for(i=0;i<size;i++){printf("book information%d\t",i+1);printf("name\t");scanf("%s",b[i].name);printf("page\t");scanf("%d",&b[i].page);printf("price\n");scanf("%f",&pt);b[i].price=pt;fflush(stdin);}for(i=0;i<size-1;i++){ for(j=i+1;j<size;j++){if(b[i].price<b[j].price){temp=b[i];b[i]=b[j];

99

Page 100: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalb[j]=temp;}}}printf("\n the highet book price is: \n");printf("%s\t\t%d\t\t%.2f\n",b[0].name,b[0].page,b[0].price);getch();}

Create structure named employee which has name address and salary as members. Write a program to name, address and salary of 10 employee using array of stricture. Display name of employee which has third highest salary.

#include<stdio.h>#include<conio.h>#include<string.h>#define size 5void main(){struct employee{ char name[34];char address[23];float salary;};struct employee e[size],temp; int i,j;float sal; clrscr();for(i=0;i<size;i++){printf("empoyee information%d\t",i+1);printf("name\t");scanf("%s",e[i].name);printf("address\t");scanf("%s",e[i].address);printf("salary\t");scanf("%f",&sal);e[i].salary=sal;}for(i=0;i<size-1;i++){ for(j=i+1;j<size;j++){if(e[i].salary<e[j].salary){temp=e[i];e[i]=e[j];e[j]=temp;}}}printf("\n list of ascending aorder are \n");

printf("%s\t\t%s\t\t%.2f\n",e[2].name,e[2].address,e[2].salary);getch();}

UnionUnion are similar to structure its syntax and use. It also contains members whose individual data types

may differ from one another (heterogenous data type). The distinction is that all members within union share the same storage area of computer memory where as each member within a structure is assigned its own unique storage. Thus unions are used to save memory space. Since same memory is shared by all members. One variable can reside into another memory at a time. When another variable is set into memory of previous involving multiple members whose value need to be assigned to all members at the same time. Therefore although union may contain many members of different types it can handled only one big member at a time. The compiler allocates a piece of storage that is large enough to hold largest variable type in union.

union student { int roll; float marks ;};here union student allocates float data type within it int is reside on.

Crate union student that has roll, marks as members .assigned some values to these members one at a time and display the results one at a time.

#include<stdio.h>#include<conio.h>void main(){union student{ char name[23]; int roll; float marks;};union student st;st.roll=45;printf("\n%d",st.roll);st.marks=90;printf("\n%f",st.marks);getch();}

Structure UnionEach member within a structure is assigned its All members within union share the same

100

Page 101: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalown unique storage. It takes more memory than union

storage area of computer memory. It takes less memory than structure

The amount of memory required to storage a structure is the sum of the size of all members.

The amount of memory required to store an union is same as member that occupies largest memory.

All the structure members can be assessed at any point of time.

Only one member of union can be accessed at any given time.

Structure is declared assruct student{ char name[56];int roll;float marks;} st;

union student{char name[45];int roll;float marks;} st;

DATA FILESThe input /output function printf() scanf() getchar(),puthar() are known as console oriented i/o functions which always use keyboard is input device and monitor are out devices . While using these library functions the entire data is lost when either program is terminated or the computer is turned off. Again it becomes boared and time consuming to handle large volume of data through keyboard. It takes a lot of time to enter entire data. These problems of data files in which data can be stored memory than read/write whenever necessary, without destroying data.A file is place on disk where a group of related data are stored. The data file allows us to store information permanently and to access and alter these information when necessary. Programming language C has various library functions for creating and processing data files. Mainly, there are two types of data files one is stream oriented high-level and low level data files. In high-level data files functions do their own buffer management where as the programmer should do it explicitly in the case of system oriented level files.The standard data files are again subdivided into text files and binary files. The test files consists consecutive characters by characters be interoperated as individual data item. The binary file origination data into blocks containing continues byte of information. For each binary and text files, there are a number of formatted and unformatted library functions.Opening and Closing a Files: Before a program write to a file or read form a file, the program must be open. Opening a file establishes a link between program and operating system. This provides the operating system the name of the file and mode in which file is to be opend. While working with high level data file we need buffer are where information is stored temporarily in course of transferring data between computer memory to data file. The buffer area is established as: FILE * ptr variable;Here, FILE is special structure declared in header stdio.h . Each file we opened as its own file is special structure that contains information about file being used. Such as its current size, its location in memory etc. The ptr variable is a pointer type. That stores beginning address and buffer area allocated after a file opened. Thus pointer contains all the information about file and its use and communication link between system and the program. A data file is opened syntax as: ptr variable=open (filename, file mode);The associate file name with buffer area and specifics how data files will be open in specified mode. The function open () returns a pointer to beginning of buffer area associated with file. A file NULL value is returned if file cannot be opened due to some reasons. After opening a file we can processes data files as required. Finally data file must be closed. The closing a file ensures that all outstanding information associated with file is flushed out form buffer and links to file are broken. It also prevent any accidental misuse of file. The file is closed using other library functions fclose() as fclose(ptr variable);File Opening ModesThe file opening mode specifies way in which a file should be opened. In other words, it specifies the purpose of openings a file. There are six modes.

a) “r” read mode: This opens existing files for reading mode only. It searches specified file. If file exists it loads it into memory and sets up a pointer to first character in it. If file does not exist, it returns NULL. The possible operation reading from the file only.

101

Page 102: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalb) “w” write mode: This mode of file opens a file for writing only. It searches specified file, If file

already exist, the contents are overwritten. If file does not exist new file is crated. It returns NULL, if it is unable to open file in write mode. The possible operation is only writing to file.

c) “a” append mode: It opens an existing file for appending. It searches specified file, If specified exists it, loads into memory and setup a pointer that points last character in it. If file does not exist, new file is created. It returns NULL. if unable to open file. The possible operation is adding new content at end of file.

d) “r+” read+write mode: It opens existing file for reading and writing. It searches specified file. If file exists it loads into memory and a pointer first character. It will returns NULl, if the file does not pointer exist. The possible operations are reading existing contents writing contents, modifying existing contents can be done in this mode.

e) “w+” read+write mode: It opens file for reading and writing. If specified file exists. It contents are destroyed. If file does not exist t new file is created. It returns NULL. If unable to open file. The possible operations are writing new contents, reading them back and modifying contents of the file.

f) “a+” append and read mode: It opens an existing file for both reading and appending. A file will be created it specified file does not exist. The possible operations are reading existing contents appending new contents to end of file but it cannot modify existing content.

Library Functions for Reading FileString Input /Output: fgets(): This function is used to read from file. syntax: fgets (string,int, fptr variable)

a. fputs ():It is used to write a string to the file. syntax : fputs(string, file ptr variable);Create a file text.txt and write some text ”Hello student” to the file

#include<stdio.h>#include<conio.h>void main(){ FILE *fptr; clrscr();fptr=fopen("c:\\text.txt","w");if(fptr==NULL){ printf("\n File cannot be created");exit();}else printf("Hello student \t be prepare for final exam");fputs("welcome to the c programming",fptr);fclose(fptr);}

WAP to open the file “text.txt” created in above.#include<stdio.h>#include<conio.h>void main(){FILE *fptr; char s[100];clrscr();fptr=fopen("c:\\test.txt","r");if(fptr==NULL){ printf("\n File cannot be opend");exit();}fgets(s,100,fptr);printf("\nThe text form file is\t%s",s);fclose(fptr); getch();}

Character Input/OutputUsing these functions, data can be read form file or written to file one character at a time.

a. fgets(): This function is used to read a character form a file. syntax char vari= fgets(file variable);b. fputs() : This function is used to write a character form a file. Syntax: fputc(char or char variable, fle

variable);WAP to create file and write some text to it writing one character at t time using fputs() function. The program should write until user hits entered key from user.

#include<stdio.h>#include<conio.h>void main(){FILE *fptr; char c; char filename[20];clrscr();printf("Enter the name of file:\t");scanf("%s",&filename);fptr=fopen(filename,"w");if(fptr==NULL){ printf("\n File cannot be created");exit(0);}

102

Page 103: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalprintf("\n Enter text then hit enter key\n");fflush(stdin);while((c=getchar())!='\n'){fputc(c,fptr); }fclose(fptr);}

WAP to open the file in example above read its contents one char at time and display int to the screen#include<stdio.h>#include<conio.h>void main(){ FILE *fptr;char c;char filename[20];clrscr();printf("Enter the name of file:\t");scanf("%s",&filename);fptr=fopen(filename,"r");if(fptr==NULL){printf("\n File cannot be created");exit(0);}printf("\n The content of file is:\n");while((c=fgetc(fptr))!=EOF){fputchar(c); }fclose(fptr);getche();}

WAP to append some text to a certain file take file name form user.#include<stdio.h>#include<conio.h>void main(){FILE *f; char c, filename[20];clrscr();printf("Enter the file which you want to append:\t");gets(filename); f=fopen(filename,"a");if(f==NULL){printf("\n File cannot be opened");}printf("\n Enter the text to be added:\n");while((c=getchar())!='\n'){fputc(c,f); } fclose(f);}

Create a program which asks file name form user and create it to write certain lines of text. It should write until user hits enter key at the beginning of line read the content of file and display to the screen.

#include<stdio.h>#include<conio.h>#include<string.h>void main(){FILE *fptr; char s[200], filename[20],c;clrscr();printf("Enter the filename:\t"); gets(filename);fptr=fopen(filename,"w");if(fptr==NULL){printf("\n File cannot be created");exit(0); }printf("\n Start writing:\n");fflush(stdin);while((c=getchar())!='\n'){fputc(c,fptr);} rewind(fptr);printf("Reading form the file.....");printf("Enter the name of file:\t"); scanf("%s",&filename);fptr=fopen(filename,"r");printf("\n The content of file is:\n");while((c=fgetc(fptr))!=EOF){putchar(c); }fclose(fptr); getche();}

WAP that opens a file and copies all its contents to another file. Take sources and destination file form user.

103

Page 104: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<stdio.h> #include<conio.h> #include<string.h>void main(){FILE *fsource,*fdesti;char ch, source[20], desti[20]; clrscr();printf("\nEnter the souce filename:\t"); gets(source);printf("Enter the desitnation file\n");gets(desti);fsource=fopen(source,"r");if(fsource==NULL){ printf("\n File cannot be opened");exit(); }fdesti=fopen(desti,"w");if(fdesti==NULL){ printf("\ndestination file cot be created\n");exit();}while((ch=fgetc(fsource))!=EOF){fputc(ch,fdesti); }printf("success....."); fclose(fsource); fclose(fdesti);getch();}

Formatted I/O: These functions are used to read/write number, character or string form file in format as user requirement.

a. fprint() : This function is formatted output function, which is used to write some integer, float, char or string to specific file. syntax: fprint(file variable, “control string” list variable);b. fscanf(): This function is formatted input function which is used to read some integer, float, char or string form a file. fscanf(file variable," control string”, &list variables);

WAP to create a file named student.txt in d drive and write name and roll address and marks of student to this file.

#include<stdio.h>#include<conio.h>#include<string.h>void main(){FILE *f; char name[20],address[20]; int roll; float marks; clrscr();f=fopen("c:\\student.txt","a");if(f==NULL){ printf("\n file cannot created");exit();}printf("\nEnter name of student");gets(name);printf("\nEnter roll");scanf("%d",&roll);fflush(stdin);printf("\nEnter address");gets(address);printf("\nEnter marks");scanf("%f",&marks);printf("\n Data is being written in file ");fprintf(f,"\nName=%s\nRoll=%d\nAddress=%s\nMarks=%.2f",name,roll,address,marks);fclose(f); getch();}

WAP to write even numbers between 10 to 50 to file named even number in d: drive#include<stdio.h>#include<conio.h>#include<string.h>void main(){FILE *f; int i; clrscr();f=fopen("D:\\even.txt","w");if(f==NULL){printf("\nFile can bo be created");exit();}else printf("File has been successfully ceated");fprintf(f,"The even numbers are\n");for(i=0;i<=50;i++){ if(i%2==0)fprintf(f,"%d\n",i); }fclose(f); getch();}

Create a program to create file and write the natural numbers 1 to 20 this file then read the numbers form the file to display the twice of the stored numbers

104

Page 105: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include<stdio.h>#include<conio.h>#include<string.h>void main(){FILE *f;int i,numfrom; clrscr();f=fopen("c:\\puja.txt","w+");if(f==NULL){printf("\nFile can bo be created");exit();}for(i=1;i<=20;i++){ fprintf(f,"%d\n",i); }rewind(f);printf("\nThe twice of natural file are\n");for(i=1;i<=20;i++){fscanf(f,"%d",&numfrom);numfrom=2*numfrom;printf("%d\t",numfrom);}fclose(f);getch();}

WAP to open a file named inventory .text and store in the following data in following formatProduct name Quantity RateApple 3 43Orange 5 89Banana 10 45

#include<stdio.h>#include<conio.h>void main(){FILE *f; char item[20];int qty,rate,i; clrscr();f=fopen("D:\\inventory.txt","w");if(f==NULL){printf("\nFile can not be created");exit();}for(i=0;i<5;i++){printf("\nEnter priduct name \t qutntity\t and rate\n");scanf("%s",item);scanf("%d%d",&qty,&rate);fprintf(f,"%s\t%d\t%d\n",item,qty,rate);}fclose(f);getch();}

End of File (EOF) : The EOF represents End of File and determines whether the file associated with a file handle has reached end of file or not . This unique integer is sent to program by operating system and is defined in a header file stdio.h . While creating a file, operating system transmits EOF signal when it finds last character of file. In text mode, a special character 1A hex decimal is inserted after the last character in the file. This character is used to indicate EOF. If character last encountered an any pint in file, the read function will return EOF signal to program. An attempt to read after EOF might either case the program to terminate with errors or result in a infinite loop situations. Thus the last point of file is detected using EOF while reading data form file. Without this mark we cannot detect last character at the file such that is difficultly to find up to what time character is to be read while reading data from the file.

WAP to read the content of file student.txt stored in c:/ drive use EOF to detect the end of file.#include<stdio.h>#include<conio.h>void main(){FILE *f;char c; clrscr();f=fopen("c:\\student.txt","r");if(f==NULL){ printf("\nFile can bo be created"); }while((c=fgetc(f))!=EOF){printf("%c",c);}fclose(f);getch();}

Binary Data Files: The binary data files organize data into block containing continuous bytes of information. A binary file is file of any length that holds bytes with variables in range 0 to 0xff (0 to 225).These bytes have other meaning like value of 13 means, carriage return, 10 means, line feed, 26 means, end of file. In modern terms we recognized binary file as stream of bytes file opening mode of text file is appended by a character.

1. "r" is replaced by rb105

Page 106: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal2. "w" is replaced by wb3. "a" is replaced by ab4. "r+" is replaced by r+b5. "w "+ is replaced by w+b6. "a+" is replaced by a+b;7. fptr=fopen(“text, ‘’wb”);

The default mode is text mode. Thus when simple r is written as mode of opening, this is assumed as text mode. We can write "rb" in place of r and file text mode of file. This syntax of all above mode in the case of binary mode is similar to the previous.WAP to write some text “welcome to pokhara” to a data file in binary mode read its contents and display.

#include<stdio.h>#include<conio.h>void main(){FILE *f;char c; clrscr();f=fopen("c:\\puja.txt","r");if(f==NULL){ printf("\nFile can bo be created"); }while((c=fgetc(f))!=EOF){printf("%c",c);}fclose(f);getch();}

Different Between Binary Mode and Text Mode There are mainly three difference between binary and text mode, they are as follows

1. In text mode, a special character EOF whose ASCII is 1A hex (26 in decimal) is inserted after last character in file. The binary mode files keep track of end from numbers present in directory entry of file ranges from 0 to 255. In this mode numbers of characters presents in directory entry of the file its mode. In this mode, numbers are stored in binary format. Therefore a number stored in memory happens to be 1A hex.(bytes have other means). Therefore a number stored in memory may be 1A but in text mode it represents the end of file.2. In text mode, numbers are stored assuring of character where as in binary format they are stored the same way as hey are stored in computer main memory.the number 1234 occupies 2 bytes but it occupies 4 bytes in text mode because 1 character for one bytes in binary mode. If occupies 2 bytes. The solution of file opens to fread() function and replcaced fprintf() and fscanf() functions.3. The end of line single character, the new line charcter is marked by ‘\n’ with ASCII value 10 in decimal whereas in dos e end of line is marked by two characters, the carriage return CR with ASCII value 13 in decimal and line feed (LF) with ASCII value 10 in decimal which is same as of c’s new line character. In text mode a new line character is automatically converted into carriage return combination before being written to the disk of file. Like the carriage return line feed combination on the disk is converted into a new line when the file is read by C program. However these conversions don't take place in this case of binary character. Similarly & while reading the combination of CR/LF will be treated as two separate character as r and n character.Record Input/OutputIt is clear that character i/o and string i/o permits reading and writing of character data only formatted i/o permits reading and writing of characters and number. However the numbers are stored as sequential of character not in memory as result they take a lot of disk space in addition these methods provides no direct way to read write complex data types such array and structures. Array and structure can be handled by reading and writing each array element one at time but this approach is very inefficient.The solution of these problems is record i/o also known as block i/o record i/o writes number to file in binary format so that integer are stored in 2 bytes are stored in 4 bytes with single precisions floating point numbers are stored in 4 bytes the same format used to store number data in memory record i/o permits reading and writing of data once. This process is not limited to single character or string of the few values in fact arrays structure array of structure can be read and rewritten as single unit.The function fwrite() is used for record output while fread() is used for record input. syntax

fwrite (&ptr,size of array, number of structure array);106

Page 107: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfread( &ptr, sixe of array, number of structure array, fptr); Where ptr is address of an array

size of integer is an value that shows size of structureNumber of structure is an integer value that shows size of arraysfptr is a file pointer of an file opened in binary mode.WAP that ask the for 10 numbers and store them in an array. Write this array to a file.

#include<stdio.h>#include<conio.h> #include<string.h>void main(){FILE *f; int num[10],i; clrscr();f=fopen("c:\\pp.txt","wb");if(f==NULL){printf("\n File can bo be created"); }printf("Enter 10 numbers");for(i=0;i<10;i++)scanf("%d",&num[i]);printf("The array of file....");for(i=0;i<10;i++)fprintf(f,"array %d\t is \t%d",i,nums[i]);fclose(f);getch();}#include<stdio.h>#include<conio.h>void main(){ FILE *f;int num[10],i;clrscr();f=fopen("c:\\p0p.txt","wb");if(f==NULL){ printf("\n File can bo be created"); }printf("Enter 10 numbers");for(i=0;i<10;i++)scanf("%d",&num[i]);printf("The array of file....");for(i=0;i<10;i++)fprintf(f,"%d",num[i]);fclose(f);getch();}

WAP that opens file numx.txt created in above program an array stored in the display to screenCreated a structure named employee having member emp name , age sn salary use this stricture to read the name , age and salary of employee and write entered information to a file data in d:/ drive

#include <stdio.h>#include<conio.h>void main(){struct emp { char name[23];int age;float salary;};struct emp em ; FILE *fptr; clrscr(); fptr= fopen("c:\\TxT.txt", "wb");if(fptr==NULL) {printf("Cannot open output file.\n"); exit(0);}printf("Enter name\t");scanf("%s",em.name);printf("Enter age\t");scanf("%d",&em.age);printf("Enter salary\t");scanf("%d",&em.salary);printf("writing to this file");fprintf(fptr,"name=%s\t age=%d\tsalary=%d\t",em.name,em.age,em.salary); fclose(fptr); /* close file */getch();}

DIRECT /RANDOM AccessThe reading and writing in all previous programs was in sequential. While reading data form a file, data items are read from beginning of file in sequence until end of file. Similarly while writing data to a file data items are placed one after the other in sequence. We can access a particular data items place in any location without starting beginning. Such type of access to a data items is called direct or random access.For random access in a file, knowledge of file pointer is necessary. A file pointer to particular bytes in a file. While opening a file in write mode, the file pointer is at beginning of file. Every time when we write to a file, file pointer moves to the end of data items so that writing can conscious from that point while

107

Page 108: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalopening a file in read mode file pointer is at the beginning file. After reading data items the file pointer moves to the beginning of next data item, which can subsquentltly are read. However if file is io end in aped mode, then file pointer will be positioned at end of existing file, so that new data items can be written form there onwards. Therefore we can read any data items form a file or write a file randomly if we would be successful to move this file pointer as our requirement. Important functions used in random access area as: fseek(): It sets the file pointer associate with a stream file handle to a new position. This function is used to move he file pointer to different positions. Syntax:fseek (fpt, offset, mode); Whererewind (): One way of positioning the file pointer to the beginning of the file to close the file and them reopen it again . This same stack can accomplished without closing ah file using rewind() function . This function positions hat file pointer in the beginning of the file. The use of functions rewind() is equivalent or using fssek()fptr,0,seek-set )ftell(): This function determines current location of file pointer . It returns integer values syntax:ftell( fptr)Where fptr is file pointer for the currently opened file.

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ struct employee{ char name[23]; int age; float salary;};struct employee emp; FILE *f; char yes,name[23];int data=0; clrscr();f=fopen("c:\\pop.txt","w+b");if(f==NULL){ printf("\n File can bo be created"); }do{ printf("Employee name\t");scanf("%s",&emp.name);printf("Employee age\t");scanf("%d",&emp.age);printf("Employee salary\t");scanf("%f",&emp.salary);fwrite(&emp,sizeof(emp),1,f);printf("do you want to anoter if Y");fflush(stdin);yes=getchar();}while((yes=='y')||(yes=='Y'));printf("Enter the employee which search");fflush(stdin);gets(name);rewind(f);while(fread(&emp,sizeof(emp),1,f)==1){if(strcmp(emp.name,name)==0) { data=1;printf("name\tage\tsalary\n");printf("%s\t%d\t%f",emp.name,emp.age,emp.salary);}}if(data==0){printf("no mached found"); }getch();}#include<stdio.h>#include<conio.h>#include<string.h>void main(){ struct employee{ char name[23]; int age; float salary;};struct employee emp;FILE *f;char yes,name[23]; int data=0;int record=0; clrscr();f=fopen("c:\\pop.txt","r+b");if(f==NULL){ printf("\n File can bo be created"); }printf("Enter the name of employee wo you modifyed\t"); gets(name);while(fread(&emp,sizeof(emp),1,f)==1){if(strcmp(emp.name,name)==0){data=1;printf("old record is\n");printf("name\t\tage\tsalary\n");printf("%s\t%d\t%f",emp.name,emp.age,emp.salary);printf("Enteer new name age and salary\n");scanf("%s%d%d",&emp.name,&emp.age,&emp.salary);fseek(f,sizeof(emp)*record,SEEK_SET);

108

Page 109: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalfprintf("%s%d%f",&emp.name,emp.age,emp.salary);printf("\nthe records succesfully modified\n");}record++;}if(data==0)printf("\nNOt matched found");fclose(f);getch();}Graphics

There are two mode of standard output devices. Text and graphic modes. In previous chapters we just discussed in text mode only. The PCscreen is normally setup to display 25 lines of text with 80 character perlines. We can no any shape and size of characters displayed on the screen. ASCII characters displayed on screen are predefined by its video adapter. The size and shapes of characters are controlled by vedio adapter. and hardware. While displaying characters tiny dots on the screen called pixel is used. The pixels are even present in text mode as they are used to form characters that appear on screen. The graphic mode is different that they are predefined pattern of pixels. It provides the ability to manipulate the individual pixel. We can display any text charts rectangles circles histogram. To work with graphic C provides library functions graphics .h is used.Pixel: A pixel is a single point dot having some x and y cordinate representation on screen and graphics image. Graphic monitors display pictures by dividing display screen into thousands of pixel are arranged in row and columns. The pixels are so called together to formed the images. Therefore the more the pixel the better the image quality. The computer screen is two dimensional pixel on screen has some locations illustrate by x and y values where x is horizontal and y vertical offset from top. So a locations x=0 and y=0 is top left corner of computer screen. Resolutions: The numbers of pixel is used on screen is called resolution. There are fixed number of wows and each row contains certain numbers of pixels. The frequently used resolutions supported by most adaptors are 640* 480; means there are 640 pixels resolution and 480 pixels in vertical directions to produce quality image provides better higher resolution picture. Higher resolution mean as sharper and clear image formed on the computer screen.Colors: Some graphics modes support more colors than other ranges upto 2 millions colors. A particular mode may support only two colors at a time while other may support 256 colors.Video Adapters: Video adapters are used to delivered image on. Each video adapter handles graphic in different way. A particular video adapter is initialized program for particular graphics mode then it can use it to plot various elements as well to display text in different fonts. Some example of vedio adapters are CGA, VGA. Each video adapter supports different resolutions colors.Initializing Graphics: The inbuilt function initgraph() is used to initialized graphic system and put computer screen in a specific mode function Initgraph() initialized the graphic systems by loading a graphic drives form into graphic modes. It also resets all graphic setting colors palette current positions view to their vauls. initgraph (&graphic driver, &graphic, "Path");Where graphic driver is variable of int type, this variable specifies grahic driver to be used. Graphic drivers are subset of drivers. Graphics drivers are applicable only in graphics mode and they communicate directly with monitors. C offers certain graphics derivers and these are communications directly with monitors the graphic divers are available in c:\tc\ big directory.DECECT (0) =, ega via, ega64 are common driver used.The second mode graphic mode is also type int that is initialized to mode for particular adapter to be use. This variable tells monitors we are using resolutions of numbers of video pages. It supports colors that are used, the third is path specifies the directory contains of particular driver. The detect function has some special values with some meanings as.

DETECT 3 0 (requests autodetection) CGA 3 1 MCGA 3 2 EGA 3 3 EGA64 3 4 EGAMONO 3 5 IBM8514 3 6 HERCMONO 3 7 ATT400 3 8

109

Page 110: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal VGA 3 9 PC3270 3 10Graphics│ driver │graphics_modes │Value │Column x Row│ Palette │Pages═════════ě══════════════ě═════ě════════════ě═════════ě══════════ CGA │ CGAC0 │ 0 │ 320 x 200 │ C0 │ 1 │ CGAC1 │ 1 │ 320 x 200 │ C1 │ 1 │ CGAC2 │ 2 │ 320 x 200 │ C2 │ 1 │ CGAC3 | 3 │ 320 x 200 │ C3 │ 1 │ CGAHI │ 4 │ 640 x 200 │ 2 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── MCGA │ MCGAC0 │ 0 │ 320 x 200 │ C0 │ 1 │ MCGAC1 │ 1 │ 320 x 200 │ C1 │ 1 │ MCGAC2 │ 2 │ 320 x 200 │ C2 │ 1 │ MCGAC3 │ 3 │ 320 x 200 │ C3 │ 1 │ MCGAMED │ 4 │ 640 x 200 │ 2 color│ 1 │ MCGAHI │ 5 │ 640 x 480 │ 2 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── EGA │ EGALO │ 0 │ 640 x 200 │ 16 color│ 4 │ EGAHI │ 1 │ 640 x 350 │ 16 color│ 2─────────┼──────────────┼─────┼────────────┼─────────┼─────── EGA64 │ EGA64LO │ 0 │ 640 x 200 │ 16 color│ 1 │ EGA64HI │ 1 │ 640 x 350 │ 4 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── EGA-MONO │ EGAMONOHI │ 3 │ 640 x 350 │ 2 color│ 1* │ EGAMONOHI │ 3 │ 640 x 350 │ 2 color│ 2**─────────┼──────────────┼─────┼────────────┼─────────┼─────── HERC │ HERCMONOHI │ 0 │ 720 x 348 │ 2 color│ 2─────────┼──────────────┼─────┼────────────┼─────────┼─────── ATT400 │ ATT400C0 │ 0 │ 320 x 200 │ C0 │ 1 │ ATT400C1 │ 1 │ 320 x 200 │ C1 │ 1 │ ATT400C2 │ 2 │ 320 x 200 │ C2 │ 1 │ ATT400C3 │ 3 │ 320 x 200 │ C3 │ 1 │ ATT400MED │ 4 │ 640 x 200 │ 2 color│ 1 │ ATT400HI │ 5 │ 640 x 400 │ 2 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── VGA │ VGALO │ 0 │ 640 x 200 │ 16 color│ 2 │ VGAMED │ 1 │ 640 x 350 │ 16 color│ 2 │ VGAHI │ 2 │ 640 x 480 │ 16 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── PC3270 │ PC3270HI │ 0 │ 720 x 350 │ 2 color│ 1─────────┼──────────────┼─────┼────────────┼─────────┼─────── IBM8514 │ IBM8514HI │ 1 │ 1024 x 760 │256 color│ │ IBM8514LO │ 0 │ 640 x 480 │256 color│Auto Initialization of Initgraph Functions: We have explicitly used initgraph () function what graphics drives and mode assigned particular values to drivers. It is possible to find out video adapter installed in computer and use the best driver and mode. The combination that gives highest resolutions. There are two approaches for auto initialization and graphic hardware.A special constant DTECT is used for driver argument. In this method the program does not know in advance what mode will be used and cannot assume anything about the resolution.

dg=DETECT;initgraph (dg,&gm,"c:\tc:\big");

A function called detect graph () is used that returns values for best driver and mode. These values can than be used as input to initgraph () function. initgraph (&dg, &gm,"c:\tc:\big");Closing Graph (): Once a program has finshed its jobs using graphics facilities, then it should restore system to the mode that was previously in use. If graphics mode is not closed explicitly programmer undesirable

110

Page 111: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimaleffects may be felt. The close graph () function is used to restore screen to the mode. It was in before we called initgrah ()locates all memory allocated by grahic system. close graph ();Observation of Graphic Results: The library function graphic result () is used to determine whether a certain graphic operation successes or not. This function returns an errors code for last unsucefffully operations. It returns the errors code for the last graphics operations that reports an errors, then reset the errors to grOk.

#include<graphics.h>#include<stdio.h>#include<conio.h>void main(){ int errorcode,gm,gd;detectgraph(&gd,&gm);errorcode=graphresult();if(errorcode!=grOk){ printf("\n not hardware driver");}initgraph(&gd,&gm,"c:\tc\\big");errorcode=graphresult();if(errorcode!=grOk){ printf("\n graphic installed failed");}closegraph();getch();}

Some library functions related graphics are: putpxel() plots a point with specified color.putpixel (Int x, Int y, Int color);getpixel(Int x, Int y);changing drawing colorsetcolor(int color);setcolor(int color);Drawlineline(int x, int y, int x1, int y2);setline style(int style, unsigned int pattern , int thicknes);

COLORS (text mode)Constant │Value │grnd? │grnd?══════════════Ï═════Ï═════Ï═════ BLACK │ 0 │ Yes │ Yes BLUE │ 1 │ Yes │ Yes GREEN │ 2 │ Yes │ Yes CYAN │ 3 │ Yes │ Yes RED │ 4 │ Yes │ Yes MAGENTA │ 5 │ Yes │ Yes BROWN │ 6 │ Yes │ Yes LIGHTGRAY │ 7 │ Yes │ Yes DARKGRAY │ 8 │ No │ Yes LIGHTBLUE 9 │ No │ Yes LIGHTGREEN │ 10 │ No │ Yes LIGHTCYAN │ 11 │ No │ Yes LIGHTRED │ 12 │ No │ Yes LIGHTMAGENTA │ 13 │ No │ Yes YELLOW │ 14 │ No │ Yes WHITE │ 15 │ No │ Yes──────────────┼─────┼─────┼────── BLINK │128 │ No │ ***

code │ constant │ Corresponding error message string══════╪═══════════════════╪═════════════════════════════ 0 │ grOk │ No error -1 │ grNoInitGraph │ (BGI) graphics not installed (use initgraph) -2 │ grNotDetected │ Graphics hardware not detected -3 │ grFileNotFound │ Device driver file not found -4 │ grInvalidDriver │ Invalid device driver file

111

Page 112: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal -5 │ grNoLoadMem │ Not enough memory to load driver -6 │ grNoScanMem │ Out of memory in scan fill -7 │ grNoFloodMem │ Out of memory in flood fill -8 │ grFontNotFound │ Font file not found -9 │ grNoFontMem │ Not enough memory to load font -10 │ grInvalidMode │ Invalid graphics mode for selected driver -11 │ grError │ Graphics error -12 │ grIOerror │ Graphics I/O error -13 │ grInvalidFont │ Invalid font file -14 │ grInvalidFontNum │ Invalid font number -15 │ grInvalidDeviceNum │ Invalid device number -18 │ grInvalidVersion │ Invalid version numberWAP to draw a line passing frorm a point 0 to 50 to another point 200,300

#include<graphics.h>#include<stdio.h>#include<conio.h>void main(){ int gd=DETECT,gm,err;initgraph(&gd,&gm,"c:\\tc\\bgi");err=graphresult();if(err!=grOk){printf("\n graphic initailixation"); }setcolor(GREEN);line(0,50,200,300);getch(); closegraph(); }

WAP in c to draw following figures#include<graphics.h>#include<stdio.h>#include<conio.h>void main(){int gd=DETECT,gm,err;initgraph(&gd,&gm,"c:\\tc\\bgi");err=graphresult();if(err!=grOk){printf("\n graphic initailixation");}setcolor(GREEN);circle(200,300,50);ellipse(100,100,0,360,50,75);arc(400,200,90,180,75);rectangle(0,0,100,200);rectangle(150,250,200,300);getch();closegraph();}

write a program to hexagon#include<graphics.h> #include<stdio.h>#include<conio.h>void main(){int gd=DETECT,gmode;int poly[]={10,75,50,25,100,25,140,75,100,125,50,125,10,75};initgraph(&gd,&gmode,"c:\\tc\\bgi");setcolor(YELLOW);drawpoly(7,poly);fillpoly(7,poly);getch();closegraph();}WAP to display text in frpahic circle#include<graphics.h>#include<stdio.h> #include<conio.h>void main(){int gd=VGA,gm=VGAHI;initgraph(&gd,&gm,"c:\\tc\\bgi");

112

Page 113: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalsetcolor(RED);circle(200,100,50);outtextxy(200,100,".");outtextxy(175,110,"(200,100)");moveto(50,175);outtext("Fig:circle having center of c programming,200,100");getch();closegraph();}

WAP x coordinate and y coordinate#include<graphics.h>#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){int gdriver=VGA,gmode=VGAMED;int maxx; int maxy;char x[5] ="", y[5]="";initgraph(&gdriver,&gmode,"c:\\tc\\bgi");setcolor(RED);maxx=getmaxx(); maxy=getmaxy();itoa(maxx,x,10);//convert int to sringitoa(maxy,y,10);outtextxy(10,10,"max x=");outtextxy(60,10,x);outtextxy(10,20,"Max y=");outtextxy(50,20,y);getch();closegraph();}WAP to craw concentric circle at the center display#include<graphics.h>#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){int gdriver=EGA,gmode=VGAMED,x,y,maxx,maxy;initgraph(&gdriver,&gmode,"c:\\tc\\bgi");setcolor(RED);maxx=getmaxx();maxy=getmaxy();x=maxx/2; y=maxy/2;circle(x,y,50);circle(x,y,75);outtextxy(x,y,".");getch();closegraph(); }

CHAPTER 1: What is a pointer? One of those things beginners in C find difficult is the concept of pointers. The purpose of this tutorial is to provide an introduction to pointers and their use to these beginners. I have found that often the main reason beginners have a problem with pointers is that they have a weak or minimal feeling for variables, (as they are used in C). Thus we start with a discussion of C variables in general. A variable in a program is something with a name, the value of which can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within the computer to hold the value of that variable. The size of that block depends on the range over which the variable is allowed to vary. For example,

113

Page 114: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalon 32 bit PC's the size of an integer variable is 4 bytes. On older 16 bit PCs integers were 2 bytes.  In C the size of a variable type such as an integer need not be the same on all types of machines.  Further more there is more than one type of integer variable in C.  We have integers, long integers and short integers which you can read up on in any basic text on C.  This document assumes the use of a 32 bit system with 4 byte integers. If you want to know the size of the various types of integers on your system, running the following code will give you that information. #include <stdio.h>int main() {printf("size of a short is %d\n", sizeof(short));printf("size of a int is %d\n", sizeof(int));printf("size of a long is %d\n", sizeof(long));}When we declare a variable we inform the compiler of two things, the name of the variable and the type of the variable. For example, we declare a variable of type integer with the name k by writing: int k; On seeing the "int" part of this statement the compiler sets aside 4 bytes of memory (on a PC) to hold the value of the integer. It also sets up a symbol table. In that table it adds the symbol k and the relative address in memory where those 4 bytes were set aside. Thus, later if we write: k = 2; we expect that, at run time when this statement is executed, the value 2 will be placed in that memory location reserved for the storage of the value of k. In C we refer to a variable such as the integer k as an "object". In a sense there are two "values" associated with the object k. One is the value of the integer stored there (2 in the above example) and the other the "value" of the memory location, i.e., the address of k. Some texts refer to these two values with the nomenclature rvalue (right value, pronounced "are value") and lvalue (left value, pronounced "el value") respectively. In some languages, the lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the assignment statement, the 2 above. Rvalues cannot be used on the left side of the assignment statement. Thus: 2 = k; is illegal. Actually, the above definition of "lvalue" is somewhat modified for C. According to K&R II (page 197): [1] "An object is a named region of storage; an lvalue is an expression referring to an object." However, at this point, the definition originally cited above is sufficient. As we become more familiar with pointers we will go into more detail on this. Okay, now consider: int j, k; k = 2; j = 7; <-- line 1 k = j; <-- line 2 In the above, the compiler interprets the j in line 1 as the address of the variable j (its lvalue) and creates code to copy the value 7 to that address. In line 2, however, the j is interpreted as its rvalue (since it is on the right hand side of the assignment operator '='). That is, here the j refers to the value stored at the memory location set aside for j, in this case 7. So, the 7 is copied to the address designated by the lvalue of k. In all of these examples, we are using 4 byte integers so all copying of rvalues from one storage location to the other is done by copying 4 bytes. Had we been using two byte integers, we would be copying 2 bytes. Now, let's say that we have a reason for wanting a variable designed to hold an lvalue (an address). The size required to hold such a value depends on the system. On older desk top computers with 64K of memory total, the address of any point in memory can be contained in 2 bytes. Computers with more memory would require more bytes to hold an address.  The actual size required is not too important so long as we have a way of informing the compiler that what we want to store is an address. Such a variable is called a pointer variable (for reasons which hopefully will become clearer a little later). In C when we define a pointer variable we do so by preceding its name with an asterisk. In C we also give our pointer a type which, in this case, refers to the type of data stored at the address we will be storing in our pointer. For example, consider the variable declaration: int *ptr;

114

Page 115: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalptr is the name of our variable (just as k was the name of our integer variable). The '*' informs the compiler that we want a pointer variable, i.e. to set aside however many bytes is required to store an address in memory. The int says that we intend to use our pointer variable to store the address of an integer. Such a pointer is said to "point to" an integer. However, note that when we wrote int k; we did not give k a value. If this definition is made outside of any function ANSI compliant compilers will initialize it to zero. Similarly, ptr has no value, that is we haven't stored an address in it in the above declaration. In this case, again if the declaration is outside of any function, it is initialized to a value guaranteed in such a way that it is guaranteed to not point to any C object or function. A pointer initialized in this manner is called a "null" pointer. The actual bit pattern used for a null pointer may or may not evaluate to zero since it depends on the specific system on which the code is developed. To make the source code compatible between various compilers on various systems, a macro is used to represent a null pointer. That macro goes under the name NULL. Thus, setting the value of a pointer using the NULL macro, as with an assignment statement such as ptr = NULL, guarantees that the pointer has become a null pointer. Similarly, just as one can test for an integer value of zero, as in if(k == 0), we can test for a null pointer using if (ptr == NULL). But, back to using our new variable ptr. Suppose now that we want to store in ptr the address of our integer variable k. To do this we use the unary & operator and write: ptr = &k; What the & operator does is retrieve the lvalue (address) of k, even though k is on the right hand side of the assignment operator '=', and copies that to the contents of our pointer ptr. Now, ptr is said to "point to" k. Bear with us now, there is only one more operator we need to discuss. The "dereferencing operator" is the asterisk and it is used as follows: *ptr = 7; will copy 7 to the address pointed to by ptr. Thus if ptr "points to" (contains the address of) k, the above statement will set the value of k to 7. That is, when we use the '*' this way we are referring to the value of that which ptr is pointing to, not the value of the pointer itself. Similarly, we could write: printf("%d\n",*ptr); to print to the screen the integer value stored at the address pointed to by ptr;. One way to see how all this stuff fits together would be to run the following program and then review the code and the output carefully. #include <stdio.h>int j, k; int *ptr;int main(void){ j = 1; k = 2; ptr = &k; printf("\n"); printf("j has the value %d and is stored at %p\n", j, (void *)&j); printf("k has the value %d and is stored at %p\n", k, (void *)&k); printf("ptr has the value %p and is stored at %p\n", ptr, (void *)&ptr); printf("The value of the integer pointed to by ptr is %d\n", *ptr); return 0;}Note: We have yet to discuss those aspects of C which require the use of the (void *) expression used here. For now, include it in your test code. We'll explain the reason behind this expression later. To review:

A variable is declared by giving it a type and a name (e.g. int k;) A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where the asterisk tells the

compiler that the variable named ptr is a pointer variable and the type tells the compiler what type the pointer is to point to (integer in this case).

Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in &k.

We can "dereference" a pointer, i.e. refer to the value of that which it points to, by using the unary '*' operator as in *ptr.

An "lvalue" of a variable is the value of its address, i.e. where it is stored in memory. The "rvalue" of a variable is the value stored in that variable (at that address).

CHAPTER 2: Pointer types and Arrays Okay, let's move on. Let us consider why we need to identify the type of variable that a pointer points to, as in: int *ptr;

115

Page 116: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalOne reason for doing this is so that later, once ptr "points to" something, if we write: *ptr = 2;the compiler will know how many bytes to copy into that memory location pointed to by ptr. If ptr was declared as pointing to an integer, 4 bytes would be copied.  Similarly for floats and doubles the appropriate number will be copied. But, defining the type that the pointer points to permits a number of other interesting ways a compiler can interpret code. For example, consider a block in memory consisting if ten integers in a row. That is, 40 bytes of memory are set aside to hold 10 integers. Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore lets say that integer is located at memory location 100 (decimal). What happens when we write: ptr + 1; Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it points to an integer (its current address, 100, is the address of an integer), it adds 4 to ptr instead of 1, so the pointer "points to" the next integer, at memory location 104. Similarly, were the ptr declared as a pointer to a short, it would add 2 to it instead of 1. The same goes for other data types such as floats, doubles, or even user defined data types such as structures. This is obviously not the same kind of "addition" that we normally think of. In C it is referred to as addition using "pointer arithmetic", a term which we will come back to later. Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 4 for an integer). Since a block of 10 integers located contiguously in memory is, by definition, an array of integers, this brings up an interesting relationship between arrays and pointers. Consider the following: int my_array[] = {1,23,17,4,-5,100}; Here we have an array containing 6 integers. We refer to each of these integers by means of a subscript to my_array, i.e. using my_array[0] through my_array[5]. But, we could alternatively access them via a pointer as follows: int *ptr; ptr = &my_array[0]; /* point our pointer at the first integer in our array */ And then we could print out our array either using the array notation or by dereferencing our pointer. The following code illustrates this: /* Program 2.1 from PTRTUT10.HTM 6/13/97 */#include <stdio.h>int my_array[] = {1,23,17,4,-5,100};int *ptr;int main(void){ int i; ptr = &my_array[0]; /* point our pointer to the first element of the array */ printf("\n\n"); for (i = 0; i < 6; i++) { printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */ printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */ } return 0; }Compile and run the above program and carefully note lines A and B and that the program prints out the same values in either case. Also observe how we dereferenced our pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change line B to read: printf("ptr + %d = %d\n",i, *ptr++);and run it again... then change it to: printf("ptr + %d = %d\n",i, *(++ptr));and try once more. Each time try and predict the outcome and carefully look at the actual outcome. In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name, thus in our code where we wrote: ptr = &my_array[0]; we can write: ptr = my_array;to achieve the same result.

116

Page 117: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThis leads many texts to state that the name of an array is a pointer. I prefer to mentally think "the name of the array is the address of first element in the array". Many beginners (including myself when I was learning) have a tendency to become confused by thinking of it as a pointer. For example, while we can write ptr = my_array; we cannot write my_array = ptr;The reason is that while ptr is a variable, my_array is a constant. That is, the location at which the first element of my_array will be stored cannot be changed once my_array[] has been declared. Earlier when discussing the term "lvalue" I cited K&R-2 where it stated: "An object is a named region of storage; an lvalue is an expression referring to an object". This raises an interesting problem. Since my_array is a named region of storage, why is my_array in the above assignment statement not an lvalue? To resolve this problem, some refer to my_array as an "unmodifiable lvalue". Modify the example program above by changing ptr = &my_array[0]; to ptr = my_array;and run it again to verify the results are identical. Now, let's delve a little further into the difference between the names ptr and my_array as used above. Some writers will refer to an array's name as a constant pointer. What do we mean by that? Well, to understand the term "constant" in this sense, let's go back to our definition of the term "variable". When we declare a variable we set aside a spot in memory to hold the value of the appropriate type. Once that is done the name of the variable can be interpreted in one of two ways. When used on the left side of the assignment operator, the compiler interprets it as the memory location to which to move that value resulting from evaluation of the right side of the assignment operator. But, when used on the right side of the assignment operator, the name of a variable is interpreted to mean the contents stored at that memory address set aside to hold the value of that variable. With that in mind, let's now consider the simplest of constants, as in: int i, k; i = 2;Here, while i is a variable and then occupies space in the data portion of memory, 2 is a constant and, as such, instead of setting aside memory in the data segment, it is imbedded directly in the code segment of memory. That is, while writing something like k = i; tells the compiler to create code which at run time will look at memory location &i to determine the value to be moved to k, code created by i = 2; simply puts the 2 in the code and there is no referencing of the data segment. That is, both k and i are objects, but 2 is not an object. Similarly, in the above, since my_array is a constant, once the compiler establishes where the array itself is to be stored, it "knows" the address of my_array[0] and on seeing: ptr = my_array;it simply uses this address as a constant in the code segment and there is no referencing of the data segment beyond that. This might be a good place explain further the use of the (void *) expression used in Program 1.1 of Chapter 1. As we have seen we can have pointers of various types. So far we have discussed pointers to integers and pointers to characters. In coming chapters we will be learning about pointers to structures and even pointer to pointers. Also we have learned that on different systems the size of a pointer can vary. As it turns out it is also possible that the size of a pointer can vary depending on the data type of the object to which it points. Thus, as with integers where you can run into trouble attempting to assign a long integer to a variable of type short integer, you can run into trouble attempting to assign the values of pointers of various types to pointer variables of other types. To minimize this problem, C provides for a pointer of type void. We can declare such a pointer by writing: void *vptr;A void pointer is sort of a generic pointer. For example, while C will not permit the comparison of a pointer to type integer with a pointer to type character, for example, either of these can be compared to a void pointer. Of course, as with other variables, casts can be used to convert from one type of pointer to another under the proper circumstances. In Program 1.1. of Chapter 1 I cast the pointers to integers into void pointers to make

117

Page 118: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalthem compatible with the %p conversion specification. In later chapters other casts will be made for reasons defined therein. Well, that's a lot of technical stuff to digest and I don't expect a beginner to understand all of it on first reading. With time and experimentation you will want to come back and re-read the first 2 chapters. But for now, let's move on to the relationship between pointers, character arrays, and strings. CHAPTER 3: Pointers and Strings The study of strings is useful to further tie in the relationship between pointers and arrays. It also makes it easy to illustrate how some of the standard C string functions can be implemented. Finally it illustrates how and when pointers can and should be passed to functions. In C, strings are arrays of characters. This is not necessarily true in other languages. In BASIC, Pascal, Fortran and various other languages, a string has its own data type. But in C it does not. In C a string is an array of characters terminated with a binary zero character (written as '\0'). To start off our discussion we will write some code which, while preferred for illustrative purposes, you would probably never write in an actual program. Consider, for example: char my_string[40]; my_string[0] = 'T'; my_string[1] = 'e'; my_string[2] = 'd': my_string[3] = '\0';While one would never build a string like this, the end result is a string in that it is an array of characters terminated with a nul character. By definition, in C, a string is an array of characters terminated with the nul character. Be aware that "nul" is not the same as "NULL". The nul refers to a zero as defined by the escape sequence '\0'. That is it occupies one byte of memory. NULL, on the other hand, is the name of the macro used to initialize null pointers. NULL is #defined in a header file in your C compiler, nul may not be #defined at all. Since writing the above code would be very time consuming, C permits two alternate ways of achieving the same thing. First, one might write: char my_string[40] = {'T', 'e', 'd', '\0',}; But this also takes more typing than is convenient. So, C permits: char my_string[40] = "Ted";When the double quotes are used, instead of the single quotes as was done in the previous examples, the nul character ( '\0' ) is automatically appended to the end of the string. In all of the above cases, the same thing happens. The compiler sets aside an contiguous block of memory 40 bytes long to hold characters and initialized it such that the first 4 characters are Ted\0. Now, consider the following program: #include <stdio.h>char strA[80] = "A string to be used for demonstration purposes";char strB[80];int main(void){ char *pA; /* a pointer to type character */ char *pB; /* another pointer to type character */ puts(strA); /* show string A */ pA = strA; /* point pA at string A */ puts(pA); /* show what pA is pointing to */ pB = strB; /* point pB at string B */ putchar('\n'); /* move down one line on the screen */ while(*pA != '\0') /* line A (see text) */ { *pB++ = *pA++; /* line B (see text) */ } *pB = '\0'; /* line C (see text) */ puts(strB); /* show strB on screen */ return 0;}

118

Page 119: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalIn the above we start out by defining two character arrays of 80 characters each. Since these are globally defined, they are initialized to all '\0's first. Then, strA has the first 42 characters initialized to the string in quotes. Now, moving into the code, we declare two character pointers and show the string on the screen. We then "point" the pointer pA at strA. That is, by means of the assignment statement we copy the address of strA[0] into our variable pA. We now use puts() to show that which is pointed to by pA on the screen. Consider here that the function prototype for puts() is: int puts(const char *s); For the moment, ignore the const. The parameter passed to puts() is a pointer, that is the value of a pointer (since all parameters in C are passed by value), and the value of a pointer is the address to which it points, or, simply, an address. Thus when we write puts(strA); as we have seen, we are passing the address of strA[0]. Similarly, when we write puts(pA); we are passing the same address, since we have set pA = strA; Given that, follow the code down to the while() statement on line A. Line A states: While the character pointed to by pA (i.e. *pA) is not a nul character (i.e. the terminating '\0'), do the following: Line B states: copy the character pointed to by pA to the space pointed to by pB, then increment pA so it points to the next character and pB so it points to the next space. When we have copied the last character, pA now points to the terminating nul character and the loop ends. However, we have not copied the nul character. And, by definition a string in C must be nul terminated. So, we add the nul character with line C. It is very educational to run this program with your debugger while watching strA, strB, pA and pB and single stepping through the program. It is even more educational if instead of simply defining strB[] as has been done above, initialize it also with something like: strB[80] = "12345678901234567890123456789012345678901234567890"where the number of digits used is greater than the length of strA and then repeat the single stepping procedure while watching the above variables. Give these things a try! Getting back to the prototype for puts() for a moment, the "const" used as a parameter modifier informs the user that the function will not modify the string pointed to by s, i.e. it will treat that string as a constant. Of course, what the above program illustrates is a simple way of copying a string. After playing with the above until you have a good understanding of what is happening, we can proceed to creating our own replacement for the standard strcpy() that comes with C. It might look like: char *my_strcpy(char *destination, char *source) { char *p = destination; while (*source != '\0') { *p++ = *source++; } *p = '\0'; return destination; } In this case, I have followed the practice used in the standard routine of returning a pointer to the destination. Again, the function is designed to accept the values of two character pointers, i.e. addresses, and thus in the previous program we could write: int main(void) { my_strcpy(strB, strA); puts(strB); } I have deviated slightly from the form used in standard C which would have the prototype: char *my_strcpy(char *destination, const char *source); Here the "const" modifier is used to assure the user that the function will not modify the contents pointed to by the source pointer. You can prove this by modifying the function above, and its prototype, to include the "const" modifier as shown. Then, within the function you can add a statement which attempts to change the contents of that which is pointed to by source, such as: *source = 'X';which would normally change the first character of the string to an X. The const modifier should cause your compiler to catch this as an error. Try it and see. Now, let's consider some of the things the above examples have shown us. First off, consider the fact that *ptr++ is to be interpreted as returning the value pointed to by ptr and then incrementing the pointer value.

119

Page 120: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalThis has to do with the precedence of the operators. Were we to write (*ptr)++ we would increment, not the pointer, but that which the pointer points to! i.e. if used on the first character of the above example string the 'T' would be incremented to a 'U'. You can write some simple example code to illustrate this. Recall again that a string is nothing more than an array of characters, with the last character being a '\0'. What we have done above is deal with copying an array. It happens to be an array of characters but the technique could be applied to an array of integers, doubles, etc. In those cases, however, we would not be dealing with strings and hence the end of the array would not be marked with a special value like the nul character. We could implement a version that relied on a special value to identify the end. For example, we could copy an array of positive integers by marking the end with a negative integer. On the other hand, it is more usual that when we write a function to copy an array of items other than strings we pass the function the number of items to be copied as well as the address of the array, e.g. something like the following prototype might indicate: void int_copy(int *ptrA, int *ptrB, int nbr);where nbr is the number of integers to be copied. You might want to play with this idea and create an array of integers and see if you can write the function int_copy() and make it work. This permits using functions to manipulate large arrays. For example, if we have an array of 5000 integers that we want to manipulate with a function, we need only pass to that function the address of the array (and any auxiliary information such as nbr above, depending on what we are doing). The array itself does not get passed, i.e. the whole array is not copied and put on the stack before calling the function, only its address is sent. This is different from passing, say an integer, to a function. When we pass an integer we make a copy of the integer, i.e. get its value and put it on the stack. Within the function any manipulation of the value passed can in no way effect the original integer. But, with arrays and pointers we can pass the address of the variable and hence manipulate the values of the original variables. CHAPTER 4: More on StringsWell, we have progressed quite a way in a short time! Let's back up a little and look at what was done in Chapter 3 on copying of strings but in a different light. Consider the following function: char *my_strcpy(char dest[], char source[]) { int i = 0; while (source[i] != '\0') { dest[i] = source[i]; i++; } dest[i] = '\0'; return dest; }Recall that strings are arrays of characters. Here we have chosen to use array notation instead of pointer notation to do the actual copying. The results are the same, i.e. the string gets copied using this notation just as accurately as it did before. This raises some interesting points which we will discuss. Since parameters are passed by value, in both the passing of a character pointer or the name of the array as above, what actually gets passed is the address of the first element of each array. Thus, the numerical value of the parameter passed is the same whether we use a character pointer or an array name as a parameter. This would tend to imply that somehow source[i] is the same as *(p+i). In fact, this is true, i.e wherever one writes a[i] it can be replaced with *(a + i) without any problems. In fact, the compiler will create the same code in either case. Thus we see that pointer arithmetic is the same thing as array indexing. Either syntax produces the same result. This is NOT saying that pointers and arrays are the same thing, they are not. We are only saying that to identify a given element of an array we have the choice of two syntaxes, one using array indexing and the other using pointer arithmetic, which yield identical results. Now, looking at this last expression, part of it.. (a + i), is a simple addition using the + operator and the rules of C state that such an expression is commutative. That is (a + i) is identical to (i + a). Thus we could write *(i + a) just as easily as *(a + i). But *(i + a) could have come from i[a] ! From all of this comes the curious truth that if: char a[20]; int i; writing a[3] = 'x';is the same as writing 3[a] = 'x';

120

Page 121: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalTry it! Set up an array of characters, integers or longs, etc. and assigned the 3rd or 4th element a value using the conventional approach and then print out that value to be sure you have that working. Then reverse the array notation as I have done above. A good compiler will not balk and the results will be identical. A curiosity... nothing more! Now, looking at our function above, when we write: dest[i] = source[i];due to the fact that array indexing and pointer arithmetic yield identical results, we can write this as: *(dest + i) = *(source + i);But, this takes 2 additions for each value taken on by i. Additions, generally speaking, take more time than incrementations (such as those done using the ++ operator as in i++). This may not be true in modern optimizing compilers, but one can never be sure. Thus, the pointer version may be a bit faster than the array version. Another way to speed up the pointer version would be to change: while (*source != '\0') to simply while (*source)since the value within the parenthesis will go to zero (FALSE) at the same time in either case. At this point you might want to experiment a bit with writing some of your own programs using pointers. Manipulating strings is a good place to experiment. You might want to write your own versions of such standard functions as: strlen(); strcat(); strchr();and any others you might have on your system. We will come back to strings and their manipulation through pointers in a future chapter. For now, let's move on and discuss structures for a bit. CHAPTER 5: Pointers and Structures As you may know, we can declare the form of a block of data containing different data types by means of a structure declaration. For example, a personnel file might contain structures which look something like: struct tag { char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g. 12.75 per hour */ };Let's say we have a bunch of these structures in a disk file and we want to read each one out and print out the first and last name of each one so that we can have a list of the people in our files. The remaining information will not be printed out. We will want to do this printing with a function call and pass to that function a pointer to the structure at hand. For demonstration purposes I will use only one structure for now. But realize the goal is the writing of the function, not the reading of the file which, presumably, we know how to do. For review, recall that we can access structure members with the dot operator as in: #include <stdio.h>#include <string.h>struct tag { char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; }; /* e.g. 12.75 per hour */struct tag my_struct; /* declare the structure my_struct */int main(void){ strcpy(my_struct.lname,"Jensen"); strcpy(my_struct.fname,"Ted"); printf("\n%s ",my_struct.fname); printf("%s\n",my_struct.lname); return 0;}

121

Page 122: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalNow, this particular structure is rather small compared to many used in C programs. To the above we might want to add: date_of_hire; (data types not shown) date_of_last_raise; last_percent_increase; emergency_phone; medical_plan; Social_S_Nbr; etc.....If we have a large number of employees, what we want to do is manipulate the data in these structures by means of functions. For example we might want a function print out the name of the employee listed in any structure passed to it. However, in the original C (Kernighan & Ritchie, 1st Edition) it was not possible to pass a structure, only a pointer to a structure could be passed. In ANSI C, it is now permissible to pass the complete structure. But, since our goal here is to learn more about pointers, we won't pursue that. Anyway, if we pass the whole structure it means that we must copy the contents of the structure from the calling function to the called function. In systems using stacks, this is done by pushing the contents of the structure on the stack. With large structures this could prove to be a problem. However, passing a pointer uses a minimum amount of stack space. In any case, since this is a discussion of pointers, we will discuss how we go about passing a pointer to a structure and then using it within the function. Consider the case described, i.e. we want a function that will accept as a parameter a pointer to a structure and from within that function we want to access members of the structure. For example we want to print out the name of the employee in our example structure. Okay, so we know that our pointer is going to point to a structure declared using struct tag. We declare such a pointer with the declaration: struct tag *st_ptr;and we point it to our example structure with: st_ptr = &my_struct;Now, we can access a given member by de-referencing the pointer. But, how do we de-reference the pointer to a structure? Well, consider the fact that we might want to use the pointer to set the age of the employee. We would write: (*st_ptr).age = 63;Look at this carefully. It says, replace that within the parenthesis with that which st_ptr points to, which is the structure my_struct. Thus, this breaks down to the same as my_struct.age. However, this is a fairly often used expression and the designers of C have created an alternate syntax with the same meaning which is: st_ptr->age = 63;With that in mind, look at the following program: #include <stdio.h>#include <string.h>struct tag{ /* the structure type */ char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g. 12.75 per hour */};

struct tag my_struct; /* define the structure */void show_name(struct tag *p); /* function prototype */int main(void){ struct tag *st_ptr; /* a pointer to a structure */ st_ptr = &my_struct; /* point the pointer to my_struct */

122

Page 123: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal strcpy(my_struct.lname,"Jensen"); strcpy(my_struct.fname,"Ted"); printf("\n%s ",my_struct.fname); printf("%s\n",my_struct.lname); my_struct.age = 63; show_name(st_ptr); /* pass the pointer */ return 0;}void show_name(struct tag *p){ printf("\n%s ", p->fname); /* p points to a structure */ printf("%s ", p->lname); printf("%d\n", p->age);}Again, this is a lot of information to absorb at one time. The reader should compile and run the various code snippets and using a debugger monitor things like my_struct and p while single stepping through the main and following the code down into the function to see what is happening.

CHAPTER 6: Some more on Strings, and Arrays of Strings Well, let's go back to strings for a bit. In the following all assignments are to be understood as being global, i.e. made outside of any function, including main(). We pointed out in an earlier chapter that we could write: char my_string[40] = "Ted";which would allocate space for a 40 byte array and put the string in the first 4 bytes (three for the characters in the quotes and a 4th to handle the terminating '\0'). Actually, if all we wanted to do was store the name "Ted" we could write: char my_name[] = "Ted";and the compiler would count the characters, leave room for the nul character and store the total of the four characters in memory the location of which would be returned by the array name, in this case my_name. In some code, instead of the above, you might see: char *my_name = "Ted";which is an alternate approach. Is there a difference between these? The answer is.. yes. Using the array notation 4 bytes of storage in the static memory block are taken up, one for each character and one for the terminating nul character. But, in the pointer notation the same 4 bytes required, plus N bytes to store the pointer variable my_name (where N depends on the system but is usually a minimum of 2 bytes and can be 4 or more). In the array notation, my_name is short for &myname[0] which is the address of the first element of the array. Since the location of the array is fixed during run time, this is a constant (not a variable). In the pointer notation my_name is a variable. As to which is the better method, that depends on what you are going to do within the rest of the program. Let's now go one step further and consider what happens if each of these declarations are done within a function as opposed to globally outside the bounds of any function. void my_function_A(char *ptr){ char a[] = "ABCDE" . .} void my_function_B(char *ptr){ char *cp = "FGHIJ" . .}In the case of my_function_A, the content, or value(s), of the array a[] is considered to be the data. The array is said to be initialized to the values ABCDE. In the case of my_function_B, the value of the pointer cp is considered to be the data. The pointer has been initialized to point to the string FGHIJ. In both my_function_A and my_function_B the definitions are local variables and thus the string ABCDE is stored on the stack, as is the value of the pointer cp. The string FGHIJ can be stored anywhere. On my system it gets stored in the data segment.

123

Page 124: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalBy the way, array initialization of automatic variables as I have done in my_function_A was illegal in the older K&R C and only "came of age" in the newer ANSI C. A fact that may be important when one is considering portability and backwards compatibility. As long as we are discussing the relationship/differences between pointers and arrays, let's move on to multi-dimensional arrays. Consider, for example the array: char multi[5][10];Just what does this mean? Well, let's consider it in the following light. char multi[5][10];Let's take the underlined part to be the "name" of an array. Then prepending the char and appending the [10] we have an array of 10 characters. But, the name multi[5] is itself an array indicating that there are 5 elements each being an array of 10 characters. Hence we have an array of 5 arrays of 10 characters each.. Assume we have filled this two dimensional array with data of some kind. In memory, it might look as if it had been formed by initializing 5 separate arrays using something like: multi[0] = {'0','1','2','3','4','5','6','7','8','9'} multi[1] = {'a','b','c','d','e','f','g','h','i','j'} multi[2] = {'A','B','C','D','E','F','G','H','I','J'} multi[3] = {'9','8','7','6','5','4','3','2','1','0'} multi[4] = {'J','I','H','G','F','E','D','C','B','A'}At the same time, individual elements might be addressable using syntax such as: multi[0][3] = '3' multi[1][7] = 'h' multi[4][0] = 'J'Since arrays are contiguous in memory, our actual memory block for the above should look like: 0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA |_____ starting at the address &multi[0][0]

Note that I did not write multi[0] = "0123456789". Had I done so a terminating '\0' would have been implied since whenever double quotes are used a '\0' character is appended to the characters contained within those quotes. Had that been the case I would have had to set aside room for 11 characters per row instead of 10. My goal in the above is to illustrate how memory is laid out for 2 dimensional arrays. That is, this is a 2 dimensional array of characters, NOT an array of "strings". Now, the compiler knows how many columns are present in the array so it can interpret multi + 1 as the address of the 'a' in the 2nd row above. That is, it adds 10, the number of columns, to get this location. If we were dealing with integers and an array with the same dimension the compiler would add 10*sizeof(int) which, on my machine, would be 20. Thus, the address of the 9 in the 4th row above would be &multi[3][0] or *(multi + 3) in pointer notation. To get to the content of the 2nd element in the 4th row we add 1 to this address and dereference the result as in *(*(multi + 3) + 1)With a little thought we can see that: *(*(multi + row) + col) and multi[row][col] yield the same results.The following program illustrates this using integer arrays instead of character arrays. #include <stdio.h>#define ROWS 5#define COLS 10int multi[ROWS][COLS];int main(void){ int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { multi[row][col] = row*col; } } for (row = 0; row < ROWS; row++) {

124

Page 125: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal for (col = 0; col < COLS; col++) { printf("\n%d ",multi[row][col]); printf("%d ",*(*(multi + row) + col)); } } return 0;} Because of the double de-referencing required in the pointer version, the name of a 2 dimensional array is often said to be equivalent to a pointer to a pointer. With a three dimensional array we would be dealing with an array of arrays of arrays and some might say its name would be equivalent to a pointer to a pointer to a pointer. However, here we have initially set aside the block of memory for the array by defining it using array notation. Hence, we are dealing with a constant, not a variable. That is we are talking about a fixed address not a variable pointer. The dereferencing function used above permits us to access any element in the array of arrays without the need of changing the value of that address (the address of multi[0][0] as given by the symbol multi). CHAPTER 7: More on Multi-Dimensional ArraysIn the previous chapter we noted that given #define ROWS 5 #define COLS 10 int multi[ROWS][COLS];we can access individual elements of the array multi using either: multi[row][col] or *(*(multi + row) + col)To understand more fully what is going on, let us replace *(multi + row)with X as in: *(X + col)Now, from this we see that X is like a pointer since the expression is de-referenced and we know that col is an integer. Here the arithmetic being used is of a special kind called "pointer arithmetic" is being used. That means that, since we are talking about an integer array, the address pointed to by (i.e. value of) X + col + 1 must be greater than the address X + col by and amount equal to sizeof(int). Since we know the memory layout for 2 dimensional arrays, we can determine that in the expression multi + row as used above, multi + row + 1 must increase by value an amount equal to that needed to "point to" the next row, which in this case would be an amount equal to COLS * sizeof(int). That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run time, the compiler must generate code which takes into consideration the value of COLS, i.e. the 2nd dimension. Because of the equivalence of the two forms of expression, this is true whether we are using the pointer expression as here or the array expression multi[row][col]. Thus, to evaluate either expression, a total of 5 values must be known:

1. The address of the first element of the array, which is returned by the expression multi, i.e., the name of the array.

2. The size of the type of the elements of the array, in this case sizeof(int). 3. The 2nd dimension of the array 4. The specific index value for the first dimension, row in this case. 5. The specific index value for the second dimension, col in this case.

Given all of that, consider the problem of designing a function to manipulate the element values of a previously declared array. For example, one which would set all the elements of the array multi to the value 1. void set_value(int m_array[][COLS]) { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { m_array[row][col] = 1; } } }And to call this function we would then use: set_value(multi);

125

Page 126: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalNow, within the function we have used the values #defined by ROWS and COLS that set the limits on the for loops. But, these #defines are just constants as far as the compiler is concerned, i.e. there is nothing to connect them to the array size within the function. row and col are local variables, of course. The formal parameter definition permits the compiler to determine the characteristics associated with the pointer value that will be passed at run time. We really don’t need the first dimension and, as will be seen later, there are occasions where we would prefer not to define it within the parameter definition, out of habit or consistency, I have not used it here. But, the second dimension must be used as has been shown in the expression for the parameter. The reason is that we need this in the evaluation of m_array[row][col] as has been described. While the parameter defines the data type (int in this case) and the automatic variables for row and column are defined in the for loops, only one value can be passed using a single parameter. In this case, that is the value of multi as noted in the call statement, i.e. the address of the first element, often referred to as a pointer to the array. Thus, the only way we have of informing the compiler of the 2nd dimension is by explicitly including it in the parameter definition. In fact, in general all dimensions of higher order than one are needed when dealing with multi-dimensional arrays. That is if we are talking about 3 dimensional arrays, the 2nd and 3rd dimension must be specified in the parameter definition. CHAPTER 8: Pointers to ArraysPointers, of course, can be "pointed at" any type of data object, including arrays. While that was evident when we discussed program 3.1, it is important to expand on how we do this when it comes to multi-dimensional arrays. To review, in Chapter 2 we stated that given an array of integers we could point an integer pointer at that array using: int *ptr; ptr = &my_array[0]; /* point our pointer at the first integer in our array */As we stated there, the type of the pointer variable must match the type of the first element of the array. In addition, we can use a pointer as a formal parameter of a function which is designed to manipulate an array. e.g. Given: int array[3] = {1, 5, 7}; void a_func(int *p);Some programmers might prefer to write the function prototype as: void a_func(int p[]);which would tend to inform others who might use this function that the function is designed to manipulate the elements of an array. Of course, in either case, what actually gets passed is the value of a pointer to the first element of the array, independent of which notation is used in the function prototype or definition. Note that if the array notation is used, there is no need to pass the actual dimension of the array since we are not passing the whole array, only the address to the first element. We now turn to the problem of the 2 dimensional array. As stated in the last chapter, C interprets a 2 dimensional array as an array of one dimensional arrays. That being the case, the first element of a 2 dimensional array of integers is a one dimensional array of integers. And a pointer to a two dimensional array of integers must be a pointer to that data type. One way of accomplishing this is through the use of the keyword "typedef". typedef assigns a new name to a specified data type. For example: typedef unsigned char byte;causes the name byte to mean type unsigned char. Hence byte b[10]; would be an array of unsigned characters.Note that in the typedef declaration, the word byte has replaced that which would normally be the name of our unsigned char. That is, the rule for using typedef is that the new name for the data type is the name used in the definition of the data type. Thus in: typedef int Array[10];Array becomes a data type for an array of 10 integers. i.e. Array my_arr; declares my_arr as an array of 10 integers and Array arr2d[5]; makes arr2d an array of 5 arrays of 10 integers each.

126

Page 127: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalAlso note that Array *p1d; makes p1d a pointer to an array of 10 integers. Because *p1d points to the same type as arr2d, assigning the address of the two dimensional array arr2d to p1d, the pointer to a one dimensional array of 10 integers is acceptable. i.e. p1d = &arr2d[0]; or p1d = arr2d; are both correct. Since the data type we use for our pointer is an array of 10 integers we would expect that incrementing p1d by 1 would change its value by 10*sizeof(int), which it does. That is, sizeof(*p1d) is 20. You can prove this to yourself by writing and running a simple short program. Now, while using typedef makes things clearer for the reader and easier on the programmer, it is not really necessary. What we need is a way of declaring a pointer like p1d without the need of the typedef keyword. It turns out that this can be done and that int (*p1d)[10];is the proper declaration, i.e. p1d here is a pointer to an array of 10 integers just as it was under the declaration using the Array type. Note that this is different from int *p1d[10];which would make p1d the name of an array of 10 pointers to type int.

CHAPTER 9: Pointers and Dynamic Allocation of MemoryThere are times when it is convenient to allocate memory at run time using malloc(), calloc(), or other allocation functions. Using this approach permits postponing the decision on the size of the memory block need to store an array, for example, until run time. Or it permits using a section of memory for the storage of an array of integers at one point in time, and then when that memory is no longer needed it can be freed up for other uses, such as the storage of an array of structures. When memory is allocated, the allocating function (such as malloc(), calloc(), etc.) returns a pointer. The type of this pointer depends on whether you are using an older K&R compiler or the newer ANSI type compiler. With the older compiler the type of the returned pointer is char, with the ANSI compiler it is void. If you are using an older compiler, and you want to allocate memory for an array of integers you will have to cast the char pointer returned to an integer pointer. For example, to allocate space for 10 integers we might write: int *iptr; iptr = (int *)malloc(10 * sizeof(int)); if (iptr == NULL) { .. ERROR ROUTINE GOES HERE .. }If you are using an ANSI compliant compiler, malloc() returns a void pointer and since a void pointer can be assigned to a pointer variable of any object type, the (int *) cast shown above is not needed. The array dimension can be determined at run time and is not needed at compile time. That is, the 10 above could be a variable read in from a data file or keyboard, or calculated based on some need, at run time. Because of the equivalence between array and pointer notation, once iptr has been assigned as above, one can use the array notation. For example, one could write: int k; for (k = 0; k < 10; k++) iptr[k] = 2;to set the values of all elements to 2. Even with a reasonably good understanding of pointers and arrays, one place the newcomer to C is likely to stumble at first is in the dynamic allocation of multi-dimensional arrays. In general, we would like to be able to access elements of such arrays using array notation, not pointer notation, wherever possible. Depending on the application we may or may not know both dimensions at compile time. This leads to a variety of ways to go about our task. As we have seen, when dynamically allocating a one dimensional array its dimension can be determined at run time. Now, when using dynamic allocation of higher order arrays, we never need to know the first dimension at compile time. Whether we need to know the higher dimensions depends on how we go about writing the code. Here I will discuss various methods of dynamically allocating room for 2 dimensional arrays of integers. First we will consider cases where the 2nd dimension is known at compile time.

127

Page 128: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalMETHOD 1:One way of dealing with the problem is through the use of the typedef keyword. To allocate a 2 dimensional array of integers recall that the following two notations result in the same object code being generated: multi[row][col] = 1; *(*(multi + row) + col) = 1;It is also true that the following two notations generate the same code: multi[row] *(multi + row)Since the one on the right must evaluate to a pointer, the array notation on the left must also evaluate to a pointer. In fact multi[0] will return a pointer to the first integer in the first row, multi[1] a pointer to the first integer of the second row, etc. Actually, multi[n] evaluates to a pointer to that array of integers that make up the n-th row of our 2 dimensional array. That is, multi can be thought of as an array of arrays and multi[n] as a pointer to the n-th array of this array of arrays. Here the word pointer is being used to represent an address value. While such usage is common in the literature, when reading such statements one must be careful to distinguish between the constant address of an array and a variable pointer which is a data object in itself. Consider now:

#include <stdio.h>#include <stdlib.h>#define COLS 5typedef int RowArray[COLS];RowArray *rptr;int main(void){ int nrows = 10; int row, col; rptr = malloc(nrows * COLS * sizeof(int)); for (row = 0; row < nrows; row++) { for (col = 0; col < COLS; col++) { rptr[row][col] = 17; } } return 0;} Here I have assumed an ANSI compiler so a cast on the void pointer returned by malloc() is not required. If you are using an older K&R compiler you will have to cast using: rptr = (RowArray *)malloc(.... etc.Using this approach, rptr has all the characteristics of an array name name, (except that rptr is modifiable), and array notation may be used throughout the rest of the program. That also means that if you intend to write a function to modify the array contents, you must use COLS as a part of the formal parameter in that function, just as we did when discussing the passing of two dimensional arrays to a function. METHOD 2:In the METHOD 1 above, rptr turned out to be a pointer to type "one dimensional array of COLS integers". It turns out that there is syntax which can be used for this type without the need of typedef. If we write: int (*xptr)[COLS];the variable xptr will have all the same characteristics as the variable rptr in METHOD 1 above, and we need not use the typedef keyword. Here xptr is a pointer to an array of integers and the size of that array is given by the #defined COLS. The parenthesis placement makes the pointer notation predominate, even though the array notation has higher precedence. i.e. had we written int *xptr[COLS];we would have defined xptr as an array of pointers holding the number of pointers equal to that #defined by COLS. That is not the same thing at all. However, arrays of pointers have their use in the dynamic allocation of two dimensional arrays, as will be seen in the next 2 methods. METHOD 3:Consider the case where we do not know the number of elements in each row at compile time, i.e. both the number of rows and number of columns must be determined at run time. One way of doing this would be to create an array of pointers to type int and then allocate space for each row and point these pointers at each row. Consider:

128

Page 129: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal#include <stdio.h>#include <stdlib.h>int main(void){ int nrows = 5; /* Both nrows and ncols could be evaluated */ int ncols = 10; /* or read in at run time */ int row; int **rowptr; rowptr = malloc(nrows * sizeof(int *)); if (rowptr == NULL) { puts("\nFailure to allocate room for row pointers.\n"); exit(0); } printf("\n\n\nIndex Pointer(hex) Pointer(dec) Diff.(dec)"); for (row = 0; row < nrows; row++) { rowptr[row] = malloc(ncols * sizeof(int)); if (rowptr[row] == NULL) { printf("\nFailure to allocate for row[%d]\n",row); exit(0); } printf("\n%d %p %d", row, rowptr[row], rowptr[row]); if (row > 0) printf(" %d",(int)(rowptr[row] - rowptr[row-1])); } return 0;}In the above code rowptr is a pointer to pointer to type int. In this case it points to the first element of an array of pointers to type int. Consider the number of calls to malloc(): To get the array of pointers 1 call To get space for the rows 5 calls ----- Total 6 callsIf you choose to use this approach note that while you can use the array notation to access individual elements of the array, e.g. rowptr[row][col] = 17;, it does not mean that the data in the "two dimensional array" is contiguous in memory. You can, however, use the array notation just as if it were a continuous block of memory. For example, you can write: rowptr[row][col] = 176;just as if rowptr were the name of a two dimensional array created at compile time. Of course row and col must be within the bounds of the array you have created, just as with an array created at compile time. If you want to have a contiguous block of memory dedicated to the storage of the elements in the array you can do it as follows: METHOD 4:In this method we allocate a block of memory to hold the whole array first. We then create an array of pointers to point to each row. Thus even though the array of pointers is being used, the actual array in memory is contiguous. The code looks like this: #include <stdio.h>#include <stdlib.h>int main(void){ int **rptr; int *aptr; int *testptr; int k; int nrows = 5; /* Both nrows and ncols could be evaluated */ int ncols = 8; /* or read in at run time */ int row, col; /* we now allocate the memory for the array */ aptr = malloc(nrows * ncols * sizeof(int));

129

Page 130: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal if (aptr == NULL) { puts("\nFailure to allocate room for the array"); exit(0); } /* next we allocate room for the pointers to the rows */ rptr = malloc(nrows * sizeof(int *)); if (rptr == NULL) { puts("\nFailure to allocate room for pointers"); exit(0); } /* and now we 'point' the pointers */ for (k = 0; k < nrows; k++) { rptr[k] = aptr + (k * ncols); } /* Now we illustrate how the row pointers are incremented */ printf("\n\nIllustrating how row pointers are incremented"); printf("\n\nIndex Pointer(hex) Diff.(dec)");

for (row = 0; row < nrows; row++) { printf("\n%d %p", row, rptr[row]); if (row > 0) printf(" %d",(rptr[row] - rptr[row-1])); } printf("\n\nAnd now we print out the array\n"); for (row = 0; row < nrows; row++) { for (col = 0; col < ncols; col++) { rptr[row][col] = row + col; printf("%d ", rptr[row][col]); } putchar('\n'); } puts("\n"); /* and here we illustrate that we are, in fact, dealing with a 2 dimensional array in a contiguous block of memory. */ printf("And now we demonstrate that they are contiguous in memory\n"); testptr = aptr; for (row = 0; row < nrows; row++) { for (col = 0; col < ncols; col++) { printf("%d ", *(testptr++)); } putchar('\n'); } return 0;}Consider again, the number of calls to malloc() To get room for the array itself 1 call To get room for the array of ptrs 1 call ---- Total 2 calls

Now, each call to malloc() creates additional space overhead since malloc() is generally implemented by the operating system forming a linked list which contains data concerning the size of the block. But, more importantly, with large arrays (several hundred rows) keeping track of what needs to be freed when the time comes can be more cumbersome. This, combined with the contiguousness of the data block that permits initialization to all zeroes using memset() would seem to make the second alternative the preferred one. As a final example on multidimensional arrays we will illustrate the dynamic allocation of a three dimensional array. This example will illustrate one more thing to watch when doing this kind of allocation. For reasons cited above we will use the approach outlined in alternative two. Consider the following code: /* Program 9.4 from PTRTUT10.HTM 6/13/97 */#include <stdio.h>#include <stdlib.h>#include <stddef.h>

130

Page 131: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalint X_DIM=16;int Y_DIM=5;int Z_DIM=3;int main(void){ char *space; char ***Arr3D; int y, z; ptrdiff_t diff; /* first we set aside space for the array itself */ space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char)); /* next we allocate space of an array of pointers, each to eventually point to the first element of a 2 dimensional array of pointers to pointers */ Arr3D = malloc(Z_DIM * sizeof(char **)); /* and for each of these we assign a pointer to a newly allocated array of pointers to a row */ for (z = 0; z < Z_DIM; z++) { Arr3D[z] = malloc(Y_DIM * sizeof(char *)); /* and for each space in this array we put a pointer to the first element of each row in the array space originally allocated */ for (y = 0; y < Y_DIM; y++) { Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM); } } /* And, now we check each address in our 3D array to see if the indexing of the Arr3d pointer leads through in a continuous manner */ for (z = 0; z < Z_DIM; z++) { printf("Location of array %d is %p\n", z, *Arr3D[z]); for ( y = 0; y < Y_DIM; y++) { printf(" Array %d and Row %d starts at %p", z, y, Arr3D[z][y]); diff = Arr3D[z][y] - space; printf(" diff = %d ",diff); printf(" z = %d y = %d\n", z, y); } } return 0;}

If you have followed this tutorial up to this point you should have no problem deciphering the above on the basis of the comments alone. There are a couple of points that should be made however. Let's start with the line which reads: Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);Note that here space is a character pointer, which is the same type as Arr3D[z][y]. It is important that when adding an integer, such as that obtained by evaluation of the expression (z*(X_DIM * Y_DIM) + y*X_DIM), to a pointer, the result is a new pointer value. And when assigning pointer values to pointer variables the data types of the value and variable must match. CHAPTER 10: Pointers to FunctionsUp to this point we have been discussing pointers to data objects. C also permits the declaration of pointers to functions. Pointers to functions have a variety of uses and some of them will be discussed here. Consider the following real problem. You want to write a function that is capable of sorting virtually any collection of data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes.

131

Page 132: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya RimalSedgewick [1] has described the bubble sort using C code by setting up a function which when passed a pointer to the array would sort it. If we call that function bubble(), a sort program is described by bubble_1.c, which follows: /* Program bubble_1.c from PTRTUT10.HTM 6/13/97 */#include <stdio.h>int arr[10] = { 3,6,1,2,3,8,4,1,7,2};void bubble(int a[], int N);int main(void){ int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0;}void bubble(int a[], int N){ int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (a[j-1] > a[j]) { t = a[j-1]; a[j-1] = a[j]; a[j] = t; } } }}

The bubble sort is one of the simpler sorts. The algorithm scans the array from the second to the last element comparing each element with the one which precedes it. If the one that precedes it is larger than the current element, the two are swapped so the larger one is closer to the end of the array. On the first pass, this results in the largest element ending up at the end of the array. The array is now limited to all elements except the last and the process repeated. This puts the next largest element at a point preceding the largest element. The process is repeated for a number of times equal to the number of elements minus 1. The end result is a sorted array. Here our function is designed to sort an array of integers. Thus in line 1 we are comparing integers and in lines 2 through 4 we are using temporary integer storage to store integers. What we want to do now is see if we can convert this code so we can use any data type, i.e. not be restricted to integers. At the same time we don't want to have to analyze our algorithm and the code associated with it each time we use it. We start by removing the comparison from within the function bubble() so as to make it relatively easy to modify the comparison function without having to re-write portions related to the actual algorithm. This results in bubble_2.c:

/* Program bubble_2.c from PTRTUT10.HTM 6/13/97 */ /* Separating the comparison function */#include <stdio.h>int arr[10] = { 3,6,1,2,3,8,4,1,7,2};void bubble(int a[], int N);int compare(int m, int n);int main(void){ int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n');

132

Page 133: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0;}void bubble(int a[], int N){ int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare(a[j-1], a[j])) { t = a[j-1]; a[j-1] = a[j]; a[j] = t; } } }}int compare(int m, int n){ return (m > n);}If our goal is to make our sort routine data type independent, one way of doing this is to use pointers to type void to point to the data instead of using the integer data type. As a start in that direction let's modify a few things in the above so that pointers can be used. To begin with, we'll stick with pointers to type integer. /* Program bubble_3.c from PTRTUT10.HTM 6/13/97 */#include <stdio.h>int arr[10] = { 3,6,1,2,3,8,4,1,7,2};

void bubble(int *p, int N);int compare(int *m, int *n);int main(void){ int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0;}void bubble(int *p, int N){ int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare(&p[j-1], &p[j])) { t = p[j-1]; p[j-1] = p[j]; p[j] = t; } } }}int compare(int *m, int *n){ return (*m > *n);}Note the changes. We are now passing a pointer to an integer (or array of integers) to bubble(). And from within bubble we are passing pointers to the elements of the array that we want to compare to our comparison function. And, of course we are dereferencing these pointer in our compare() function in order to make the actual comparison. Our next step will be to convert the pointers in bubble() to pointers to type void so that that function will become more type insensitive. This is shown in bubble_4. /* Program bubble_4.c from PTRTUT10,HTM 6/13/97 */#include <stdio.h>int arr[10] = { 3,6,1,2,3,8,4,1,7,2};void bubble(int *p, int N);int compare(void *m, void *n);int main(void){ int i; putchar('\n'); for (i = 0; i < 10; i++) {

133

Page 134: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0;}

void bubble(int *p, int N){ int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare((void *)&p[j-1], (void *)&p[j])) { t = p[j-1]; p[j-1] = p[j]; p[j] = t; } } }}int compare(void *m, void *n){ int *m1, *n1; m1 = (int *)m; n1 = (int *)n; return (*m1 > *n1);}Note that, in doing this, in compare() we had to introduce the casting of the void pointer types passed to the actual type being sorted. But, as we'll see later that's okay. And since what is being passed to bubble() is still a pointer to an array of integers, we had to cast these pointers to void pointers when we passed them as parameters in our call to compare(). We now address the problem of what we pass to bubble(). We want to make the first parameter of that function a void pointer also. But, that means that within bubble() we need to do something about the variable t, which is currently an integer. Also, where we use t = p[j-1]; the type of p[j-1] needs to be known in order to know how many bytes to copy to the variable t (or whatever we replace t with). Currently, in bubble_4.c, knowledge within bubble() as to the type of the data being sorted (and hence the size of each individual element) is obtained from the fact that the first parameter is a pointer to type integer. If we are going to be able to use bubble() to sort any type of data, we need to make that pointer a pointer to type void. But, in doing so we are going to lose information concerning the size of individual elements within the array. So, in bubble_5.c we will add a separate parameter to handle this size information. These changes, from bubble4.c to bubble5.c are, perhaps, a bit more extensive than those we have made in the past. So, compare the two modules carefully for differences. /* Program bubble_5.c from PTRTUT10.HTM 6/13/97 */#include <stdio.h>#include <string.h>long arr[10] = { 3,6,1,2,3,8,4,1,7,2};void bubble(void *p, size_t width, int N);int compare(void *m, void *n);int main(void){ int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr, sizeof(long), 10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%ld ", arr[i]); } return 0;}void bubble(void *p, size_t width, int N){ int i, j;

134

Page 135: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal unsigned char buf[4]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { if (compare((void *)(bp + width*(j-1)), (void *)(bp + j*width))) /* 1 */ {/* t = p[j-1]; */ memcpy(buf, bp + width*(j-1), width);/* p[j-1] = p[j]; */ memcpy(bp + width*(j-1), bp + j*width , width);/* p[j] = t; */ memcpy(bp + j*width, buf, width); } } }}int compare(void *m, void *n){ long *m1, *n1; m1 = (long *)m; n1 = (long *)n; return (*m1 > *n1);}Note that I have changed the data type of the array from int to long to illustrate the changes needed in the compare() function. Within bubble() I've done away with the variable t (which we would have had to change from type int to type long). I have added a buffer of size 4 unsigned characters, which is the size needed to hold a long (this will change again in future modifications to this code). The unsigned character pointer *bp is used to point to the base of the array to be sorted, i.e. to the first element of that array. We also had to modify what we passed to compare(), and how we do the swapping of elements that the comparison indicates need swapping. Use of memcpy() and pointer notation instead of array notation work towards this reduction in type sensitivity. Again, making a careful comparison of bubble5.c with bubble4.c can result in improved understanding of what is happening and why. We move now to bubble6.c where we use the same function bubble() that we used in bubble5.c to sort strings instead of long integers. Of course we have to change the comparison function since the means by which strings are compared is different from that by which long integers are compared. And,in bubble6.c we have deleted the lines within bubble() that were commented out in bubble5.c. /* Program bubble_6.c from PTRTUT10.HTM 6/13/97 */#include <stdio.h>#include <string.h>#define MAX_BUF 256char arr2[5][20] = { "Mickey Mouse", "Donald Duck", "Minnie Mouse", "Goofy", "Ted Jensen" };void bubble(void *p, int width, int N);int compare(void *m, void *n);int main(void){ int i; putchar('\n'); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } bubble(arr2, 20, 5); putchar('\n\n'); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } return 0;}

135

Page 136: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimalvoid bubble(void *p, int width, int N){ int i, j, k; unsigned char buf[MAX_BUF]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { k = compare((void *)(bp + width*(j-1)), (void *)(bp + j*width)); if (k > 0) { memcpy(buf, bp + width*(j-1), width); memcpy(bp + width*(j-1), bp + j*width , width); memcpy(bp + j*width, buf, width); } } }}int compare(void *m, void *n){ char *m1 = m; char *n1 = n; return (strcmp(m1,n1));} But, the fact that bubble() was unchanged from that used in bubble5.c indicates that that function is capable of sorting a wide variety of data types. What is left to do is to pass to bubble() the name of the comparison function we want to use so that it can be truly universal. Just as the name of an array is the address of the first element of the array in the data segment, the name of a function decays into the address of that function in the code segment. Thus we need to use a pointer to a function. In this case the comparison function. Pointers to functions must match the functions pointed to in the number and types of the parameters and the type of the return value. In our case, we declare our function pointer as: int (*fptr)(const void *p1, const void *p2);Note that were we to write: int *fptr(const void *p1, const void *p2);we would have a function prototype for a function which returned a pointer to type int. That is because in C the parenthesis () operator have a higher precedence than the pointer * operator. By putting the parenthesis around the string (*fptr) we indicate that we are declaring a function pointer. We now modify our declaration of bubble() by adding, as its 4th parameter, a function pointer of the proper type. It's function prototype becomes: void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *));When we call the bubble(), we insert the name of the comparison function that we want to use. bubble7.c illustrate how this approach permits the use of the same bubble() function for sorting different types of data.

/* Program bubble_7.c from PTRTUT10.HTM 6/10/97 */#include <stdio.h>#include <string.h>#define MAX_BUF 256long arr[10] = { 3,6,1,2,3,8,4,1,7,2};char arr2[5][20] = { "Mickey Mouse", "Donald Duck", "Minnie Mouse", "Goofy", "Ted Jensen" };void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *));int compare_string(const void *m, const void *n);int compare_long(const void *m, const void *n);int main(void){ int i; puts("\nBefore Sorting:\n"); for (i = 0; i < 10; i++) { /* show the long ints */

136

Page 137: wapnepal.com.np€¦  · Web viewThe object of this course is to acquaint the students with the basic principles of programming and development of software systems. It encompasses

BE Computer Programming in C Yagya Rimal printf("%ld ",arr[i]); } puts("\n"); for (i = 0; i < 5; i++) { /* show the strings */ printf("%s\n", arr2[i]); } bubble(arr, 4, 10, compare_long); /* sort the longs */ bubble(arr2, 20, 5, compare_string); /* sort the strings */ puts("\n\nAfter Sorting:\n"); for (i = 0; i < 10; i++) { /* show the sorted longs */ printf("%d ",arr[i]); } puts("\n"); for (i = 0; i < 5; i++){ /* show the sorted strings */ printf("%s\n", arr2[i]); } return 0;}void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *)){ int i, j, k; unsigned char buf[MAX_BUF]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j <= i; j++) { k = fptr((void *)(bp + width*(j-1)), (void *)(bp + j*width)); if (k > 0) { memcpy(buf, bp + width*(j-1), width); memcpy(bp + width*(j-1), bp + j*width , width); memcpy(bp + j*width, buf, width); } } }}int compare_string(const void *m, const void *n){ char *m1 = (char *)m; char *n1 = (char *)n; return (strcmp(m1,n1));}int compare_long(const void *m, const void *n){ long *m1, *n1; m1 = (long *)m; n1 = (long *)n; return (*m1 > *n1);}

137


Recommended