Search This Blog

Sunday, February 28, 2010

FUNDAMENTALS OF COMPUTING AND PROGRAMMING

Introduction
General-purpose computer – the electronic chips contain programs that allow the user to perform a range of complex processes and calculations.
Computer is an electronic device which capable of solving problems and manipulating data. A general-purpose computer is defined as an electronic device that:
· operates under the control of a set of instructions, called a program, that is stored in its memory
· accepts data supplied by a user
· manipulates the data according to the programmed instructions
· produces the results (information)
· stores the results (information) for future use
A computer is an electronic device, operating under the control of instructions stored in its own memory, that can accept data (input), process the data according to specified rules (process), produce results (output), and store the results (storage) for future use

The Information Processing Cycle


Using a computer to convert data into useful information is referred to as information processing (also called data processing). Processing data into information involves four basic functions:

· input – data entered into a computer for processing
· processing – the manipulation of data according to program instructions
· output – the creation of information resulting from processing
· storage – the retention of processed data on a storage medium for future use

Collectively, these steps are known as the information processing cycle.

Characteristics of Computers
Speed
Computers operate with lightening-like speed, and processing speeds are increasing as new and improved models are introduced.
Contemporary personal computers are capable of executing billions of instructions per second and larger computers, such as supercomputers, can execute trillions of instructions per second.
Accuracy
Computers are extremely accurate when accurate programs and data are entered and processed correctly. The popular expression garbage-in, garbage-out (GIGO) means that if inaccurate programs and data are entered into a computer for processing, the resulting output will also be inaccurate.
Diligence
- A computer is a lack of concentration.
- It can work for hours without creating any error
- Due to this capability it overpowers human being in routine type of work.
Versatility
Computers are perhaps the most versatile of all machines or devices. They can perform a variety of personal, business, and scientific applications. Computers are frequently used by families, banks, retailers, manufacturers, schools, government agencies, hospitals, and scientific organizations for a variety of useful and important applications.
Storage
A computer is capable of accepting and storing programs and data. Computers can store huge amounts of data and, once stored in a computer, users can access programs and data again and again to process different data.
Power of Remembering Any amount of information can be stored in computer and recalled as long as you require it, for any numbers of years.
It depends entirely upon you how much data you want to store in a computer and when to lose or retrieve these data.

No Feeling
- It does not have feelings,
- It does not get tired even after long hours of work.
No IQ (intelligence quotient)
Computer is a dumb machine and it cannot do any work without instruction from the user and it cannot take its own decision as you can
Communications
Most modern computers contain special equipment and programs that allow them to communicate with other computers through telephone lines, cable connections, and satellites. Computers having this capability are often linked together so users can share programs, data, information, and equipment such as a printer. The structure in which computers are linked together is called a network
Evolution of Computers
The abacus was an early aid for mathematical computations. Its only value is that it aids the memory of the human performing the calculation. A skilled abacus operator can work on addition and subtraction problems at the speed of a person equipped with a hand calculator (multiplication and division are slower). The abacus is often wrongly attributed to China. In fact, the oldest surviving abacus was used in 300 B.C. by the Babylonians. The abacus is still in use today, principally in the Far East.
In 1617 an eccentric Scotsman named John Napier invented logarithms, which are a technology that allows multiplication to be performed via addition. The magic ingredient is the logarithm of each operand, which was originally obtained from a printed table. But Napier also invented an alternative to tables, where the logarithm values were carved on ivory sticks which are now called Napier’s Bones.
Napier’s invention led directly to the slide rule, first built in England in 1632 and still in use in the 1960’s by the NASA engineers of the Mercury, Gemini, and Apollo programs which landed men on the moon.
Leonardo da Vinci (1452-1519) made drawings of gear-driven calculating machines but apparently never built any.
The first gear-driven calculating machine to actually be built was probably the calculating clock, so named by its inventor, the German professor Wilhelm Schickard in 1623. This device got little publicity because Schickard died soon afterward in the bubonic plague.
In 1642 Blaise Pascal, at age 19, invented the Pascaline as an aid for his father who was a tax collector. Pascal built 50 of this gear-driven one-function calculator (it could only add) but couldn’t sell many because of their exorbitant cost and because they really weren’t that accurate (at that time it was not possible to fabricate gears with the required precision).
Just a few years after Pascal, the German Gottfried Wilhelm Leibniz (co-inventor with Newton of calculus) managed to build a four-function (addition, subtraction, multiplication, and division) calculator that he called the stepped reckoner
In 1801 the Frenchman Joseph Marie Jacquard invented a power loom that could base its weave (and hence the design on the fabric) upon a pattern automatically read from punched wooden cards, held together in a long row by rope. Descendents of these punched cards have been in use ever since
By 1822 the English mathematician Charles Babbage was proposing a steam driven calculating machine the size of a room, which he called the Difference Engine. This machine would be able to compute tables of numbers, such as logarithm tables. He obtained government funding for this project due to the importance of numeric tables in ocean navigation.
And by then was on to his next brainstorm, which he called the Analytic Engine. This device, large as a house and powered by 6 steam engines, would be more general purpose in nature because it would be programmable, thanks to the punched card technology of Jacquard. But it was Babbage who made an important intellectual leap regarding the punched cards. Hollerith’s invention, known as the Hollerith desk, consisted of a card reader which sensed the holes in the cards, a gear driven mechanism which could count
Hollerith built a company, the Tabulating Machine Company which, after a few buyouts, eventually became International Business Machines, known today as IBM.
Mark I computer which was built as a partnership between Harvard and IBM in 1944. This was the first programmable digital computer made in the U.S. But it was not a purely electronic computer. Instead the Mark I was constructed out of switches, relays, rotating shafts, and clutches. The machine weighed 5 tons, incorporated 500 miles of wire, was 8 feet tall and 51 feet long, and had a 50 ft rotating shaft running its length, turned by a 5 horsepower electric motor. The Mark I ran non-stop for 15 years,
ENIAC, which stood for Electronic Numerical Integrator and Calculator. ENIAC was built at the University of Pennsylvania between 1943 and 1945 by two professors, John Mauchly and the 24 year old J. Presper Eckert
Once ENIAC was finished and proved worthy of the cost of its development, its designers set about to eliminate the obnoxious fact that reprogramming the computer required a physical modification of all the patch cords and switches. It took days to change ENIAC’s program. Eckert and Mauchly’s next teamed up with the mathematician John von Neumann to design EDVAC, which pioneered the stored program. Because he was the first to publish a description of this new computer
By the end of the 1950’s computers were no longer one-of-a-kind hand built devices owned only by universities and government research labs. Eckert and Mauchly left the University of Pennsylvania over a dispute about who owned the patents for their invention. They decided to set up their own company. Their first product was the famous UNIVAC computer, the first commercial (that is, mass produced) computer. In the 50’s, UNIVAC (a contraction of “Universal Automatic Computer”) was the household word for “computer” just as “Kleenex” is for “tissue”. The first UNIVAC was sold, appropriately enough, to the Census bureau. UNIVAC was also the first computer to employ magnetic tape.
A microprocessor (uP) is a computer that is fabricated on an integrated circuit (IC). Computers had been around for 20 years before the first microprocessor was developed at Intel in 1971.
1642 – Blaise Pascal invents mechanical calculator (counting device)
1830- Charles’s Babbages “Difference Engine”
First Steam-powered “Analytical Engine”
1880’s- John H. Patterson’s Mechanical cash register (NCR)
First applications for computing devices
1930’s- Claude Shannon: Suggests use of Binary system for use with electronic circuits
1940s- John Von Neumann:Proposes reconfigurable computing by storing programs in memory
1940s – 1950s: First electronic computers,
-Vacuum tubes & mechanical relays: UNIVAC, ENIAC
- 30 tons
- 150KWatt
- 80 bytes of memory
ILLIAC (Metze et. al. play Illinois fight song on accumulator bit. – first computer music)
1948- John Bardeen, Walter Brattain, William Schockley file patent on invention of the transistor
1958- Jack Kilby: introduces concept of “Integrated Circuit”
1960s- Computers begin to use transistors.
1965- Gordon Moore
Observes that every chip produced contained roughly twice as much capacity as its predecessor and that chips new generations of chips were being released every 18-24 months.


Late 1960s- IBM mainframes
- Powerful, centralized CPUs with terminals
- Age of the “big iron”
1970s- DEC PDP-11s
- Low-cost Mini-computers
- Age of the “Vaxen”
1974- Microprocessors
- Intel introduces the 8080 (a “toy”)
- Bill Gates sophmore year at Harvard
1974- Altair 8800
- 8080 CPU
- Affordable ($379 kit)
- No screen (LEDs on front panel)
- No keyboard (DIP switches on front panel)
- No storage
- 4k memory.
Bill Gates & Paul Allen start writing BASIC
1977- Apple II, Commodore-64
1980- IBM meets with Bill Gates to license BASIC/MSDOS (QDOS)
1981- IBM Personal Computer:
- 16-bit microprocessor: 4.77 MHz 8088
- ROM BASIC,
- cassette interface,
- 360k floppy (optional)
- DOS 1.0
1982- Illiac-IV
1983- Low cost computing
- 10 MByte Hard disk costs $3000
- 640KB of Memory costs $1000
Compaq introduces “Portable Computing”
1984- Macintosh: GUI based on work at Xerox Parc
IBM Introduces PC-AT: 80286-based system.
Record year for IBM.
Lockwood buys first 8088 computer.
1985- First 32-bit 80×86 CPUs
Intel introduces 80386
Address up to 4 Gbytes of memory.
1986- First 32-bit 80×86 Systems
Compaq introduces first 80386-based system
1989- Intel introduces 80486, includes math co-processor (FPU)
1992- AMD/Cyrix 486 (Compatible CPUs)Intel Pentium (64-bit memory bus)
1996- Use of Reduced Instruction Set Computer (RISC) core to exectute 80×86 instructions - AMD K5 (RISC Ops = ROPS)
- Intel Pentium Pro


Computer Generations
1-First Generation Computers
First generation computers used Thermion valves. These computers were large in size and writing programs on them was difficult.Some of the computers of this generation were:
ENIAC : It was named Electronic Numerical Integrator And Calculator (ENIAC). Today your favorite computer is many times as powerful as ENIAC, still size is very small.
EDVAC: It stands for Electronic Discrete Variable Automatic Computer and was developed in 1950. The advantages is storing and doing logical decision internally.
Other Important Computers of First Generation:
EDSAC: ( Electronic Delay Storage Automatic Computer )
UNIVAC-1.

Limitations of First Generation Computer:
· The operating speed was quite slow.
· Power consumption was very high.
· It required large space for installation.
· The programming capability was quite low.
2-Second Generation Computers
l Around 1955 a device called Transistor replaced the bulky electric tubes in the first generation computer. They have no filament and require no heating. Manufacturing cost was also very low. Thus the size of the computer got reduced considerably.
l It is in the second generation that the concept of Central Processing Unit (CPU), memory, programming language and input and output units were developed. The programming languages such as COBOL, FORTRAN were developed during this period. Some of the computers of the Second Generation were:
- IBM 1620: Its size was smaller as compared to First Generation computers and mostly used for scientific purpose.
- IBM 1401: Its size was small to medium and used for business applications.
- CDC 3600: Its size was large and is used for scientific purposes.
3. Third Generation Computers
was introduced in 1964. They used Integrated Circuits (ICs). Some of the computers developed during this period were: IBM-360, ICL-1900, IBM-370, and VAX-750.
- Higher level language such as BASIC was developed during this period.
- Computers of this generations were small in size, low cost, large memory and processing speed is very high.
4-Fourth Generation Computers( present day computers) .
It uses large scale Integrated Circuits (LSIC) built on a single silicon chip called microprocessors. Due to the development of microprocessor it is possible to place computer’s central processing unit (CPU) on single chip. These computers are called microcomputers.
5-Fifth Generation Computer
was introduced in 1990s . The speed is extremely high and it can perform parallel processing. The concept of Artificial intelligence has been introduced to allow the computer to take its own decision. It is still in a developmental stage.
Classification of Computers
Analog computer:
Digital computer:
1-Microcomputer.
Microcomputer is at the lowest end of the computer range in terms of speed and storage capacity. Its CPU is a microprocessor. The most common application of personal computers (PC) is in this category. The PC supports a number of input and output devices. Examples of microcomputer are IBM PC, PC-AT

- 1973: Xerox Alto
- 1975: Altair
- 1978: Apple II
- 1981: IBM PC (5150)
- 1983: Apple Macintosh

2-Mini Computer.
The mini computer is used in multi-user system in which various users can work at the same time. This type of computer is generally used for processing large volume of data in an organization. They are also used as servers in Local Area Networks (LAN).
3-Mainframes.
These types of computers are generally 32-bit microprocessors. They operate at very high speed, have very large storage capacity and can handle the work load of many users. They are generally used in centralized databases. They are also used as controlling nodes in Wide Area Networks (WAN).
Example of mainframes are DEC, ICL and IBM 3000 series.
4-Supercomputer.
They are the fastest and most expensive machines. They have high processing speed compared to other computers. They have also multiprocessing technique. One of the ways in which supercomputers are built is by interconnecting hundreds of microprocessors.
Supercomputers are mainly being used for whether forecasting, biomedical research, remote
sensing, aircraft design and other areas of science and technology. Examples of supercomputers
are CRAY YMP, CRAY2, NEC SX-3, CRAY XMP and PARAM from India.

Categories of Computers
Rapid advances in computer technology often blur the differences among types of computers, and industry professionals may disagree on how computers should be categorized. Typically, they use criteria based on differences in usage, size, speed, processing capabilities, and price, resulting in the following categories. For an overview, see Table 1-1.
Personal Computers
A personal computer (PC) is a self-contained computer capable of input, processing, output, and storage. A personal computer is designed to be a single-user computer and must have at least one input device, one output device, a processor, and memory. The three major groups of PCs are desktop computers, portable computers, and handheld computers.
Desktop Computers A desktop computer is a PC designed to allow the system unit, input devices, output devices, and other connected devices to fit on top of, beside, or under a user’s desk or table. This type of computer may be used in the home, a home office, a library, or a corporate setting.
Portable Computers A portable computer is a PC small enough to be moved around easily. As the name suggests, a laptop computer fits comfortably on the lap. As laptop computers have decreased in size, this type of computer is now more commonly referred to as a notebook computer. Manufacturers recently began introducing a new type of computer called the tablet PC, which has a liquid crystal display (LCD) screen on which the user can write using a special-purpose pen, or stylus. Tablet PCs rely on digital ink technology that allows the user to write on the screen. Another type of portable computer, called a wearable computer, is worn somewhere on the body, thereby providing a user with access to mobile computing capabilities and information via the Internet.
Did You Know? In 1974, Micro Instrumentation Telemetry Systems (MITS) began selling the Altair personal computer, widely regarded as the world’s first PC, as a mail-order kit. Buyers were required to assemble the components.
Handheld Computers An even smaller type of personal computer that can fit into the hand is known as a handheld computer (also called simply handheld, pocket PC, or Palmtop). In recent years, a type of handheld computer called a personal digital assistant (PDA) has become widely used for performing calculations, keeping track of schedules, making appointments, and writing memos. Some handheld computers are Internet-enabled, meaning they can access the Internet without wire connections. For example, a smartphone is a cell phone that connects to the Internet to allow users to transmit and receive e-mail messages, send text messages and pictures, and browse through Web sites on the phone display screen.
Workstations
A workstation is a high-performance single-user computer with advanced input, output, and storage components that can be networked with other workstations and larger computers. Workstations are typically used for complex applications that require considerable computing power and high-quality graphics resolution, such as computer-aided design (CAD), computer-assisted manufacturing (CAM), desktop publishing, and software development.
Midrange Servers
Linked computers and terminals are typically connected to a larger and more powerful computer called a network server, sometimes referred to as a host computer. Although the size and capacity of network servers vary considerably, most are midrange rather than large mainframe computers (discussed later).
Ø Midrange server – formerly known as a minicomputer, a midrange server is a powerful computer capable of accommodating hundreds of client computers or terminals (users) at the same time.
Ø Terminal – a device consisting of only a monitor and keyboard, with no processing capability of its own.
Mainframe Computers
Larger, more powerful, and more expensive than midrange servers, a mainframe computer is capable of accommodating hundreds of network users performing different computing tasks. These computers are useful for dealing with large, ever-changing collections of data that can be accessed by many users simultaneously. Government agencies, banks, universities, and insurance companies use mainframes to handle millions of transactions each day.
Supercomputers
A supercomputer is the fastest, most powerful, and most expensive of all computers. Many are capable of performing trillions of calculations in a single second. Primary applications include weather forecasting, comparing DNA sequences, creating artificially intelligent robots, and performing financial analyses.
Did You Know? The fastest computer in the world is IBM’s latest supercomputer, named the BlueGene/L. Housed at the Lawrence Livermore National Laboratory, it can perform up to 280.6 trillion calculations in one second. The next system, Blue Gene/P, scheduled for completion in 2008, is expected to have a processing speed of 1 quadrillion calculations per second.


Computer Hardware: An Overview
Hardware includes all of the physical components that comprise the computer and other devices connected to it, such as the keyboard or monitor. These connected devices are referred to as peripheral devices because they are outside, or peripheral to, the computer.
Hardware devices are grouped into the following categories:

- system unit
- input devices
- output devices
- storage devices
- communications devices
The System Unit The system unit is a relatively small plastic or metal cabinet housing the electronic components that process data into information. Inside the cabinet is the main circuit board, called the motherboard (Figure 1-7), which provides for the installation and connection of other electronic components. The main components of the motherboard include: central processing unit (CPU), also called the processor, which consists of electronic chips that read, interpret, and execute the instructions that operate the computer and perform specific computing tasks.
memory, also called primary storage, which consists of small electronic chips that provide temporary storage for instructions and data during processing.
Input Devices An input device is a hardware device that allows users to enter program instructions, data, and commands into a computer. Common input devices are the keyboard, mouse, and microphone.
Output Devices An output device is a device that makes information available to the user. Some output devices produce output in hardcopy (tangible) form, while other output devices produce output in softcopy (intangible) form that can be viewed, but not physically handled.
Storage Devices Unlike memory that stores instructions and data temporarily during processing, a storage device, often called secondary storage, provides for the permanent storage of programs, data, and information that can be reused.
Communications Devices A communications device makes it possible for a user to communicate with another computer and to exchange instructions, data, and information with other computer users. The most popular communications device is a modem, an electronic device capable of converting computer-readable information into a form that communications systems, such as standard telephone lines, can transmit and receive.
The Central Processing Unit


Every computer contains a central processing unit (CPU). The CPU of larger computers often spans several separate microprocessor chips and various circuit boards, whereas in a personal computer the CPU is a single chip. This microprocessor chip is a small electronic device consisting of tiny transistors and other circuit parts on a piece of semiconductor material.
Recall from Chapter 1 that the CPU, or microprocessor, is often referred to as the “brain” of a personal computer system because it interprets and executes the instructions for most computer operations. The CPU consists of a control unit, an arithmetic/logic unit (ALU), and registers (see Figure 2-13).
These components of the CPU perform four basic operations that are collectively called a machine cycle. The machine cycle includes fetching an instruction, decoding the instruction, executing the instruction, and storing the result (see Figure 2-14). The machine cycle is the same for all types of computers.
Did You Know? Intel’s first microprocessor, the 4004, was introduced in 1971. It contained 2,300 transistors. Today’s Pentium 4 processor, by contrast, contains 55 million transistors.
Control Unit The control unit directs and coordinates the overall operation of the computer system. It acts as a traffic officer, signaling to other parts of the computer system what they are to do. It interprets program instructions and then initiates the action needed to carry them out. These are the fetching and decoding steps of the machine cycle. Fetching means retrieving an instruction or data from memory. Decoding means interpreting or translating the instruction into strings of binary digits (bytes) the computer understands. The time required to fetch and decode an instruction is called instruction time, or I-time.
Arithmetic/Logic Unit The arithmetic/logic unit (ALU) is the part of the CPU that performs the executing step of the machine cycle. Executing means carrying out the instructions and performing arithmetic and logical operations on the data. The arithmetic operations the ALU can perform are addition, subtraction, multiplication, and division. The ALU can also perform logical operations, such as comparing data items.
Registers To speed up processing, the ALU uses registers (temporary storage locations) to hold instructions and data. This is the storing step of the machine cycle. Storing means writing or recording the result to memory. The time required to execute and store an instruction is called execution time, or E-time.
Various kinds of registers are used, each serving a specific purpose. Once processing begins, an instruction register holds instructions currently being executed. A data register holds the data items being acted upon. A storage register hold the immediate and final results of processing.



Number Systems
Binary to Decimal
• Technique
– Multiply each bit by 2n, where n is the “weight” of the bit
– The weight is the position of the bit, starting from 0 on the right
– Add the results
1010112 => 1 x 20 = 1


1 x 21 = 2


0 x 22 = 0


1 x 23 = 8


0 x 24 = 0


1 x 25 =32
4310
Octal to Decimal
Technique
– Multiply each bit by 8n, where n is the “weight” of the bit
– The weight is the position of the bit, starting from 0 on the right
– Add the results
7248 => 4 x 80 = 4


2 x 81 = 16


7 x 82 = 448


46810
Hexadecimal to Decimal

Technique
– Multiply each bit by 16n, where n is the “weight” of the bit
– The weight is the position of the bit, starting from 0 on the right
– Add the results
ABC16 => C x 160 = 12 x 1 = 12


B x 161 = 11 x 16 = 176


A x 162 = 10 x 256 = 2560
274810
Decimal to Binary
• Technique
– Divide by two, keep track of the remainder


– First remainder is bit 0 (LSB, least-significant bit)
– Second remainder is bit 1
– Etc.
12510 =? 2
12510 = 11111012

Octal to Binary

• Technique
– Convert each octal digit to a 3-bit equivalent binary representation
Hexadecimal to Binary

• Technique
– Convert each hexadecimal digit to a 4-bit equivalent binary representation
• Convert a hexadecimal number to a binary number,
• simply divided the binary number into 4-bit groups
• Substitute the corresponding four bits in binary for each hexadecimal digit in the number.
• For example, convert ABCD to a binary value, The binary equivalent is:
• ABCD= 1010 1011 1100 1101

Binary to Octal
• Technique
– Group bits in threes, starting on right
– Convert to octal digits
Binary to Hexadecimal
• Technique
– Group bits in fours, starting on right
– Convert to hexadecimal digits
• Binary to Hex Conversion
• Break the binary number into 4-bit groups from the Left to the right.
• Convert the 4-bit binary number to its Hex equivalent.
• For example, the binary value 101011111011 0010 will be written:
• 1010 1111 1011 0010=AFB2



Computer Softwares

Hardware

*Hardware is the machine itself and its various individual equipment.
*It includes all mechanical,electronic and magnetic devices such as monitor, printer, electronic circuit, floppy and hard disk.
Software
· Software refers to the set of computer programs, which are used in applications and operating systems.
· It is the collection of programs, which increase the capabilities of the hardware.
· Software guides the computer at every step where to start and stop during a particular job.
· The process of software development is called programming.

SOFTWARE TYPES

Application Software:
· Application Software is a set of programs for a specific application.
· Application software is useful for word processing, accounting, producing statistical report, Graphics, Excel and Data Base.
· programming languages COBOL, FORTRAN, C++, VB, VC, Java

Types of Application Software
Application software enables users to perform the activities and work that computers were designed for. The specific type of application used depends on the intended purpose, and there are application programs for almost every need. Three broad types of application software available for business users are individual, collaboration, and vertical programs (see Table 5-1).

Individual application software refers to programs individuals use at work or at home. Examples include word processing, spreadsheet, database management, and desktop publishing programs.

Collaboration software (also called groupware) enables people at separate PC workstations to work together on a single document or project, such as designing a new automobile engine.

Vertical application software is a complete package of programs that work together to perform core business functions for a large organization. For example, a bank might have a mainframe computer at its corporate headquarters connected to conventional terminals in branch offices, where they are used by managers, tellers, loan officers, and other employees. All financial transactions are fed to the central computer for processing. The system then generates managers’ reports, account statements, and other essential documents.

Other Application Software Models
Shareware Shareware is software developed by an individual or software publisher who retains ownership of the product and makes it available for a small “contribution” fee. The voluntary fee normally entitles users to receive online or written product documentation and technical help.

Freeware Freeware is software that is provided free of charge to anyone wanting to use it. Hundreds of freeware programs are available, many written by college students and professors who create programs as class projects or as part of their research.

Open Source Software An open source software program is software whose programming code is owned by the original developer but made available free to the general public, who is encouraged to experiment with the software, make improvements, and share the improvements with the user community

Application Software for Individual Use
The thousands of application programs that individuals use to perform computing tasks at work and at home can be grouped into four types:

*productivity software
*software for household use
*graphics and multimedia software
*communication software
Productivity Software
Productivity software is designed to improve efficiency and performance on the job and at home, and is the largest category of application software for individual use. In-depth knowledge and skill in using productivity software applications can make a potential employee more valuable to a business, organization, or agency.

Word Processing
A word processing program can be used to create almost any kind of printed document. Word processors are the most widely used of all software applications because they are central to communication. Whatever the type of document created with a word processing program, the essential parts of the procedure remain the same:

*create (enter) text
*edit the text
*format the document
*save and print the file

Desktop Publishing
Desktop publishing (DTP) software allows users to create impressive documents that include text, drawings, photographs, and various graphics elements in full color. Professional-quality publications can be produced with DTP software. Textbooks such as this one may be designed and laid out with a desktop publishing application such as PageMaker, QuarkXpress, or Adobe InDesign. Major word processors offer limited desktop publishing features sufficient for creating simple newsletters and brochures.

Spreadsheets

Spreadsheet software is an electronic version of the ruled worksheets accountants used in the past. Spreadsheet software provides a means of organizing, calculating, and presenting financial, statistical, and other numerical information. Businesses find spreadsheets particularly useful for evaluating alternative scenarios. The spreadsheet uses “what if” calculations to evaluate possibilities. By entering various data values and formulas into a spreadsheet, questions can be answered quickly and accurately.

For the individual user, spreadsheets fulfill many purposes, including:

*preparing and analyzing personal or business budgets
*reconciling checkbooks
*analyzing financial situations
*tracking and analyzing investments
*preparing personal financial statements
*estimating taxes

Database Management
In a computerized database system, data are stored in electronic form on a storage medium, such as hard or floppy disks or CDs. A database is a collection of data organized in one or more tables consisting of individual pieces of information, each located in a field, and a collection of related fields, each collection making up one record (see Figure 5-1). A commercial database program typically allows users to create a form for entering data. A user can design an electronic form to make entering information into the database easier. The information entered using such a form will become a record in a table. Users can add, remove, or change the stored data.

Presentation Graphics
Presentation graphics software allows users to create computerized slide shows that combine text, numbers, animation, graphics, sounds, and videos. A slide is an individual document that is created in presentation graphics software. A slide show may consist of any number of individual slides. For example, an instructor may use a slide show to accompany a lecture to make it more engaging and informative. Microsoft PowerPoint and Corel Presentations are two popular presentation software programs.

Software for Household Use
Numerous software applications designed for use in the household are available for purchase. Among the many products available are applications for managing personal finances, preparing tax returns, preparing legal documents, playing games, and education and reference.

Graphics and Multimedia Software
Graphics and multimedia software allows both professional and home users to work with graphics, video, and audio. A variety of applications software is focused in this area, including painting and drawing software, image-editing software, video and audio editing software, Web authoring software, and computer-aided design (CAD) software.

Communications Software
One of the major reasons people use computers is to communicate with others and to retrieve and share information. Communications software allows users to send and receive e-mail, browse and search the Web, engage in group communications and discussions, and participate in videoconferencing activities.
Automatic Multimedia Tagging Software
Advances in Speech Recognition Software
Pattern Recognition Software
Distributed Computing

System Software:
· When you switch on the computer the programs written in ROM is executed which activates different units of your computer and makes it ready for you to work.
· This set of programs can be called system software.
· System software are general programs designed for performing tasks such as controlling all operations required to move data into and out of the computer
· System Software allows application packages to be run on the computer.
Computer manufactures build and supply this system software with the computer system.

An operating system is the most important piece of software on a personal computer. The location of the operating system identifies the boot drive for the personal computer, which is typically the hard drive. Once started, the operating system manages the computer system and performs functions related to the input, processing, output, and storage of information, including:

managing main memory, or RAM
*configuring and controlling peripheral devices
*managing essential file operations, including formatting or copying disks, and renaming or deleting files
*monitoring system performance
*providing a user interface
Windows
Windows 2000 Professional Windows 2000 Professional, introduced in late 1999, was designed for use with business computers and was the successor to Windows 98 for office environments. Incorporating the power of Windows NT, Windows 2000 Professional was used to link
Windows XP Professional Microsoft’s Windows XP Professional was designed for the latest computers that are fast, powerful, and have lots of memory and hard disk space. It combined the more powerful features of Windows 2000 and Windows NT and included many cosmetic changes. Windows XP contained many new and improved features and was extremely user-friendly. Icons had a three-dimensional look, and provided impressive features for managing photo and music files. It was the first Windows version to be copy-protected.

Windows Vista Windows Vista, released in 2007, improves and expands on Windows XP’s capabilities. It provides much more robust security features than any earlier version. The centerpiece of this security system is User Access Control (UAC), a protection system that prompts the user for administrator-level credentials whenever an operation is attempted that might affect system stability or security in some way. Home networking is easier than ever with Windows Vista.

Macintosh Operating System

The Macintosh, the first commercial GUI, was originally released in 1984 and has been updated many times since. It included a virtual desktop, pull-down menus, dialog boxes, and icons representing common commands and programs. With its impressive graphics and ease of use, it quickly became the model for other GUIs.
OS/2

IBM’s OS/2 GUI operating system was the company’s response to the popularity of Microsoft Windows and the Apple Mac OS. The latest version is called OS/2 Warp. In addition to running native application programs, OS/2 can also run programs written for DOS and Windows systems.
Linux

Linux is a UNIX-based operating system that runs on a number of computer platforms including PCs, servers, and handheld devices. The Linux kernel (the central module or basic part) was developed mainly by Linus Torvalds. Torvalds designed Linux as an open-source software program, which means that the developer retains ownership of the original programming code but makes it free to the general public, who is encouraged to experiment with the software, make improvements, and share the improvements with the entire user community. During recent years, many improvements and refinements have been made rendering Linux an extremely popular and functional operating system for both large and small computers.

Server Operating Systems

Some operating systems are designed specifically for use with local area networks, allowing multiple users to connect to the server and to share network resources such as files and peripheral devices such as printers. The kind of operating system selected for use with a network server depends on network architecture and processing requirements.
Novell Netware

NetWare, developed by Novell, Inc. during the 1980s, is a popular and widely used operating system for microcomputer-based local area networks. Network users have the option of working with or without network resources.
Windows

Microsoft’s Windows NT Server was one of Microsoft’s earlier entries into the client/server market. It supported the connection of various peripheral devices and multitasking operations in which networked computers could process applications at the same time. Windows NT Server was replaced by Windows 2000 Server.
UNIX

Developed in the early 1970s by programmers at Bell Laboratories, the UNIX operating system was originally designed for servers and large computer systems

Linux Linux (pronounced LIN-UKS) is one of the fastest-growing server operating systems. Linux is an open-source software program based on the UNIX operating system
Solaris Solaris is a Unix-based operating environment developed by Sun Microsystems. It was originally developed to run on Sun’s SPARC workstations but now runs on many workstations from other manufacturers

Compiler :It is a program translator that translates the instruction of a higher level language to machine language.
An interpreter is another type of program translator used for translating higher level language into machine language.
l It takes one statement of higher level languages, translate it into machine language and immediately execute it.
Software Development Steps
Software Development Life Cycle
The product developed which achieves customer satisfaction is not done in a single step. It involves series of steps in a software development process. This is needed to develop quality products with error free products to achieve customer satisfaction. There are many models available in the software development process.

But majority of software development process follow the model named as software development life cycle. This software develop life cycle has number of steps in it. The below article describes about the software development life cycle and the steps involved into it.
Software development life cycle model is also called as waterfall model which is followed by majority of systems. This software development life cycle process has the following seven stages in it namely
1. System Requirements Analysis2. Feasibility study3. Systems Analysis and Design4. Code Generation5. Testing6. Maintenance7. Implementation
Let us discuss each of these to have an overview about teach of the following steps in software development life cycle.
1. System Requirements Analysis:
The first essential or vital thing required for any software development is system. Also the system requirement may vary based on the software product that is going to get developed. So a careful analysis has to be made about the system requirement needed for the development of the product. After the analysis and design of the system requirement phase the system required for the development would be complete and the concentration can be on the software development process.
2. Feasibility study:
After making an analysis in the system requirement the next step is to make analysis of the software requirement. In other words feasibility study is also called as software requirement analysis. In this phase development team has to make communication with customers and make analysis of their requirement and analyze the system. By making analysis this way it would be possible to make a report of identified area of problem. By making a detailed analysis on this area a detailed document or report is prepared in this phase which has details like project plan or schedule of the project, the cost estimated for developing and executing the system, target dates for each phase of delivery of system developed and so on. This phase is the base of software development process since further steps taken in software development life cycle would be based on the analysis made on this phase and so careful analysis has to be made in this phase.
3. Systems Analysis and Design:
This is an important phase in system development .Here analysis is made on the design of the system that is going to be developed. In other words database design, the design of the architecture chosen, functional specification design, low level design documents, high level design documents and so on takes place. Care must be taken to prepare these design documents because the next phases namely the development phase is based on these design documents. If a well structured and analyzed design document is prepared it would reduce the time taken in the coming steps namely development and testing phases of the software development life cycle.
4. Code Generation:
This is the phase where actual development of the system takes place. That is based on the design documents prepared in the earlier phase code is written in the programming technology chosen. After the code is developed generation of code also takes place in this phase. In other words the code is converted into executables in this phase after code generation.
5. Testing:
A software or system which is not tested would be of poor quality. This is because this is the phase where system developed would be tested and reports are prepared about bugs or errors in system. To do this testing phase there are different levels and methods of testing like unit testing, system test and so on. Based on the need the testing methods are chosen and reports are prepared about bugs. After this process the system again goes to development phase for correction of errors and again tested. This process continues until the system is found to be error free. To ease the testing process debuggers or testing tools are also available.

To develop reliable and good quality Program/Software we need to follow the following 5 steps :

1. Requirement Specification.
2. Analysis.
3. Design.
4. Implementation.
5. Verification and testing.
Internet Evolution
— The Internet is a network of networks
— Computer users on the Internet can contact one another anywhere in the world
— In Internet a huge resource of information is accessible to people across the world
— Information in every field starting from education, science, health, medicine, history, and geography to business, news, etc. can be retrieved through Internet
— You can also download programs and software packages from anywhere in the world
— In 1969 Department of Defense (DOD) of USA started a network called ARPANET (Advanced Research Projects Administration Network )
— Around 1970, NSFNET (National Science Foundation Network) was created. With the advancement of modern communication facilities,
— By 1990 many computers were looking up to NSFNET giving birth to Internet
— Internet is not a governmental organization.
— The ultimate authority of the Internet is the Internet Society.
— This is a voluntary membership organization whose purpose is to promote global information exchange.
— Internet has more than one million computers attached to it.
— Ten years of research brought Local Area Ethernet Networks (LANs) and workstations were developed to get connected to LAN.
— Computers connected to ARPANET used a standard or rule to communicate with each other with NCP (National Control Protocol).
— Protocol is a network term used to indicate the standard used by a network for communication.
— Rapid change in information technology suppressed NCP and brought TCP/IP (Transmission Control Protocol/Internet Protocol) in to the world of networking
— The Internet is a rare example of a large democracy with no state of head, no official censors, no bosses, no board of directors. Nobody controls the Internet and in principle, any computer can speak to any other computer, as long as it obeys the technical rules of the TCP/IP protocol.
— This freedom of Internet helped it to move out of its original base in military and research institutions, into elementary and high schools, colleges, public libraries, commercial sectors
Basic Internet Terminology
Blog - A blog is information that is instantly published to a Web site. Blog scripting allows someone to automatically post information to a Web site. The information first goes to a blogger Web site. Then the information is automatically inserted into a template tailored for your Web site.
Bookmark – a way of storing your favorite sites on the Internet. Browsers like Netscape or Internet Explorer let you to categorize your bookmarks into folders.
Browser – A software program that allows users to access the Internet. Examples:
Non-graphical a user interface for computers which allows you to read plain text, not pictures, sound, or video, on the Internet. It is strictly text based, non-Windows, and does not place high memory demands on your computer. An example is lynx .(http://lynx.browser.org/)
Graphical a user interface for computers which enables people to see color, graphics, and hear sound and see video, available on Internet sites. These features are usually designated by underlined text, a change of color, or other distinguishing feature; sometimes the link is not obvious, for example, a picture with no designated characteristic. Examples are Netscape and Internet Explorer.
CGI (Common Gateway Interface script) – a specificiation for transferring information between a Web server and a CGI program, designed to receive and and return data. The script can use a variety of languages such as C, Perl, Java, or Visual Basic. Many html pages that contain forms use a cgi program to process the data submitted by users/clients.
Chat – real-time, synchronous, text-based communication via computer.
Cookie – Information (in this case URLs, Web addresses) created by a Web server and stored on a user’s computer. This information lets Web sites the user visits to keep of a user’s browsing pattterns and preferences. People can set up their browsers to accept or not accept cookies.
Domain Name – A method of identifying computer addresses. Your e-mail address has a domain address. If you have an “edu” at the end of your e-mail address that means your account is affiliated with an educational institution. A “com” extension means you have a business account. A government account has a .gov suffix.
FTP – Using file transfer protocol software to receive from upload) or send to (download) files (text, pictures, spreadsheets, etc.) from one computer/server to another.
Home page - Generally the first page retrieved when accessing a Web site. Usually a “home” page acts as the starting point for a user to access information on the site. The “home” page usually has some type of table of contents for the rest of the site information or other materials. When creating Web pages, the “home” page has the filename “index.html,” which is the default name. The “index” page automatically opens up as the “home” page.
HTML – A type of text code in Hypertext Markup Language which, when embedded in a document, allows that document to be read and distributed across the Internet.
HTTP – The hypertext transfer protocol (http) that enables html documents to be read on the Internet.
Hypertext – text that is non-sequential, produced by writing in HTML (Hypertext Markup Language) language. This HTML coding allows the information (text, graphics, sound, video) to be accessed using HTTP (Hypertext Transfer Protocol).
Hyperlink – Text, images, graphics that, when clicked with a mouse (or activated by keystrokes) will connect the user to a new Web site. The link is usually obvious, such as underlined text or a “button” of some type, but not always.
Instant Messaging (IM) – a text-based computer conference over the Internet between two or more people who must be online at the same time. When you send an IM the receiver is instantly notified that she/he has a message.
IP Address – (Internet Protocol) The number or name of the computer from which you send and receive information on the Internet.
Modem – A device that connects your computer to the Internet, when you are not connected via a LAN (local area network, such as at work or on a campus.) Most people connect to a modem when using a home computer. The modem translates computer signals to analog signals which are sent via phone lines. The telephone “speaks” to the computer/server which provides your Internet access.
URL – A universal resource locator (a computer address) that identifies the location and type of resource on the Web. A URL generally starts with “http.”
Intranet: It is a relatively smaller private network that uses the Internet protocols and connectivity. It is an extension of the Internet and is privately used by organizations.
Web Server: A web server is a computer program that accepts HTTP requests from web clients and provides them with HTTP responses.
IP Address: It is a way of numerically identifying an entity on a computer network. The original addressing system known as IPv4, used 32 bit addresses. With the growth of the Internet, IPv6 came to be used wherein the addresses are composed of 128 bits. You might want to know how to find your IP address.
Internet Service Provider: A company, which provides users with an access to the Internet, is known as an Internet service provider or Internet access provider. ISP, as it is called, offers email accounts and other services like remote storage of files for its customers. Here is a word about choosing a cheap ISP.
Internet Address
— Every page on the Internet has a unique address.
— This address is used get the web page for user from Internet.
— The address on the Internet is known as URL (Uniform Resource Locator).
— A typical Internet address or URL would look like; http://www.mans.edu.eg/facscim/arabic/
— The URL contains the components that specify the protocol, server, and pathname of an item
URL parts
— The protocol is followed by a colon (http:),
— The server is preceded by two slashes (//www.mnmjec.edu.)
— Each segment of the pathname is preceded by a single slash /facscim/ /english/Tables/Default.htm).
— A protocol is set of rules that tells the computer know how to interpret the information at that address
— The first component, the protocol, defines the manner for interpreting computer information.
— Many Internet pages use HTTP (HyperText Transfer Protocol).
— Other common Internet protocols that one might come across are FTP (File Transfer Protocol),
— NEWS (Usenet news groups protocol), and
— GOPHER (an alternative transfer protocol). Gopher protocol is mostly out of date now.
— The second component, of the address is the server (www.mnmjec.edu), identifies the computer system that stores the information you seek and is always preceded by two slashes.
— A server is a computer that has information stored on it and sends it to the client, when a request is made.
— Each server on the Internet has a unique address name whose text refers to the organization maintaining the server.
— Most of the Web pages will have .htm or .html as their secondary or extension name.

Getting connected to Internet Applications

Types of Internet Connections

There are two main ways for users to connect to the Internet: through dial-up access or by using a LAN connection.

Dial-up Access Dial-up access allows access to the Internet over a standard telephone line by using a computer and a modem to dial into an ISP or VAN connection. Dial-up access is a feature typically included with the software provided by an ISP. Using a regular telephone line is usually the slowest telecommunications medium for setting up an individual Internet account through a dial-up ISP.

Local Area Network (LAN) Connection LAN connections provide faster and more direct Internet access by connecting users to an ISP on a direct wire, at speeds 30 or more times faster than can be achieved through a dial-up modem. Because they are more expensive than dial-up access, LAN connections are more commonly found in the workplace. Despite the increased cost there are approximately forty million LAN users in the United States using cable and DSL connections to connect from their homes.

Cable Modem Television cable companies provide a special modem and software for broadband (high-speed) Internet access. This service offers the advantage of simultaneous Web access and telephone calls, but is not available everywhere. In addition, the service slows down as more subscribers sign up in a neighborhood or location. The cost is about $50 monthly, plus a possible installation fee.

Digital Subscriber Line (DSL) DSL Internet service is as fast as cable modem and provides simultaneous Web access and telephone use, but the service is usually available only to users within three miles of the telephone carrier’s central switching office. The line is dedicated to one household, and is not shared with neighbors. DSL service costs around $50 monthly, plus an installation fee.

Wireless The fastest growing segment of Internet service involves wireless connections to the Internet. Thousands of Wireless “hot-spot” portals are springing up, allowing access in public places and even aboard airplanes.

— (i) Gateway Access
— Gateway Access is also known as Level-One connection.
— It is the access to the Internet from a network, which is not on the Internet.
— The gateway allows the two different types of networks to “talk” to each other. But the users of the Gateway Internet have limited access to the Internet.
— They might not be able to use all the tools available on Internet. The local Internet Service Provider (ISP) normally defines this limitation.
Dial-up Connection

— ‘Dial-up’ connection is also known as Level Two connection.
— This provides connection to Internet through a dial-up terminal connection.
— The computer, which provides Internet access is known as ‘Host’ and the computer that receives the access, is ‘Client’ or ‘Terminal’.
— The client computer uses modem to access a “host” and acts as if it is a terminal directly connected to that host.
— This type of connection is also known as ‘Remote Modem Access’ connection.
— And the host to which the client gets connected is actually connected to the Internet by a full time connection (See Leased Connection).

— In dial-up connection to Internet, Host carries all the command that are typed on a client machine and forward them to Internet.
— It also receives the data or information from the Internet on behalf of the ‘Client’ and passes it to them. The client computer acts as a ‘dumb’ terminal connected to remote host.
— This type of connection can further be divided into two categories.
Shell Connection
— In this type of Internet Connection, the user will get only textual matter of a Web Page.
— This connection does not support Graphics display. However the user will be able to surf the Internet, do FTP, receive mail.
— Shell Accounts were the only type of Internet access available for many years before the Internet entered in to the world of graphics and became more users friendly.
TCP/IP Connection
— Today’s graphical World Wide Web browsers provide easier access with multimedia sound and pictures.
— The major difference between Shell and TCP/IP account is that, Shell account can only display text and does not support graphics display, whereas TCP/IP can display both.
— Hence it is more popular Internet connection. Shell accounts are slowly phasing out from the Internet scenario
To access any of these dial-up accounts you need the followings;
l computer, WebTV, personal digital assistant (PDA), or Web phone
l dial-up modem, digital subscriber line (DSL) modem, or cable modem
l telephone line or cable connection
l telecommunications software
l Web browser
l an account with an Internet Service Provider (ISP)
Leased Connection
— Leased connection is also known as direct Internet access or Level Three connection.
— It is the secure, dedicated and most expensive, level of Internet connection.
— With leased connection, your computer is dedicatedly and directly connected to the Internet using high-speed transmission lines.
— It is on-line twenty-four hours a day, seven days a week.
— Leased Internet connections are limited to large corporations and universities who could afford the cost.
Newer Internet Applications

Not only does the content of the Internet change daily, but they very way in which the Internet is used and understood as a communication medium is constantly evolving.

Peer-to-Peer File Sharing
Peer-to-Peer (P2P) file sharing allows people to download material directly from other users’ hard drives, rather than from files located on Web servers. Napster is famous for pioneering P2P file sharing.
Internet Telephony
Internet telephony is another increasingly popular way to use the Internet. By using this technology, also called Voice over IP (VoIP), two or more users with sufficiently good connections can use the Internet to make telephone calls around the world. Once their voices are digitized and broken down into packets, they can be transmitted anywhere, just like any other form of data. There are no long distance telephone charges, and users only pay their normal ISP connection fees.
Streaming Audio and Video
An alternative to downloading a piece of music or video is to access it using streaming techniques (also known as webcasting). Streaming sends a continuous stream of data to the receiving computer, where it is immediately displayed. Old data is erased as new data arrives.
Webcams
Tiny video cameras called webcams allow conversations over the Web through live video transmission. Often mounted on top of a computer monitor, the cameras automatically create and transmit video to the PC. Despite the fact that the images are a bit grainy and jerky, millions are in use. As the technology improves, their popularity is sure to increase even further.
Audio Mail
Audio mail is a fledgling type of electronic mail that allows people to transmit messages by voice. As with e-mail, attachments can be included. The technology can be compared to voice mail, without telephone charges.

Problem Solving and Office Automation

PROGRAM DEVELOPMENT CYCLE
Program development cycle is a systematic approach to problem solving and is composed of several phases, each comprised of multiple steps:
1. Feasibility Study
2. Analysis
3. Design
4. Testing
5. Implementation
6. Evaluation
7. Maintenance
Planning – establishing the plans for creating an information system by
Defining the system to be developed – based on the systems prioritized according to the organization’s critical success factor (CSF), a system must be identified and chosen
Defining the project scope – a high level of system requirements must be defined and put into a project scope document
Developing the project plan - – all details from tasks to be completed, who completed them and when they were completed must be formalized
Managing and monitoring the project plan – this allows the organization to stay on track, creating project milestones and feature creeps which allow you to add to the initial plan
Analysis – the users and IT specialists collaborate to collect, comprehend, and logistically formalize business requirements by
Gathering the business requirements – IT specialists and knowledge workers collaborate in a joint application design (JAD) and discuss which tasks to undertake to make the system most successful
Analyzing the requirements – business requirements are prioritized and put in a requirements definition document where the knowledge worker will approve and place their signatures
Design – this is where the technical blueprint of the system is created by
Designing the technical architecture – choosing amongst the architectural designs of telecommunications, hardware and software that will best suit the organization’s system and future needs
Designing the systems model – graphically creating a model from graphical user interface (GUI), GUI screen design, and databases, to placement of objects on screen
Write the test conditions - Work with the end users to develop the test scripts according to the system requirements
Development – executing the design into a physical system by
Building the technical architecture – purchasing the material needed to build the system
Building the database and programs – the IT specialists write programs which will be used on the system
Testing – testing the developed system
Test the system using the established test scripts – test conditions are conducted by comparing expected outcomes to actual outcomes. If these differ, a bug is generated and a backtrack to the development stage must occur.
Deployment – the systems are placed and used in the actual workforce and
The user guide is created
Training is provided to the users of the system - usually through workshops or online
Maintenance – keeping the system up to date with the changes in the organization and ensuring it meets the goals of the organization by
Building a help desk to support the system users – having a team available to aid technical difficulties and answer questions
Selfsourcing
Selfsourcing is defined as having knowledge workers within an organization build the organization’s system
Align selfsourcing applications to the goals of the organization – All intentions must be related to the organization’s goals and time management is key.
Establish what external assistance will be necessary – this may be where an IT specialist in the organization may assist
Document and formalize the completed system created for future users –
Provide ongoing support - being able to maintain and make adjustments to the system as the environment changes..
Prototyping
Prototyping is defined as creating a model, which displays the necessary characteristics of a proposed system
Gathering requirements – these requirements will be stated by the knowledge workers as well as become apparent in comparison with the old or existing system
Create prototype of system – Confirm a technically proficient system by using prototypes and create basic screen and reports
Review by knowledge workers - create a model of the system that will be analyzed, inspected and evaluated by knowledge workers who will propose recommendations to have the system reach its maximum potential
Revise the prototype
convince the organization of the advantages of switching up to the new system
Outsourcing
Outsourcing is defined as having a third party (outside the organization) to build the organization’s system so expert minds can create the highest quality system by.
Outsourcing for development software -
Purchasing existing software and paying the publisher to make certain modifications and paying the publisher for the right to make modifications yourself
Outsourcing the development of an entirely new unique system for which no software exists
Selecting a target system – make sure there is no confidential information critical to the organization that others should not see. If the organization is small enough, consider selfsourcing
Establish logical requirements - IT specialists and knowledge workers collaborate in a joint application design (JAD) and discuss which tasks to undertake to make the system most successful to gather business requirements
Develop a request for a proposal – a request for proposal (RFP) is created and formalized. It includes everything the home organization is looking for in the system and can be used as the legal binding contract
Evaluate request for proposed returns and choose a vendor amongst the many who have replied with different prototypes
Test and Accept a Solution – the chosen system must be tested by the home organization and a sign-off must be conducted
Monitor and Reevaluate – keep the system up to date with the changing environment and evaluate the chosen vendor’s ability and accommodate to maintain the system
FLOW CHART
Flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a process.
A flowchart is one of the seven basic tools of quality control, which also includes the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, and scatter diagram. They are commonly used in business/economic presentations to help the audience visualize the content better, or to find flaws in the process.

Symbols
A typical flowchart from older Computer Science textbooks may have the following kinds of symbols:
Start and end symbols, represented as lozenges, ovals or rounded rectangles, usually containing the word "Start" or "End", or another phrase signaling the start or end of a process, such as "submit enquiry" or "receive product".
Arrows, showing what's called "flow of control" in computer science. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.
Processing steps, represented as rectangles. Examples: "Add 1 to X"; "replace identified part"; "save changes" or similar.
Input/Output, represented as a parallelogram. Examples: Get X from the user; display X.
Conditional (or decision), represented as a diamond (rhombus). These typically contain a Yes/No question or True/False test. This symbol is unique in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. The arrows should always be labeled. More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further, or replaced with the "pre-defined process" symbol.
A number of other symbols that have less universal currency, such as:

A Document represented as a rectangle with a wavy base;
A Manual input represented by rectangle, with the top irregularly sloping up from left to right. An example would be to signify data-entry from a form;
A Manual operation represented by a trapezoid with the longest parallel side at the top, to represent an operation or adjustment to process that can only be made manually.
A Data File represented by a cylinder
ALGORITHM
In mathematics, computing, linguistics and related disciplines, an algorithm is a sequence of instructions, often used for calculation, data processing. It is formally a type of effective method in which a list of well-defined instructions for completing a task will, when given an initial state, proceed through a well-defined series of successive states, eventually terminating in an end-state. The transition from one state to the next is not necessarily deterministic; some algorithms, known as probabilistic algorithms, incorporate randomness.
PROGRAM CONTROL STRUCTURES
· Sequence control structure
· Selection control structure
· Repetative control structure
GENERATION OF PROGRAMMING LANGUAGES
First generation programming languages
Second generation programming languages
Third generation programming languages
Fourth generation programming languages
Fifth generation programming languages
First generation programming languages (machine languages)
Machine code or machine language is a system of instructions and data directly executed by a computer's central processing unit. Machine code may be regarded as a primitive (and cumbersome) programming language or as the lowest-level representation of a compiled and/or assembled computer program. Programs in interpreted languages (often BASIC, Matlab, Smalltalk, Python, Ruby, etc), are not represented by machine code however, although their interpreter (which may be seen as a processor executing the higher level program) often is. Machine code is also referred to as native code, a term that, in the context of an interpreted language, may refer to the platform-dependent

Second generation programming languages(assembly language)
· Assembly languages directly correspond to a machine language in order to allow machine code instructions to be written in a form understandable by humans. Assembly languages allow programmers to use symbolic addresses which are later converted to absolute addresses by the assembler. Most assemblers also allow for macros and symbolic constants.
· An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture. This representation is usually defined by the hardware manufacturer, and is based on abbreviations (called mnemonics) that help the programmer remember individual instructions, registers, etc.
· A utility program called an assembler is used to translate assembly language statements into the target computer's machine code. The assembler performs a more or less isomorphic translation (a one-to-one mapping) from mnemonic statements into machine instructions and data.
Third generation programming languages(high level languages)
A high-level programming language is a programming language that, in comparison to low-level programming languages, may be more abstract, easier to use, or more portable across platforms. Such languages often abstract away CPU operations such as memory access models and management of scope.(ex:c,c++,java etc).
Execution models
There are three models of execution for modern high-level languages:
Interpreted
Interpreted languages are read and then executed directly, with no compilation stage.
Compiled
Compiled languages are transformed into an executable form before running. There are two types of compilation:
Intermediate representations
When a language is compiled to an intermediate representation, that representation can be optimized or saved for later execution without the need to re-read the source file. When the intermediate representation is saved it is often represented as bytecode.
Machine code generation
Some compilers compile source code directly into machine code. Virtual machines that execute bytecode directly or transform it further into machine code


have blurred the once clear distinction between intermediate representations and truly compiled languages.

Translated
A language may be translated into a low-level programming language for which native code compilers are already widely available. The C programming language is a common target for such translators.
Fourth generation programming languages(query languages)
Fourth-generation programming languages are high-level languages built around database systems. They are generally used in commercial environments.
TYPES
A number of different types of 4GLs exist:
Table-driven (Codeless) programming, usually running with runtime framework and libraries. Instead of using code, the developer defines his logic by selecting an operation in a pre-defined list of memory or data table manipulation commands. Report generators take a description of the data format and the report to generate and from that they either generate the required report directly or they generate a program to generate the report.
Similarly, forms generators manage online interactions with the application system users or generate programs to do so.
More ambitious 4GLs (sometimes termed fourth generation environments) attempt to automatically generate whole systems from the outputs of CASE tools, specifications of screens and reports, and possibly also the specification of some additional processing logic.
Data management 4GLs such as SAS, SPSS and Stata provide sophisticated coding commands for data manipulation, file reshaping, case selection and data documentation in the preparation of data for statistical analysis and reporting.
Fifth generation programming languages
A fifth-generation programming language (abbreviated 5GL) is a programming language based around solving problems using constraints given to the program, rather than using an algorithm written by a programmer. Most constraint-based and logic programming languages and some declarative languages are fifth-generation languages.
Example:
Artificial intelligence (AI) is both the intelligence of machines and the branch of computer science which aims to create it.

Overview of C
1.1 Syntax
The C code you write is called the SOURCE CODE or the SYNTAX.
Syntax is a mixture of:
C keywords like int, for and return.
Constants and variables.
Operators like + (arithmetic “addition”), (logical “or”) and & (the “address of” operator).
Note that C is CASE SENSITIVE! For example, words like cat, Cat, cAt and CAT are all considered different from one another.
Also, the amount of WHITE SPACE you use in a C program does not affect the way it’s compiled. Use extra spaces and line breaks to make your programs more readable – indentation of code is very common. Obviously, you can NOT put spaces or line breaks in the middle of keywords like this: str uct !!
1.2 Commenting Your Code
You can add comments to your code by enclosing your remarks within /* and */. However, nested comments aren’t allowed.
A few properties of comments:

They can be used to inform the person viewing the code what the code does. This is helpful when you revisit the code at a later date.

The compiler ignores all the comments. Hence, commenting does not affect the efficiency of the program.

You can use /* and */ to comment out sections of code when it comes to finding errors, instead of deletion.
Here are examples of commented code:
/* Comments spanning several */
/* lines can be commented*/
/* out like this!*/

/* But this is a
simpler way
of doing it! */

// These are C++
// style comments
// and should NOT
// be used with C!!

/* /* NESTED COMMENTS
ARE ILLEGAL!! */ */
1.3 Creating Executable Programs
There are several tasks that need to be performed before you can run a program: coding, compiling and linking.
1.
You have to write the SOURCE CODE in C. You declare which header files you want to include within the source code. The source code must be saved with the extension .c.
2.
Then you run the COMPILER, which translates the source code into machine code. This produces output in a format that the computer can understand. It is worth repeating that computers do NOT understand C!
3.
Sometimes the source code is still lacking some parts, so after going through the compiler, the code is passed through a LINKER. This basically “links” the source code to other library or object files so that the final program is produced. Imagine the program being a jigsaw puzzle – the linker simply puts together missing pieces to complete the program.

#include

int main() {
printf("Hello World!\n");
return 0;
}
1.4 Tip
When saving in Notepad you should surround a filename with quote marks, for example, “world.c“. This ensures that the filename will be saved with the correct extension, rather than world.c.txt, which is incorrect.
1.5 Compiling
Compilation obviously varies from compiler to compiler – please read your compiler’s help file or ask your course tutor.
1.6 #include
If a line starts with a hash, denoted by #, it tells the compiler that a command should be sent to the C PREPROCESSOR. The C preprocessor is a program that is run before compilation takes place (hence the name). #include is one of the many C preprocessor commands you’ll use.
Basically, when the preprocessor finds #include it looks for the file specified and replaces #include with the contents of that file. In a way, this makes the code more readable and easier to maintain if you needed to use common library functions. More preprocessor commands in the later sections…..
1.7 Header Files
Header files have the extension .h and the full filename follows from the #include directive.
They contain declarations to certain functions that you may or may not have used in your program.
For example, the stdio.h file is required if you have used functions like printf and scanf in your program. More about these two functions in the Standard Input and Output section.
There are two ways to include a header file:#include "stdio.h" and#include
If you use the double quote marks, it means that the directory you’re currently in, will be searched for first for the header file, before any other directories are searched.
If you use the angled brackets, directories other than the one you’re currently in, will be searched for the header file. Usually this will be the default directory for header files specified in your compiler, so you’ll probably be using square brackets all the time.
1.8 The main Function
A FUNCTION is like a subroutine where a group of instructions are evaluated when the function is CALLED.
All C programs must have a main function. You can only have one, but you can place it anywhere within the code.
The program always start with the main function and ends when the end of main is reached. Functions RETURN a value too, in other words, passes back a value to the program.
If a function returns nothing, its return type is of type void – i.e. nothing is returned.
The main function is special, as it returns an integer by default, which is why you’ll see me write return 0; at the end of the program. Zero is usually returned to indicate error-free function termination.
Another way to terminate a program is to use the exit function – there’s an example later on.
Here’s the program again:
#include

int main() {
printf("Hello World!\n");
return 0;
}
1.9 printf
As you might have guessed, printf is a function that outputs text to the program window. For now, all you need to remember is that you pass it a STRING (a sequence of characters), which gets outputted. The \n character is the NEWLINE character, which allows you to start a new line in the output to make things neater.
Notice that there is a semicolon at the end of the line. Semicolons are used to terminate STATEMENTS, which are instructions for the computer to process. Here we are instructing the computer to “print hello world”.


As a programming language, C is rather like Pascal or Fortran. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures.
Of the three languages, C allows the most precise control of input and output. C is also rather more terse than Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C’s range of powerful operators. It also allows the programmer to produce programs which are impossible to understand.
Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead to errors which are very hard to trace. This course only deals with the simplest applications of pointers.
It is hoped that newcomers will find C a useful and friendly language. Care must be taken in using C. Many of the extra facilities which it offers can lead to extra types of programming error. You will have to learn to deal with these to successfully make the transition to being a C programmer.
The course aims to introduce programmers to the C language. Previous programming experience is assumed, so we can quickly progress to looking at the features of C and their uses. Students with little programming experience will need to do some homework in order to keep up with the lectures.
1.9.1 Structure of a C Program
Example
/*A simple C example program*/
#include
void main(void)
{
printf(”Hello World”);
}
The output of the program is shown below. This is what appears on the screen when the program runs.
Hello World
Let’s examine the program line by line. Here’s the first line.
/*A simple C example program*/
Other than the two forward slash marks that begin the line, it looks pretty much like ordinary English. The /* marks the beginning of a comment. The compiler ignores everything from the double slash to the end of the line. That means you can type anything you want on that line and the complier will never complain. To end the comment you must close it with */
Although comments are not required, they are very important to programmers. Real programs are much more complicated than the example above, and comments help explain what’s going on.
The next line looks like this:
#include
Because this line starts with a #, it is called a preprocessor directive. The preprocessor reads your program before it is complied and only executes those lines beginning with a # symbol. The word inside the angular brackets <> is a header file name, which is required to do the work of Input / Output. The contents of stdio.h are included at the point where the #include statement appears. The preprocessor directives should not end with a semicolon because preprocessors are messages to the compiler.
The next line reads:
void main(void)
This starts the beginning of a function. A function can be thought of as a group of one or more programming statements that collectively has a name. The name of this function is main, and the set of parentheses enclosing the word void indicate that it is a function.
Although most C programs have more than one function, every C program must have a function called main. It is the starting point of the program. If you are reading someone else’s C program and want to find where it starts, just look for the function called main.
The next line is a
{
This is called the left brace and marks the opening or beginning of a function, in our case main. All statements of the main are enclosed in a set of braces.
After the opening brace you see the following line:
printf(“Hello World”);
This statement displays the string Hello World on screen. We will discuss more about the printf()later on in this chapter.
The last line is a
}
This marks the end of the function main. Since main is the only function in the program it also marks the end of our program.
A special mention of the semicolon
A semicolon ; is used to mark the end of a statement in C. This allows the complier to understand that the end of a line has been reached. Usually a common mistake is that programmers omit the semicolon and try to compile the program.
1.9.2 The C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. The C character set can be defined as a set of characters permissible under the C language to represent information. Under C, the upper case letters A-Z, the lower case letters a-z, the digits 0-9 and certain special symbols are all valid characters that can be used as building blocks to construct basic program elements.
Following is a table of character sets that are available under C
AlphabetsA, B, C, ………………… Za, b, c, ………………… z
Digits0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters or Symbols+ – * & ^ % $ # @ ! ? > < { } [ ] ( ) \ / “ ‘ : ; . , _
Variables

IDENTIFIERS

The identifiers are name given to various program elements such as variables, functions and arrays.

l Identifiers consist of letters and digits in any order, except that
the First character must be a letter.
l The identifier can be in lowercase or uppercase.
l The upper and lower case are interchangeable.
l The underscore ( _ ) can be included and it can also begin with underscore.
l The identifiers should not contain a blank space, hyphen or quotes.

Valid Identifiers

sum , Sum, SuM, a112, total_sum

Invalid Identifiers

“sum” quotes(“) is illegal

total-sum Illegal character ( - )

total sum Blank space should not be there


VARIABLES
Variable Declaration and Definition, Variable Initialization and Sample programs
· A variable is a very basic part of every programming-language.
l A variable is a block of memory that you can store, change and read information from/to.
l A variable is an identifier that is used to represent some specified type of information within the program.

The basic format for declaring variables is

data type var, var, … ;

where data type is one of the four basic types, an integer, character, float, or double type.

E.g.:
int Sum, a, x;

char name;

C is case sensitive, so even though the two variables listed below have the same name, they are considered different variables in C.
sum
Sum
User defined variables must be declared before they can be used in a program.


DATA TYPES

The four basic data types are

1. INTEGER

· These are whole numbers, both positive and negative.
· The integer can store data between –32768 to 32767.

The keyword used to define integers is,

int

An example of an integer value is 32. An example of declaring an integer variable called sum is,

int sum;
sum = 20;



2. FLOATING POINT

· These are numbers, which contain fractional parts, both positive and negative.

The keyword used to define float variables is,

float

An example of a float value is 34.12. An example of declaring float variable called money is,

float money;
money = 0.12;


3. DOUBLE

· These are exponetional numbers, both positive and negative.

The keyword used to define double variables is,

double

An example of a double value is 3.0E2. An example of declaring a double variable called big is,

double big;
big = 312E+7;


4. CHARACTER

These are single characters. The keyword used to define character variables is,

char

An example of a character value is the letter A. An example of declaring a character variable called letter is,

char letter;
letter = ‘A’;

You can also perform the declaration and assignment in the same statement.
Example:

char letter = ‘A’;

Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes.


Remember the Rule: Single character – Use single quotes.


Sample program illustrating each data type


#include <>

main()
{
int sum;
float money;
char letter;
double pi;

sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = ‘A’; /* assign character value */
pi = 2.01E6; /* assign a double value */

printf(”value of sum = %d\n”, sum );
printf(”value of money = %f\n”, money );
printf(”value of letter = %c\n”, letter );
printf(”value of pi = %e\n”, pi );
}

Sample program output
value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06


NOTE

Data Type Description Memory Requirement

int Integer Quantity 2 bytes or 1 Word

char Single character 1 Byte

float Floating Point Number (A 1 word ( 4 bytes )
number containing decimal
point or exponent )

double Double precision floating 2 Words ( 8 bytes )
point number ( A exponent
with large magnitude )


CONSTANTS Constants-
Integer Constants, Real Constants, Floating point Constants, Character Constant, String Constant,
Constants are identifiers whose values once set in the program, never changes.
· The simplest constants are decimal integers, e.g. 0, 1, 2, 123.
· The constants can be Integer, floating point or character.
· We also have constants for specifying characters and strings.

DECLARATIONS

A declaration tells the compiler the name and type of a variable you’ll be using in your program. In its simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon

char c;
int i;
float f;

You can also declare several variables of the same type in one declaration, separating them with commas:

int i1, i2;

l The placement of declarations is significant.
l They must either be placed at the beginning of a function, or at the beginning of a brace-enclosed block of statements, or outside of any function.

You may wonder why variables must be declared before use. There are two reasons:

1. It makes things somewhat easier on the compiler; it knows right away what kind of
storage to allocate and what code to emit to store and manipulate each variable.

2. It gives the opportunity to give the initial ‘default values’ to the variables in one common place as soon as they are declared.

EXPRESSIONS

Any arrangement of variables, constants or operators that specifies a computation is called an expression.

a + 10;

is an expression. When the computation specified in the expression is performed then the result is usually a value. So if a is 5 then the result of the expression is 15.

OPERATORS
Assignment Operators, Conditional Operators, Arithmetic Operators, Relational Operators, Logical Operators, Bitwise Operators, and Unary operators.

ARITHMETIC OPERATORS

The basic operators for performing arithmetic are the same in many computer
languages:

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Operation Operator Equation Value of Sum before Value of sum after

Addition + sum = sum + 2 4 6
Subtraction - sum = sum –2 4 2
Multiply * sum = sum * 2 4 8
Divide / sum = sum / 2 4 2
Modulus % sum = sum % 3 4 1

UNARY OPERATORS

C includes a class of operators that act upon a single operand to produce a new value. Such operators are called unary operators. The most common unary operator is minus, where a minus precedes a numerical constant, variable or expression. Other unary operators are ++ and –. These are called as increment operators.
Eg :

-743 -(a + b) - 0.2

Operation Operator Equation Value of Sum before Value of sum after

Increment ++ ++sum 4 5
Decrement – –sum 4 3

RELATIONAL OPERATORS

The relational operators in C are ,

Operator Meaning

= = equal to
!= not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to

These allow the comparison of two or more variables. So they are also called Comparison Operators. These six operators are used to form logical expressions representing conditions that are either True or False. The resulting expression will be of type integer, since True is represented by the integer value 1 and False is represented by the value 0.

Eg :

Let a, b and c take values 1, 2 and 3 respectively.


Expression Interpretation Value

a < b True 1

(a + b) >= c True 1

(b + c) > (a + 5) False 0

c != 3 False 0

b = = 2 True 1

LOGICAL OPERATORS
These are the usual And, Or and Not operators.

Symbol Meaning

&& AND
OR
! NOT
They are frequently used to combine relational operators, for example
Let a be a integer variable whose value is 7 and i be a character variable representing q.

Expression Interpretation Value

(a >= 6) && ( i = = ‘q’) True 1

(a >= 6) ( i = = 120) True 1

(a >= 6) && ( i = = 120) False 0



Not operates on a single logical value, its effect is to reverse its state. Here is an example of its use.


if( !acceptable)
printf(”Not Acceptable !!\n”);

ASSIGNMENT OPERATORS

The assignment operator = assigns a value to a variable. Assignment expressions that make use of this operator are written in the form

identifier = expression

where identifier represents a variable and expression represents a constant, variable or a complex expression.
Eg :

x = 1

sets x to 1, and

a = b;

sets a to whatever b’s value is. The expression

i = i + 1;

is the standard programming idiom for increasing a variable’s value by 1. This expression takes i’s old value, adds 1 to it, and stores it back into i.

CONDITIONAL OPERATOR

Simple conditional operation can be carried out with the conditional operator ( ?
An expression using this operator is called a conditional expression. The general syntax is,

expression 1 ? expression 2 : expression 3

expression 1 is evaluated first. if the expression 1 is True then expression 2 is evaluated and this becomes the value of conditional expression. However if expression 1 is false then expression 3 is evaluated and this becomes the value of conditional expression.
Eg :

(i < 0 ) ? 0 : 100

The expression ( i < 0) is evaluated first. If it is true( i.e if the value of i is less than 0) then the entire conditional expression takes the value 0. Otherwise the conditional expression takes the value 100.

PROGRAM STRUCTURE

Managing Input and Output operators-Introduction, Reading a character, Writing a character, Formatted input and Formatted output, sample programs

STRUCTURE OF C PROGRAM

Every C program should consist of :
l One or more functions, one of which must be called main.
l The program will always begin by executing the main function.
l Additional function definitions may precede or follow main.

Each function must contain,

1. A function heading, which consist of a function name. Followed by an optional list of arguments enclosed in parenthesis

2. A list of argument declarations, if arguments are included in the heading (Arguments are symbols that represent information being passed between the functions and other parts of the program)

3. A compound statement, which comprises of the remainder of function.

DATA INPUT

The header file required by the standard input/output library functions is called stdio.h

getchar Function

l Single characters can be entered into the program using the C library function getchar.
l The getchar function is a part of a standard C language I/O library.
l It returns a single character from the standard input device.
l The function does not require any arguments though a pair of empty parenthesis should follow the word getchar.

The general syntax is,
Character variable = getchar ( )

Where character variable refers to previously declared character variable.
Eg :

char c;

……

c = getchar();

scanf function

l A library function used to Input data into the computer from a standard device.

l This function can be used to enter any combination of numerical values, single characters and strings.

In general scanf function can be written as

scanf (control string, arg1, arg2 , arg3 , ….., arg n)

Where control string refers to a string containing certain required formatting information and arg1,arg2 … arg n are arguments that represent the individual input data items.

l The control string comprises of individual group of characters, with one character group for each input data item.

l Each character group must begin with a percent sign ( % ) followed by a conversion character.

The most frequently used conversion characters are,

Character Meaning

c data item is a single character
d data item is a decimal integer
e data item is a double value
f data item is a floating point value
s data item is a string followed by white space
Eg :

#include

main()
{
char item[20] ;
int number;
float cost;
………
scanf(“%d, %f ”,&number, &cost);
………
}

the control string is “%d, %f “. It contains two character groups.

l The first character group, %d, indicates that the first argument( number) represents a decimal integer value

l The second character group, %f, indicates that the second argument(cost) represents floating point number.

l All arguments other than array names should be preceded by an ampersand as in number and cost.

DATA OUTPUT

putchar Function

l Single characters can be displayed using the C library function putchar.
l The putchar function is complementary to the getchar function.
l It transmmits a single character to the standard output device.
l It must be expressed as an argument to the function, enclosed in parenthesis.

The general syntax is,

putchar(character variable)

Where character variable refers to previously declared character variable.

Eg :

char c;

……

putchar(c);

The first statement declares c as a character type variable. The second statement causes a current value c to be transmitted to the standard output device.
printf Function

l It is a library function which is used to output data from the computer onto a standard output device
l This function can be used to output any combination of numerical values, single characters and strings.
l The printf function moves data from the computers memory to the standard output device.

In general printf function can be written as

printf ( control string, arg1, arg2 , arg3 , ….., arg n )

Where control string refers to a string containing certain required formatting information and arg1,arg2 … arg n are arguments that represent the individual input data items.

l The control string comprises of individual group of characters, with one character group for each input data item.

l Each character group must begin with a percent sign ( % ) followed by a conversion character.

l The conversion characters used are same as the one used in scanf function.

Eg :

#include

main()
{
int number;
float cost;

………

printf(“%d, %f ”, number, cost);
………
}

The control string is “ %d, %f “. It contains two character groups. The first character group, %d, indicates that the first argument( number) represents a decimal integer value
The second character group, %f, indicates that the second argument(cost) represents floating point number.

Note : All the arguments are not preceded by an ampersand.

This differ from the scanf function which requires ampersands for all arguments other than array names.

Decision Making-Introduction, Decision making with IF statements, SWITCH statements, Break statements, Continue statements and GOTO statements

CONTROL STRUCTURE

IF ELSE

The if statements allows branching (decision making) depending upon the value
or state of variables.
This allows statements to be executed or skipped, depending upon
decisions.

The basic syntax is,


if (expression)
statement1 or block ;
else
statement2 or block ;


The expression is evaluated and if the expression is True, statement1 is executed. If the expression is False (if the expression is zero) then statement 2 is executed.
Eg :

if(result >= 45)
printf(”Pass “);
else
printf(” Fail”);

Here the expression (result >= 45) is evaluated and if the value of the result variable is
greater than or equal to 45 then Pass is printed. If the value is less than 45 then Fail is printed.

BLOCK

If we wish to have more than one statement following if or the else, they should be grouped together between curly brackets. Such a grouping is called a compound statement or a block.

Example of use of a statement:

if(result >= 45)
printf(”Passed\n”);
else
printf(”Failed\n”);






Example of use of a block:

if(result >= 45)
{
printf(”Passed\n”);
printf(”Congratulations\n”)
}
else
{
printf(”Failed\n”);
printf(”Better luck next time\n”);
}

NESTED IF

l Is the way of doing a multi-way decision based on several conditions.
l The way it is done is by using the else if variant on the if statement.
l Works by cascading several comparisons.
l As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed.

The general syntax for this is

if(expression1)
{
statements ;
}
else if(expression2)
{
statements ;
}
else if(expression3)
{
statements ;
}
Consider the example to award grades depending on the exam result.

if(result >= 75)
printf(”Passed: Grade A\n”);
else if(result >= 60)
printf(”Passed: Grade B\n”);
else if(result >= 45)
printf(”Passed: Grade C\n”);
else
printf(”Failed\n”);

In this example, all comparisons test a single variable called result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used with more or fewer else if’s, and the final lone else may be left out. It is up to the programmer to devise the correct structure for each programming problem.



SWITCH
The Switch statement is a multi-way decision that tests whether an expression matches one of a number of constant values, and branches accordingly.
The general syntax is,

switch(expression) {

case value1:
program statement;
program statement;
……
break;
case valuen:
program statement;
…….
break;
default:
…….
…….
break;
}

l The keyword break must be included at the end of each case statement.
l The default clause is optional, and is executed if the cases are not met. The right brace at the end signifies the end of the case selections.
Eg :
#include

main()
{
int menu, numb1, numb2, total;

printf(”Enter in two numbers –>”);
scanf(”%d %d”, &numb1, &numb2 );
printf(”Enter in choice\n”);
printf(”1=Addition\n”);
printf(”2=Subtraction\n”);
scanf(”%d”, &menu );

switch(menu) {
case 1: total = numb1 + numb2;
break;
case 2: total = numb1 - numb2;
break;
default: printf(”Invalid option selected\n”);
}
if(menu == 1)
printf(”%d plus %d is %d\n”,numb1,numb2, total);
else if( menu == 2 )
printf(”%d minus %d is %d\n”,numb1,numb2, total);

}

Sample Program Output

Enter in two numbers –> 25 10
Enter in choice
1=addition
2=subtraction
2
25 minus 10 is 15

NOTE

Switch is well structured, but can only be used in certain cases where
l Only one variable is tested, all branches must depend on the value of that variable.
l Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.


Branching and Looping-Introduction, WHILE statements, DO statements, FOR statements, Jumps in loops

LOOPS
C gives you a choice of three types of loop, while, do while and for.

l WHILE
l DO WHILE
l FOR

WHILE LOOP

l The while loop keeps repeating an action until an associated test returns false.
l This is useful where the programmer does not know in advance how many times the loop will be traversed.

The Syntax is,

while(expression)

{
statement1 ;
statement2 ;
statement3 ;
..…..
…….
….…
statementn ;
}







Eg :

#include

main()
{
int i = 1;
while ( i < 5 )
{
printf ( “%d\n”,i);
i++;
}

}

Sample Program Output:

1
2
3
4

Here the while loop first checks the value of i and if its less than 5 it prints the value and the value of i is incremented by 1.The loop continues till the expression ( i < 5 ) becomes false i.e if the value of i is greater than or equal to 5.

DO WHILE

l The do while loops is similar, but the test occurs after the loop body is executed.
l This ensures that the loop body is run at least once.


The syntax is,

do
{
statements;
}
while(expression) ;


l The statements are executed and then expression is evaluated.



Eg :

#include

main()
{
int i = 1;

do
{
printf(”%d\n”,i);
i++;
}
while(i < 5) ;
}

Sample Program Output :

1
2
3
4


The output is same as the example in while loop.
The only difference is that the condition is tested at the end.
The same example using while loop is shown below:


#include

main()
{
int i = 1;
while(i < 5)
{
printf(”%d\n”,i);
i++;
}

}

Sample Program Output:

1
2
3
4

A COMMON EXAMPLE

while loop


#include

main()
{
int i, j ;
i = 1;
j = i + 1;
while(j < 1)
{
printf(”%d\n”,j);
}
}
Sample Program output

Nothing will be printed

v The value of i is initialized to 1
v Then j is assigned a value i+1.
v Now j will have a value 2.
v The while loop condition fails as value of j is greater than 1.
v So a nothing will be printed because the printf statement will not be executed.
do while Loop


#include

main()
{
int i ,j ;
i = 1;
j = i + 1;
do
{
printf(”%d\n”,j);
}
while(j < 1) ;
}


Sample Program output

2

v The value of i is initialized to 1
v Then j is assigned a value i+1.
v Now j will have a value 2.
v Here the condition is tested only at the end. So the value of j is printed once even though the condition fails.

NOTE

Difference between while and do while :

WHILE DO-WHILE

1. Entry control structure Exit control structure
2. Loop may or may not be executed Loop is executed at least once

for Loop


l The for loop is frequently used, usually where the loop will be traversed a fixed number of times.
l It is very flexible.

The general syntax is,

for(expression1 ; expression2 ; expression3)
{
statements ;
}

Eg :

Printing ten numbers using the while loop:

#include

main()
{
int count=1;
while(count<=10)
{
printf(”%d “,count);
count = count+1 ;
}
printf(”\n”);
}

The same example using the for loop equivalent to while loop:

#include

main()
{
int count;
for(count = 1; count < = 10; count = count+1)
{
printf(”%d “,count);
}
printf(”\n”);
}


Sample Program Output

1 2 3 4 5 6 7 8 9 10

v The integer variable count is initialized to 1.
v The for loop continues as long as the condition (count <= 10 ) is True.
v At the beginning of the program the value of count is 1 and the condition count <= 10 is satisfied, so the printf statement is executed.
v The count is incremented by the condition count = count +1.
v This process continues till the value of count reaches 11.
v When the value of count is 11 then the condition fails and loop is exited.


BREAK

l The break statement provides an early exit from loops.
l The Break causes the innermost enclosing loop to be exited.
l It can be used within while, do – while, for or switch statement.

It is generally written as,

break;
Eg :

switch(choice)
{

case ‘G’ : { printf(“Green “);
break; }

case ‘Y’ : { printf(“Yellow “);
break; }

case ‘R : { printf(“Red “);
break; }

case ‘V’ : { printf(“Violet “);
break; }

}

Here depending on the value of the variable choice, the corresponding block will be executed.
Note : A break is given at each block in order to transfer control out of the particular block and to prevent execution of the of succeeding group of statements.

CONTINUE
l The continue statement is used to bypass the remainder of the current pass through a loop.
l The loop does not terminate when a continue statement is encountered.
l The remaining loop statements are skipped and the computation proceeds directly to the next pass of the loop.

It is simply written as ,

continue;
Eg : A program to Print odd Numbers.

#include

main()
{
int i;
for(i = 1 ; i <= 10 ; i++)
{
if( (i%2)== 0 )
{ continue;}
printf(“%d\n”,i);
}

}

Sample Program output

1
3
5
7
9

l In the for loop i is divided by 2 and the remainder is obtained by the modulus operator.
l If the remainder is 0 then it’s a even number and is NOT printed.
l So a continue here skips the printf statement and proceeds to the next iteration.
l Thus only the odd numbers between 1 and 10 are printed.

GOTO

The goto statement is used to alter the normal execution of the program by transferring the control to some other part of the program. The general syntax is,

goto label;

l Label is the identifier used to label the target the statement to which the control is to be transferred.

NOTE : Each label in the program must have a unique label and no two
labels should have the same label.

The target statement should appear as,

Label : statements

Eg :
………

if(x < 0) goto error;

………

error : printf(“The Number is less than 0”);



All variables declared outside of a function are GLOBAL.
! Global variables have global scope, i.e., they are seen in ALL the functions.

! All variables declared within a function are LOCAL to that function.

! Local variables have local scope. They “exist” only within the function that declares them.

Pre-execution (checking) loops: (may never execute) for loop while loop

Post-execution (checking) loop: (executes at least once) do-while loop

for( init. cond. ; logic cond. ; increment )
{
statement(s) ;
}

Example:
for( x = 34; x < 1104; x++)
printf(“looping ”); //shortcut notation

while ( logic condition )
{
statement(s) ;
}
Example:
short x = 0;
while( x > 5)
x –;

do
{
statement(s) ;
}
while ( logic condition ) ;
Example:
do
x = x + 123; //shortcut notation
while( x < 12345 );

Preprocessors: General (1)
Preprocessors are executed before the program is compiled.
They specify how to the program should be compiled.
They can not be changed during the program execution.
All preprocessors start with the pound
sign (#) and do not have a semicolon at the end

Applications:
Write programs for different operating systems
Debugging!
Preprocessor Examples:


Arrays -Initialization, Characteristics, one, two and multi dimensional arrays, operations with arrays, Handling of Character Strings-Declaration & Initialization of Strings
Display of Strings with Different Formats, String standard functions
User defined functions–Defining and declaring function prototypes, the return statement
Types of functions, Call by Value, Call by reference, Function returning more values, Function as an argument, Function with operators, Function & decision statements, Function and loop statements, Function with arrays & pointers, Recursion, Pointer to functions, Structures–Features, initialization, structure within structure, array of structures, pointer to structure, Structures and functions, Union, Union of structures,
Pointers- Declaration, Arithmetic operations with pointers, pointers and arrays, pointers and two-dimensional arrays, Array of pointers, pointer to pointer, pointers and strings, void pointers ,Sample Programs,
Preprocessor Directives-#define, #include, #ifndef, #error, #line directives, Developing a C program-Guidelines
COMPILER, which translates the source code into machine code
COMPILER, which translates the source code into machine code. This produces output in a format that the computer can understand.
LINKER
Sometimes the source code is still lacking some parts, so after going through the compiler, the code is passed through a LINKER. This basically “links” the source code to other library or object files so that the final program is produced. Imagine the program being a jigsaw puzzle – the linker simply puts together missing pieces to complete the program.
Declaring Arrays
You need to make a declaration before using an array. To declare an array, you need to specify its data type, its name and, in most cases, its size. Make sure the array has a valid name. Here’s an example:
int arrayOfInts[5];
This reserves memory for an array that to hold five integer values. The number of elements should be enclosed in the square brackets. If you don’t specify the number of elements during the declaration, you have declared an UNSIZED array – the size will be calculated when you insert values into it.
Initializing Arrays
You can assign values to the array in several ways. For example, if I wanted an array to hold the numbers 1 through to 10, I could do this in several ways, as this example demonstrates:
int main() {
int arrayOfInts1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int arrayOfInts2[10];
int arrayOfInts3[] = {1,2,3,4,5,
6,7,8,9,10}; /* an unsized array */
int arrayOfInts4[10];
int i;
arrayOfInts2[0] = 1;
arrayOfInts2[1] = 2;
arrayOfInts2[2] = 3;
arrayOfInts2[3] = 4;
arrayOfInts2[4] = 5;
arrayOfInts2[5] = 6;
arrayOfInts2[6] = 7;
arrayOfInts2[7] = 8;
arrayOfInts2[8] = 9;
arrayOfInts2[9] = 10;
for(i=0 ; i<10 ; i++) {
arrayOfInts4[i] = i + 1;
}
return 0;
}
Printing Out Arrays
One of the commonest ways to print out the contents of the array is to use a loop. I personally prefer using a for loop, like this:
#include
int main() {
int anotherIntArray[5] = {1,2,3,4,5};
int i;
for(i=0 ; i<6 ; i++) {
printf(”anotherIntArray[%d] has a value of %d\n”,
i, anotherIntArray[i]);
}
return 0;
}
Output:
I iterated one element too far to demonstrate what happens if you did. As you can see, MSVC++ seemed to print out a random number.
You can also use a loop with scanf to insert elements:
#include
int main() {
int anotherIntArray[5];
int i;
printf(”Enter 5 integers one by one “);
printf(”pressing return after each one:\n”);
for(i=0 ; i<5 ; i++) {
scanf(”%d”, &anotherIntArray[i]);
}
for(i=0 ; i<5 ; i++) {
printf(”anotherIntArray[%d] has a value of %d\n”,
i, anotherIntArray[i]);
}
return 0;
}
Character Arrays
So far I’ve used arrays of integers in my examples – probably the type I’ve been using the most. You can use arrays for floats and doubles as well as chars.
Character arrays have a special property…
Each element of the array can hold one character. But if you end the array with the NULL CHARACTER, denoted by (that is, backslash and zero), you’ll have what is known as a STRING CONSTANT. The null character marks the end of a string – useful for functions like printf. Time for an example…..
#include
int main() {
char charArray[8] = {’F',’r',’i',’e',’n',’d',’s’,”};
int i;
for(i=0 ; i<8 ; i++) {
printf(”charArray[%d] has a value of %c\n”,
i, charArray[i]);
}
printf(”My favourite comedy is %s\n”, charArray);
/* Alternative way */
return 0;
}
Output:
Single Dimensional Arrays
Sometimes it’s inconvenient to call a function that requires a long list of arguments.
One way around this, is to store your variables into an array, then pass a POINTER to the array to the function. This method will be discussed in greater detail in the pointers section, but for now you need to know that the array isn’t actually passed to the function – just the array’s location in the memory. This is known as PASS BY REFERENCE. The name of an array references the array’s location in the memory, its ADDRESS.
#include
int addNumbers(int fiveNumbers[]); /* declare function */
int main() {
int array[5];
int i;
printf(”Enter 5 integers separated by spaces: “);
for(i=0 ; i<5 ; i++) {
scanf(”%d”, &array[i]);
}
printf(”\nTheir sum is: %d\n”, addNumbers(array));
return 0;
}
int addNumbers(int fiveNumbers[]) { /* define function */
int sum = 0;
int i;
for(i=0 ; i<5 ; i++) {
sum+=fiveNumbers[i]; /* work out the total */
}
return sum; /* return the total */
}
Notice that I’ve left the size of the array blank in both the function declaration and definition – the compiler works it out for you. Also, when I called the function, I passed on the name of the array. This is the equivalent to passing &array[0] – the address of the first element. You’ll learn about the address-of operator later.
Multidimensional Arrays
This is similar to passing 1D arrays but, in the function declarations you must specify all the dimension sizes (but the leftmost one is optional).
#include
void printArray(int array[][4]); /* declare function */
int main() {
int array[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
printArray(array);
return 0;
}
void printArray(int array[][4]) { /* define function */
int i, j;
for(i=0 ; i<3 ; i++) {
for(j=0 ; j<4 ; j++) {
printf(”%2d “, array[i][j]);
}
printf(”\n”);
}
}
& – The “Address of” Operator
Before I tell you what a pointer is, I’d have to introduce you to this operator.
It looks familiar – we saw it in the bitwise operators section. However, bitwise AND takes two operands like this: a & b, but the ADDRESS OF operator only takes one on the right: &x.
Recall that when you declare a variable, you reserve bytes in the computer’s memory for that variable. The allocated memory is referenced by the variable name and must be unique.
You can picture the computer’s memory as a very long row of slots. Now, each slot has a unique ADDRESS, which is expressed in hexadecimal format. It’s like a long road of houses – each house has a unique number in decimal format. In each occupied house, there are people.
In our case, the houses are memory slots, and the people are the variables.
Now suppose we wanted to find out where in the memory a variable lives. We can use the address-of operator. &x returns the “address of x” in hex format.
#include
int main() {
int x = 0;
printf(”Address of x “);
printf(”= 0x%p \n”, &x);
return 0;
}
Output: Address of x = 0×0065FDF4
%p is the format specifier for addresses (%x would still compile OK). 0x in the printf function is there to signify that a hex number follows.
Recall: scanf(”%d”, &x);
- You can translate this as: “take the inputted integer and put it in the address of x“.
Left and Right Values
Now let’s look at the assignment operator:x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x, say.
Also known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.
So x is an L-value because it can appear on the left as we’ve just seen, or on the right like this:y = x;
However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.
Pointers
POINTERS are VARIABLES that store the memory address of other variables.
Suppose we had an integer variable, x. We know how to get the address of x using &, but how do we store the hex value returned by &x ?
This is where pointers come into play. A pointer is a variable, so it is declared just like a variable. The only difference is that pointer variables must have the DEREFERENCE OPERATOR, *, before its name.
Don’t confuse this with the multiplication operator though – multiply takes two operands (e.g. x*y), dereference only takes one (e.g. *x).
The data type of a pointer must match the data type of the variable it points to.
Let’s look at declaring and initializing pointers…
int x;
float y;
int *pointer_to_x;
pointer_to_x = &x;
float *pointer_to_y = &y;
/*a simpler way*/
Finally, *pointer_to_x = &x; causes a compilation error, so be careful with the way you declare and initialize your pointers.
char * is somewhat special, and will be looked at in the string section.
Warning
You compiler might complain if you try and declare variables after creating pointers, so it’s best if you declare all your variables at the beginning of main, rather than “on the fly” e.g. halfway through main.
Accessing Variable Values Using Pointers
Now that you have a pointer that points to a variable, how can we retrieve the value it’s pointing to?
Answer: you can access the variable’s value using the dereference operator. Here’s an example:
#include
int main() {
int x = 12;
int *ptr = &x;
printf(”Address of x: 0x%p\n”, ptr);
printf(”Address of x: 0x%x\n”, &x);
printf(”Address of ptr: 0x%x\n”, &ptr);
printf(”Value of x: %d\n”, *ptr);
return 0;
}
Output:
The first 2 printf statements demonstrates that the address of x is stored in the pointer variable, ptr. Notice how %p returns a full 8 digit hex value in uppercase – maybe I should’ve used %X for the address of x for clarity.
The 3rd printf demonstrates that ptr itself has a place in the memory, which shows it’s a variable.
The final printf uses the dereference operator to extract the value pointed to by ptr, like this: *ptr.
Pointers and Arrays
When I first learnt pointers, I kept thinking: “Why should I use pointers?!!”. Looking at my previous example, I could’ve simplify things a little by not using pointers.
Pointers are useful when it comes to arrays.
One less obvious fact is that the name of an array is a pointer, simply because the name points to the first element of that array.
Try and picture this: when you initialize an array (of size 10, lets say), the computer picks a row of 10 CONSECUTIVE unused memory slots and stores the values in them.
The name of the array refers to the base of the array, that is, the very first memory slot of that array (which holds the first element).
So if the name is a pointer, we should be able to extract the first element using the dereference operator. In other words, *nameOfArray should return the value of nameOfArray[0].
#include
int main() {
int x[10] = {0,1,2,3,4,5,6,7,8,9};
printf(”Address of x[0]: 0x%p\n”, &x[0]);
printf(”Address of x: 0x%p\n”, x);
printf(”Value of x[0]: %d\n”, x[0]);
printf(”Value of x[0]: %d\n”, *x);
return 0;
}
Output:
So the name of the array points to the first element, as assumed.
Pointer Arithmetic
Once we’ve created a pointer that points to a certain variable, we can either reassign it another variable’s address, or we can move it around by performing POINTER ARITHMETIC.
Suppose we had an int pointer, ptr. If we say ptr++, ++ptr or ptr+=1, we’re actually moving the pointer forward by 2 bytes (i.e. the size of its data type). So it’ll point somewhere else in the computer’s memory.
Similarly, ptr–, –ptr and ptr-=1 will move the int pointer “back” 2 bytes.
And you’re not restricted to move in steps of 1 either: ptr+=n will move it “forward” by n*2 bytes, (assuming ptr is an int pointer).
The larger the data type, the larger the step size. So if ptr was a double pointer, ptr-=3 will move it “back” by 3*8 = 24 bytes.
Warning
The arithmetic assignment operators you can use with pointers are += and -=
ptr*=2 and ptr/=2 cannot be used!
Passing Pointers to Functions
Recall from a previous tutorial that you can pass arrays to functions. The array isn’t actually passed to the function – just the array’s address, or more precisely, a pointer to the array. This is known as PASS BY REFERENCE. The name of an array is a pointer to the first element.
This example is similar to a prevoius example in the Passing Arrays to Functions section, but notice the new function header and the pointer arithmetic inside the function.
Notice that when you pass an int * to a function, there should be an int * declared variable in your function header. The basic trick is to remove the [] and add a * before the array name. See the alternative version back in the Passing Arrays to Functions section for a comparison.
Inside the for loop, the dereference operator is used to fetch the value pointed to and added onto sum. At the end of each loop iteration, the fiveNumbers pointer is incremented to point to the next value.
#include
void half(int *number); /* declare function */
void half2(int number); /* declare function */
int main() {
int i = 8;
int *ptr = &i; /* create a pointer to i */
half(ptr);
printf(”The value of i is %d\n”, i);
half(&i);
printf(”The value of i is %d\n”, i);
half2(i);
printf(”The value of i is %d\n”, i);
return 0;
}
void half(int *number) {
*number = *number/2;
}
void half2(int number) {
number = number/2;
}
Output:
You can see that passing ptr to half modifies i. Passing &i to half halves i again – remember that ptr simply stores the address of i, i.e. &i.
Passing i to half2 (note the difference between half and half2) has no effect on i when program flow returns to main.
Introduction, Characteristics of Computers – Speed, Accuracy, D
Handling of Character Strings-
A string is an array of characters. Strings must have a 0 or null character after the last character to show where the string ends. The null character is not included in the string.
There are 2 ways of using strings. The first is with a character array and the second is with a string pointer.
A character array is declared in the same way as a normal array.
char ca[10];
You must set the value of each individual element of the array to the character you want and you must make the last character a 0. Remember to use %s when printing the string.
char ca[10];ca[0] = 'H';ca[1] = 'e';ca[2] = 'l';ca[3] = 'l';ca[4] = 'o';ca[5] = 0;printf("%s",ca);
String pointers are declared as a pointer to a char.
char *sp;
When you assign a value to the string pointer it will automatically put the 0 in for you unlike character arrays.
char *sp;sp = "Hello";printf("%s",sp);
You can read a string into only a character array using scanf and not a string pointer. If you want to read into a string pointer then you must make it point to a character array.
char ca[10],*sp;scanf("%s",ca);sp = ca;scanf("%s",sp);
Declaration & Initialization of Strings
char string[24]=”mech”
String standard functions
String handling functions
The strings.h header file has some useful functions for working with strings. Here are some of the functions you will use most often:
strcpy(destination,source)You can’t just use string1 = string2 in C. You have to use the strcpy function to copy one string to another. strcpy copies the source string to the destination string.
s1 = "abc";s2 = "xyz";strcpy(s1,s2); // s1 = “xyz”
strcat(destination,source)Joins the destination and source strings and puts the joined string into the destination string.
s1 = "abc";s2 = "xyz";strcat(s1,s2); // s1 = “abcxyz”
strcmp(first,second)Compares the first and second strings. If the first string is greater than the second one then a number higher than 0 is returned. If the first string is less than the second then a number lower than 0 is returned. If the strings are equal then 0 is returned.
s1 = "abc";s2 = "abc";i = strcmp(s1,s2); // i = 0
strlen(string)Returns the amount of characters in a string.
s = "abcde";i = strlen(s); // i = 5
User defined functions–
Defining and declaring function prototypes,
the return statement
Functions are sub-programs. You have already been using a function which is the main function.
You must always declare a function before the function that calls it. The main function will be calling our function so we will put ours above main.
First put its return value such as int or char. If you don’t want a return value then use void. After that give it a unique name and put a set of brackets after that. You then put the set of curly brackets which will have the sub-program between them. We will call our function Hello because it will simply print the word Hello on the screen.
#includevoid Hello(){printf("Hello\n");}
int main(){Hello();return 0;}
Parameters
Parameters are values that are given to a function so that it can perform calculations with them. The “Hello\n” which we used in the Hello function is a parameter which has been passed to the printf function.
You need to declare variables inside the parameter brackets to store the values of the parameters that are passed to the function. Here is an Add function which adds the 2 parameters together and then returns the result.
#includeint Add(int a,int b){return a + b;}int main(){int answer;answer = Add(5,7);return 0;}
You can pass the address of a variable to a function so that a copy isn’t made. For this you need a pointer.
#include
int Add(int *a,int *b){return *a + *b;}int main(){int answer;int num1 = 5;int num2 = 7;answer = Add(&num1,&num2);printf("%d\n",answer);return 0;s}
Introduction
Your computer’s memory is a resource – it can run out. The memory usage for program data can increase or decrease as your program runs.
Up until this point, the memory allocation for your program has been handled automatically when compiling. However, sometimes the computer doesn’t know how much memory to set aside (for example, when you have an unsized array).
The following functions give you the power to dynamically allocate memory for your variables at RUN-TIME (whilst the program is running). For the past tutorials, memory was allocated when the program was compiled (i.e. COMPILE-TIME).
To use the four functions discussed in this section, you must include the stdlib.h header file.
Introduction
A function can be thought of as a mini-program, where a group of statements are executed when the function is called.
A function is CALLED (or INVOKED) when you need to branch off from the program flow and execute the group of statements within that function. Once the statements in the function are executed, program flow resumes from the place where you called your function.
You’ve already encountered a few functions: main, printf and scanf.
The main function is special, in the way that it’s called automatically when the program starts.
In C, and other programming languages, you can create your own functions.
A Typical Function
Functions have 5 main features:
1.
The DATA TYPE is the data type of the RETURN VALUE of the function.
2.
The NAME is required as an identifier to the function, so that the computer knows which function is called. Naming of functions follows the same set of rules as the naming of variables.
3.
Functions can take ARGUMENTS – a function might need extra information for it to work. Arguments are optional.
4.
The function BODY is surrounded by curly brackets and contains the statements of the function.
5.
The RETURN VALUE is the value that is passed back to the main program. Functions exit whenever you return a value.
This is what a function definition might look like:
int squareNumber(int a)
{
int b = a*a;
return b;
}
The variables within the squareNumber function are LOCAL VARIABLES – when the function exits, variables a and b are deleted from memory.
int squareNumber(int a) is also known as the FUNCTION HEADER.
Declaring and Defining Functions
Before you use a function you must the function before the main function.
Like with variables, this involves writing the data type, then the function name. Unlike variables, you must also decalre all the arguments that the function will use.
The function declaration is a single statement consisting of the function header – don’t forget the semi colon at the end!
Here is an example with a function declaraion:
#include
void printAverage(int x, int y, int z);
/* the function declaration */
int main() {
int a, b, c;
printf(”Enter 3 integers separated by spaces: “);
scanf(”%d %d %d”, &a, &b, &c);
printAverage(a, b, c); /* the function call */
return 0; /* exit main function */
}
void printAverage(int x, int y, int z) {
/* the function definition */
float average = (float) (x + y + z) / 3;
/* coersion in practice! */
printf(”The average value of %d, %d and %d is %f\n”,
x, y, z, average);
}
It’s common practice to place the function definition underneath main – if you’re editing main most of the time, you wouldn’t want to scroll too far down the page to get to it!
You can put the function definition above it if you wanted. In that case you would not need the the semi-colon at the end of the function header as we would be declaring and defining it at the same time.
But if you place it underneath main, make sure you put the function declaration above main – see the example. This is because the computer won’t know if the function exists if you call it without it being declared in the first place. It’s the same with variables: you can’t assign anything to x unless you’ve declared x beforehand.
Notice that in the function call I had to pass three arguments to match the three arguments in the function definition. Also, the variable names in the function’s argument section didn’t have to match the variable names in the function call. The most important thing is that the data types match.
Functions That Call Themselves
#include
int factorial(int x);
int main() {
int a, b=1, temp;
printf(”Enter an integer: “);
scanf(”%d”, &a);
printf(”\n%d factorial is %d\n\n”, a, factorial(a));
printf(”Enter another integer: “);
scanf(”%d”, &a);
temp = a;
for( ; a>0 ; a–) {
b*=a;
}
printf(”\n%d factorial is %d\n”, temp, b);
return 0;
}
int factorial(int x)
{
/* n factorial, (or n!) is 1*2*3* … *n */
if(x!=0) {
return (x*factorial(x-1));
}
else
{
return 1;
}
}
A function that calls itself is said to be a RECURSIVE function.

· Declare the Function: We do this with a function prototype, which declares the function so that the compiler knows about it. This declaration provides a complete description of the function interface. Function prototypes usually precede main. They tell the compiler and us what a function will do, but not HOW it will do it.
· Write the Function Definition: The definition consists of a body and a header. The header is virtually a repeat of the prototype. The body contains the declaration and the executable statements for the function.
· Write the Call(s) to the Function: These calls cause the function to execute and return values (if there are any to be returned). While there is one prototype and one definition per function, there may be many calls, with different arguments.
Recursive function calls can be less efficient than a loop, and I don’t personally use them.
There’s nothing new in the last example for me to explain. Later, I will show you how to define your functions in file different to the one where main sits.
Knowing When Your Variables Are Accessible
All constants and variables have scope. In other words, the values they hold are accessible in some parts of the program, where as in other parts, they don’t appear to exist.
There are 4 types of scope: block, function, file and program scope. Each one has its own level of scope.
Block Scope
Recall that a statement block is a group of statements enclosed within an opening and closing curly brackets: {}.
Now, if you declare a variable within a statement block, when the program exits the block, the variable will cease to exist.
This type of variable, is said to have BLOCK SCOPE, and is also known as a LOCAL VARIABLE.
You’ve already used local variables before – when you defined your own functions, for instance. Outside of the function definition, the variable would not be visible, as shown in this example:
There are times when your program contains a nested block, like a for loop inside main(). If you were to declare and initialize a variable x outside the loop and then declare and initialize another variable called x inside the loop, they will occupy up different memory slots and are considered as different variables. The effect can be shown in this example:
Function Scope
This type of scope only applies to goto label names. You can’t have the same label name inside a function. However, you can have the same label name in different functions like this:
Program Scope
If you want to avoid passing arguments to your functions you can declare your variables outside any function blocks. Such variables are sometimes known as GLOBAL VARIABLES. Their value can be accessed from anywhere within the ENTIRE program. Take this example:
File Scope
FILE SCOPE is when a variable is only accessible until the end of the file.
A variable with file scope is a global variable declared with the the static keyword before the data type, like this:
static int x = 15;
This makes it impossible for x to be accessible by other files, other than the one it’s declared and initialized in.
This is useful for when you come to write your own header files and function prototypes as it can prevent compilation errors and potential bugs.
Let’s recap:
1.
Variables with BLOCK SCOPE (variables declared in a block, i.e. local variables) are the least accessible, as they are visible between an opening curly bracket and a closing one.
2.
Variables with FUNCTION SCOPE (goto labels in this case) are the next least accessible, as they are visible in a whole function.
3.
Variables with FILE SCOPE(global variables with the static specifier) are the second most accessible, as they are visible in the whole file.
4.
Finally, variables with PROGRAM SCOPE (variables declared outside any blocks, i.e. global variables) are always accessible throughout the program.
What is a struct?
A struct (short for STRUCTURE), is a collection of variables of different types. Structures are sometimes referred to as ABSTRACT DATA TYPES, or ADTs for short.
We already know how to store a group of variables of the same type using arrays.
Variables in a struct are called MEMBERS or FIELDS, and are accessed by their name.
Variables in an array are called ELEMENTS, and are accessed using square brackets an an index.
Declaring a Structure
Declaring a struct requires the struct keyword, followed by a name. Then you declare your collection of variables between a pair of curly brackets. For example:
struct human {
char *name;
int age;
float height;
};/* don’t forget this
semi colon!!!! */
It’s best to declare your struct before main.
human is now a structure type, with three fields: name, expressed as a string, an integer age and a floating point height.
You can put whatever data types you want. And you’re not limited to normal variables either – arrays and pointers can also go into a struct, though, you must specify an array size.
You can NOT use the assignment operator with the struct declaration.
NOTE: The size of a struct is the sum of the sizes of all the variables it holds.
Declaring Structure Variables
Like with enum, you can insert a list of variables after the end bracket like this:
struct album {
char *name;
char *artist;
int numTracks;
} CD1, CD2, CD3;
This declares three variables of the struct album type.
But if album was declared outside main, the three variables will be global variables.
So instead, you can write this inside main:
struct album CD1, CD2, CD3;
Or better still, declare your struct and write:
typedef struct album Album;
… then inside main:
Album CD1, CD2, CD3;
Try and group all your typedef statements outside main – it makes the code look neater and easier to maintain.
Initializing Structure Variables
Now that you know how to declare structure variables, there are two ways to initialize them: all the fields in one statement, or one field at a time.
To initialize all fields in one statement, you declare your variable as usual, but assign it a list of variables enclosed in brackets, like this:
struct human TR = {”Tony”, 12, 1.5};
This is similar to the method of initializing arrays.
Now the struct human variable, TR has all three fields initialized: the name field holds the string, “Tony”, the age field holds the integer, 12, and the height is 1.5.
To reference an individual field, you use the DOT OPERATOR to separate the struct variable name and the field name.
You can use the dot operator to initialize each field individually:
struct human TR;
TR.name = “Tony”;
TR.age = 12;
TR.height = 1.5;
To access each field, use the dot operator again.
For example, TR.age will return 12.
Advantages of char *name Over char name[50]
When I first encountered structs I used a sized char array to store strings.
Suppose I redefine human:
struct human {
char name[50];
int age;
float height;
};
The first disadvantage, is that the name array must have a size big enough to store any string I was going to use.
Secondly, the only (obvious) way to initialize a string field, is to do it all at once:
struct human TR = {”Tony”, 12, 1.5};
TR.name = “Tony” won’t work, simply because the only way of assigning a string into an array is when you declare an array: char name[5] = “Tony”; Recall that TR.name is actually a char pointer, but it’s an R-value in this case. In other words, assigning a value into it wouldn’t work, as it wasn’t declared as a char *. But…
TR.name[0] = ‘T’;
TR.name[1] = ‘o’;
TR.name[2] = ‘n’;
TR.name[3] = ‘y’;
TR.name[4] = ”;
… works because the elements of the name array are L-values.
If human was defined with char *name, you could use TR.name = “Tony”; because pointers are L-values: remember that strings are considered to be of type char * as well.
Arrays of Structure Variables
Like with the usual data types, you can store a group of similar typed variables in an array.
The method of declaring an array is the same as before, but initializing your elements isn’t as simple as first thought…
#include
typedef struct robot ROBOT;
struct robot {
char *name;
int energy;
};
int main()
{
int i;
ROBOT robots[3];
robots[0].name = “Lunar Lee”;
robots[0].energy = 50;
robots[1].name = “Planetary Pete”;
robots[1].energy = 20;
robots[2].name = “Martian Matt”;
robots[2].energy = 30;
/* robots[0] = {”Lunar Lee”, 50}; WON’T WORK,
BUT HERE’S ANOTHER WAY…
ROBOT robots[3] = { {”Lunar Lee”, 50},
{”Planetary Pete”, 20},
{”Martian Matt”, 30} }; */
for(i=0 ; i<3 ; i++) {
printf(”Robot %d is called %s “, i, robots[i].name);
printf(”and has %d units of energy.\n”, robots[i].energy);
}
return 0;
}
There is a quicker way of initialization, as shown in the commented section. It involves initializing the entire array all at once. Notice how I separated each array element with a line break for clarity. Also note that a group of fields must be enclosed in brackets as well: {”Lunar Lee”, 50}, for example.
Pointing to Structures and Using the Arrow Operator ->
Like with arrays, you can create pointers to structures. This time, the pointer stores the memory address of a structure variable.
Declaring you pointer follows along the same lines as with arrays, for example, if user was of type HUMAN (where HUMAN is struct human):
HUMAN *human_ptr = &user;
Or:
HUMAN *human_ptr; human_ptr = &user;
- Both of these would do the trick. However, make sure you’ve declared all your program variables before initializing pointers, else you’d encounter problems later on!
Your compiler might complain if you try and declare variables after creating pointers, so it’s best if you declare all your variables at the beginning of main, rather than “on the fly” e.g. halfway through main.
Now that you’ve created a pointer, you now access fields using the arrow operator, which is made up of two characters: a hyphen, then the greater than sign: ->. This replaces the dot operator, but other than that, accessing structure fields is similar:
human_ptr->name = “Martin”;
Is the equivalent of:
user.name = “Martin”;
Here’s the last example rewritten using pointers:
Passing Structures to Functions
This is similar to passing arrays to functions.
In the function declaration you need to specify the structure’s type, then a name and any other arguments.
Passing pointers is a better way, but for demonstration purposes, here’s a function that expects a ROBOT variable and displays some info:
#include
typedef struct robot ROBOT;
struct robot {
char *name;
int energy;
int IQ;
float velocity;
};
void info(ROBOT r); /* declare function */
int main() {
ROBOT r1 = {”Earthling Ed”, 100, 231, 4.1}; /* initialize 2 ROBOTs */
ROBOT r2 = {”Toxic Tom”, 150, 254, 2.5};
info(r1);
info(r2);
return 0;
}
void info(ROBOT r) {
printf(”%s has %d units of energy, an IQ of %d…\n”,
r.name, r.energy, r.IQ);
printf(”… and a velocity of %0.1f metres per second.\n”,
r.velocity);
}
Output:
Notice how I moved the function declaration below the typedef statement, since I used the defined type, ROBOT, in the function’s argument section.
info returns nothing, hence the void data type, and expects a ROBOT variable. r is a local variable that is created whenever info is called.
The %0.1f format specifier in the second printf displays the velocity correct to 1 decimal place. The zero is the minimum field width (the least number of spaces the number will occupy when displayed on screen).
Structures Within Structures
You can have fields of any data type in a structure, as well as pointers and arrays AND other structures.
You must create a struct before you use it in another struct, but declaring the field is similar to declaring an array.
#include
typedef struct weapon WEAPON;
typedef struct robot ROBOT;
struct weapon {
int ammo;
char *name;
int damage;
};
struct robot {
WEAPON weapon1; /* struct within a struct */
char *name;
int energy;
};
int main() {
ROBOT boss = { {100, /* boss.weapon1.ammo */
“Laser Gun”, /* boss.weapon1.name */
25}, /* boss.weapon1.damage */
“Krypton Kathy”, /* boss.name */
250}; /* boss.energy */
ROBOT *ptr1;
WEAPON *ptr2;
/*boss.weapon1.ammo = 100; alternative initialization –
notice I had to put:
boss.weapon1.name = “Laser Gun”;
this is AFTER declaring the 2 pointers above
boss.weapon1.damage = 25;
boss.name = “Krypton Kathy”;
boss.energy = 250;*/
ptr1 = &boss;
ptr2 = &boss.weapon1;
printf(”You have encountered %s.\n”, ptr1->name);
printf(”She has %d units of energy.\n”, ptr1->energy);
printf(”Her weapon is the deadly %s.\n”, ptr2->name);
printf(”Each hit takes up to %d units of energy off you.\n”,
ptr2->damage);
printf(”She has %d shots left.\n”, ptr1->weapon1.ammo);
printf(”You have 10 units of energy left. “);
printf(”Situation critical.\n Abort mission.\n”);
return 0;
}
Output:
In the definition of struct robot, you can see that I’ve used a struct weapon variable as one of the fields. struct weapon must been defined before struct robot, otherwise your compiler will complain about an undefined struct.
Inside main, I’ve declared and initialized a ROBOT variable. Look closely and you’ll see that there are 2 brackets surrounding the first three items – this is because the first three items belong to the struct weapon field.
After that, I declared two pointers – one that points to the boss and the other points to the weapon1 field of boss.
The first four printf statements make use of ptr1 and ptr2 to access certain fields, but in the fifth, notice that it’s ptr1->weapon1.ammo and not ptr1->weapon1->ammo. This is because weapon1 is not a pointer to a struct weapon, but an actual struct weapon field, hence the dot operator.
What is a union?
A union, is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time.
You can picture a union as like a chunk of memory that is used to store variables of different types. Once a new value is assigned to a field, the existing data is wiped over with the new data.
Declaring a union
Declaring a union is exactly the same as declaring a struct, except you use the union keyword:
union human {
char *name;
int age;
float height;
}; /* don’t forget this semi colon!!!! */
Once again, you can use a typedef statement to simply the declaration of union variables.
The size of an union is the size of its largest field. This is because a sufficient number of bytes must be reserved for the largest sized field.
Initializing Unions
Now, this is where things get a little different to structures. Like I said before, with a union, fields share the same memory space, so fresh data replaces any existing data. This example demonstrates what happens if you initialize all the data for a union variable, all at once:
#include
typedef struct robot1 ROBOT1;
typedef union robot2 ROBOT2;
struct robot1 {
int ammo;
int energy;
};
union robot2 {
int ammo;
int energy;
};
int main() {
ROBOT1 red = {10,200};
/* ROBOT2 blue = {15,100}; DOESN’T WORK WITH UNIONS */
ROBOT2 blue;
blue.ammo = 15;
blue.energy = 100;
printf(”The red robot has %d ammo “, red.ammo);
printf(”and %d units of energy.\n\n”, red.energy);
printf(”The blue robot has %d ammo “, blue.ammo);
printf(”and %d units of energy\n.”, blue.energy);
return 0;
}
Output:
First notice how similar the declaration of a union is to a struct.
Things get a little different inside main. You can’t initialize fields of a union variable all at once – try removing the correct initialization above and see what your compiler says. So I initialized each field separately…
The first printf statement displays the expected for the struct version of our robot.
The second printf shows you that the program has overwritten data in the ammo field with data of the energy field – this is how unions work. All fields share the same address, where as with structs, each field has its own address.
This example is similar to the last, except I used printf before initializing the energy field of the union:
#include
typedef struct robot1 ROBOT1;
typedef union robot2 ROBOT2;
struct robot1 {
int ammo;
int energy;
};
union robot2 {
int ammo;
int energy;
};
int main() {
ROBOT1 red = {10,200};
ROBOT2 blue;
printf(”The red robot has %d ammo “, red.ammo);
printf(”and %d units of energy.\n\n”, red.energy);
blue.ammo = 15;
printf(”The blue robot has %d ammo”, blue.ammo);
blue.energy = 100;
printf(” and %d units of energy.”, blue.energy);
return 0;
}
Data in the energy field has still overwritten the ammo field though – rearranging the printfs has changed made the outcome different from that of the last example.
Arrays of Union Variables
The concept is the same as that of structs. However, because of the problem of new data overwriting existing data in the other fields, the struct version of the following example won’t work if you simply replace all instances of struct with union.
#include
typedef union robot ROBOT;
union robot {
char *name;
int energy;
};
int main() {
int i;
ROBOT robots[3];
robots[0].name = “Lunar Lee”;
robots[0].energy = 50;
robots[1].name = “Planetary Pete”;
robots[1].energy = 20;
robots[2].name = “Martian Matt”;
robots[2].energy = 30;
for(i=0 ; i<3 ; i++) {
/*printf(”Robot %d is called %s “, i, robots[i].name);*/
printf(”and has %d units of energy.\n”, robots[i].energy);
}
return 0;
}
The reason why I commented out the printf that displays the name is because I initialized everything at once. As a consequence, by the time the program reaches the for loop the union holds an int variable, rather than a char *. In general, my program crashes whenever an int is passed to the string format specifier, %s – other compilers might produce a different result.
Unions Inside Structures
I can’t see any obvioud reasons why one might use unions, but here’s a case when they could be useful. Suppose we want a field of a structure to contain a string or an integer, depending on what the user specifies. Take this example:
#include
struct choice {
union {
char *name;
int age;
};
int number;
};
Final Remarks on Unions
Firstly, nested unions are possibly, but are a little pointless. One union has the same memory space for all fields. If one of your fields is a union, that union would also let its fields share memory space – the same memory space reserved for the first union!!
Pointing to unions, passing unions to functions and passing pointers to unions to function are all done in the same way as that of structs. To find out more, do some searching on the web
The C preprocessor is a program that is executed before the source code is compiled.
C preprocessor commands are called DIRECTIVES, and begin with a pound / hash symbol (#). No white space should appear before the #, and a semi colon is NOT required at the end.
You’ve already seen a directive: #include
This takes the specified file, and pastes its contents into the place where you put #include before the source code is compiled. So when you use printf, stdio.h is required so that the compiler knows what printf is.
#include
If a line starts with a hash, denoted by #, it tells the compiler that a command should be sent to the C PREPROCESSOR. The C preprocessor is a program that is run before compilation takes place (hence the name). #include is one of the many C preprocessor commands you’ll use.
Basically, when the preprocessor finds #include it looks for the file specified and replaces #include with the contents of that file. In a way, this makes the code more readable and easier to maintain if you needed to use common library functions. More preprocessor commands in the later sections…..
Header Files
Header files have the extension .h and the full filename follows from the #include directive.
They contain declarations to certain functions that you may or may not have used in your program.
For example, the stdio.h file is required if you have used functions like printf and scanf in your program. More about these two functions in the Standard Input and Output section.
There are two ways to include a header file:#include “stdio.h” and#include
If you use the double quote marks, it means that the directory you’re currently in, will be searched for first for the header file, before any other directories are searched.
If you use the angled brackets, directories other than the one you’re currently in, will be searched for the header file. Usually this will be the default directory for header files specified in your compiler, so you’ll probably be using square brackets all the time.
#define
#define allows you to make text substitutions before compiling the program. Here’s an example:
#define MAX 10
Before compilation, if the C preprocessor finds MAX as one word (so words like MAXIMUM will not be affected), in the source code, it replaces it with the number 10. If MAX was part of a string (for example, between the quote marks of printf), the preprocessor will leave it alone.
You can call the MACRO DEFINITION anything you want, as long as it doesn’t contain special characters or spaces and it cannot start with a number. I tend to use uppercase and underscore characters. You can define strings as well:
#define WEBSITE_NAME “Eddie’s Basic Guide to C”
- Every time the preprocessor sees WEBSITE_NAME it will replace it with “Eddie’s Basic Guide to C”
#define commands must be placed before the main function. The # symbol must be the first character of the line in the source code.
#include
#define MIN 0 /* #defines */
#define MAX 10
#define TRUE 1
#define FALSE 0
The program will loop until you enter a number between 0 and 10.
By the time the compiler receives the program, it won’t see words like MIN, MAX, TRUE or FALSE in the source code. Instead, it’ll see the numbers 0, 10, 1 and 0 respectively.
#undef and Macro Functions
If you’ve created a macro definition, you can use #undef to remove it. This means the preprocessor will no longer make anymore text substitutions associated with that word. Also, to change a definition, you must use #undef to undefine it, then use #define to redefine it.
You can use #define to create your own MACRO FUNCTIONS. These are useful when the function is relatively small.
For example:
#define SQR(a) (a*a)
Now if you write SQR(3) in your program, the preprocessor will replace it with (3*3) in your program, NOT 9.
Be careful with your brackets, as this example demonstrates:
#include
#define MAX(a,b) (a>b ? a : b) /* a “function” */
#define DIFF1 4-7
#define DIFF2 (4-7)
#define NUMBER 10
#undef NUMBER
/* now undefine NUMBER so that we can give it a different value */
#define NUMBER 7
printf(” now I live at number %d.\n”, NUMBER);
return 0;
}
Output:
Let’s look at the printf statements:
The compiler will see the first one as:
printf(”Out of %d and %d, %d is the bigger number.\n”,
a, b, (a>b ? a : b));
Since we initialized a and b beforehand, it’ll work out if a is greater than b, if so, return a from the expression, else return b.
The compiler will see the next two printfs as:
printf(”DIFF1 = 4-7. DIFF1 times 10 equals %d.\n”, 4-7*10); printf(”DIFF2 = (4-7). DIFF2 times 10 equals %d.\n”, (4-7)*10);
Notice how the preprocessor leaves DIFF1 and DIFF2 alone inside the string of printf. Looking at the above lines, you can clearly see why the top printf prints out -66, where as the bottom did the obvious and printed 30 – macro definitions are just text substitutions!
The next printf is seen as : printf(”I live at number %d.\n”, 10);
After that, NUMBER is undefined, then redefined, so the next printf will look like:
printf(” now I live at number %d.\n”, 7);
#ifdef, #ifndef and #endif
When you come to write big programs, sometimes you’ll have to go through a process called DEBUGGING, which involves reading through your program, and trying to find out what’s causing your program to go wrong.
One common method for debugging is to comment out sections of code to find that “bug”. But what if there are comment dotted around your source code? That’s when #ifdef and #ifndef come into play. If you try nesting your comments, you’re going to get a compilation error.
In the case of #ifdef, if the macro definition that follows immediately is defined with #define, the following code from that directive to the #endif directive will be considered as part of the program and will be compiled.
With #ifndef, it’s the other way round, i.e. if there isn’t a definition, the code up to the #endif directive will be considered as part of the program and will be compiled.
Example:
#include
#define WORD1
/* you don’t have to put an expression after the defined word */
int main()
{
#ifdef WORD1
printf(”1: WORD1 is defined so this bit is compiled.\n”);
#endif
#ifndef WORD2
printf(”2: WORD2 is not defined so this bit is compiled.\n”);
#endif
return 0;
}
Output:
What is a Header File?
Header files contain declarations to functions and variables and have a .h extension. Examples of header files include stdio.h, string.h and strlib.h.
stdio.h looks horrendous in Notepad, so here is an example of a simple header file:
#ifndef EXAMPLE_H
#define EXAMPLE_H
#endif
I called this example.h and will be using it later on by writing #include “example.h” in the source file of the main program.
The functions are defined in a separate source file, so you’ll need to place the extern keyword before the function declaration.
If the header was included the first time, EXAMPLE_H won’t be defined, so the file’s contents are copied and compiled. However, I’ve defined EXAMPLE_H in the second line so if I accidentally included the header file a second time, #ifndef EXAMPLE_H isn’t true, so the contents of the header file are not copied and compiled a second time. I ended the header file with #endif.
Introduction, Characteristics of Computers – Speed, Accuracy, D
Preprocessor Directives-
#define,
The #define directive substitutes token-string for all subsequent occurrences of an identifier in the source file. The identifier is replaced only when it forms a token. sFor instance, identifier is not replaced if it appears in a comment, within a string, or as part of a longer identifier.
A #define without a token-string removes occurrences of identifier from the source file. The identifier remains defined and can be tested using the #if defined and #ifdef directives.
example
#define max 10
#include,
ou can organize constant and macro definitions into include files and then use #include directives to add these definitions to any source file. Include files are also useful for incorporating declarations of external variables and complex data types. You need to define and name the types only once in an include file created for that purpose.
The path-spec is a filename optionally preceded by a directory specification. The filename must name an existing file. The syntax of the path-spec depends on the operating system on which the program is compiled.
example
#include
#ifndef,
The #ifdef and #ifndef Directives
[1]
The #ifdef and #ifndef directives perform the same task as the #if directive when it is used with defined( identifier ).
#ifdef identifier
#ifndef identifier

// equivalent to
#if defined identifier
#if !defined identifier
You can use the #ifdef and #ifndef directives anywhere #if can be used. The #ifdef identifier statement is equivalent to #if 1 when identifier has been defined, and it is equivalent to #if 0 when identifier has not been defined or has been undefined with the #undef directive. These directives check only for the presence or absence of identifiers defined with #define, not for identifiers declared in the C or C++ source code.
These directives are provided only for compatibility with previous versions of the language. The defined( identifier ) constant expression used with the #if directive is preferred.
The #ifndef directive checks for the opposite of the condition checked by #ifdef. If the identifier has not been defined (or its definition has been removed with #undef), the condition is true (nonzero). Otherwise, the condition is false (0).
The #if, #elif, #else, and #endif Directives
[2]
The #if directive, with the #elif, #else, and #endif directives, controls compilation of portions of a source file. If the expression you write (after the #if) has a nonzero value, the line group immediately following the #if directive is retained in the translation unit.
#error,
the error messages include the argument token-string and are currently not subject to macro expansion. These directives are most useful for detecting programmer inconsistencies and violation of constraints during preprocessing. The following example demonstrates error processing during preprocessing:
#line directives, Developing a C program-Guidelines
C Storage Classes
[3]
The “storage class” of a variable determines whether the item has a “global” or “local” lifetime. C calls these two lifetimes “static” and “automatic.” An item with a global lifetime exists and has a value throughout the execution of the program. All functions have global lifetimes.
Automatic variables, or variables with local lifetimes, are allocated new storage each time execution control passes to the block in which they are defined. When execution returns, the variables no longer have meaningful values.
C provides the following storage-class specifiers:
Syntax
storage-class-specifier:
auto
register
static
extern
typedef

[1]

[2]

[3]

No comments:

Post a Comment