Chapter 1: System Development Concept
- System:
A System is a collection or arrangement of entities or things that work together to achieve one or more common goals. It can also be defined as, a set of components linked together according to a plan to achieve a specific objective. In a typical system one or more inputs are changed into a desired output. Systems may be made up of other smaller systems, which are called as Subsystems. Subsystems in turn are made up of other subsystems. For example a Computer System is made up of number of subsystems, which are input subsystem, storage subsystem, processing subsystem and output subsystem.
Information System:
Information System is as a system, which gathers and delivers information to the people in an organization. The purposes of Information Systems are to process input, maintain files, and produce information and reports about the organization. An Information System, today, is considered as subsystem of business. An information system is a set of processes and procedures that transform data into information and knowledge. Information Systems consists of subsystems, including customized hardware and software along with data that’s central to the company or organization’s mission, trained users who know how to use the system to serve customers better, and procedures that outline precisely how to accomplish a task with out error. The five basic interacting components of any information system are;
1. Input:
Capturing / accepting components that enter into the system to be processed. Example: raw data.
2. Process:
Process that series of changes to be done on information, to convert input into output. Example: data processing.
3. Output:
Which produced by the transformation process to their ultimate destination. Example: reports.
4. Feedback
5. Control
TYPES OF INFORMATION SYSTEM
There are different types of Information Systems. They are:
a. Data Processing Systems (DPS)
A DPS process transactions and produce reports. DPS represents the automation of basic, routine processing to support operations. Typical examples of DPS are payroll, inventory, financial accounting etc.
b. Management Information Systems (MIS):
MIS can be defined as information system for providing information to support operations, management, and decision-making. MIS utilize computer, procedures, analysis, planning, control, decision-making, and a database. Users of MIS, normally, use a shared database.
c. Decision Support Systems (DSS):
DSS supports decision makers by providing information on demand. DSS tends to be used in planning, analysing alternatives and search for solutions. DSS is similar to MIS, in that, they both depend on a database as a source of data. DSS differs from MIS in that it emphasises the support of decision making in all of its phases. Though, the actual decision is still in the hands of the decision maker.
d. Expert Systems (ES):
Expert Systems capture the expertise of decision makers in solving problems. ES automates the decision-making process in a specific area, such as medical diagnoses or review of credit history for loan approvals.
System Development Life Cycle (SDLC):
System Development is the creation of new system or modification of old system. Systems development involves number of stages starting from Systems Study to Systems implementation and maintenance. SDLC is an organized way to build an Information System. SDLC, in fact, is a sequence of events carried out by Systems Analysts, Systems Designers, and users to develop and implement an Information System.
The system development life cycle (SDLC) can also be defined as, a framework for developing computer-based information system. In order words, SDLC is the overall process of developing information system through a multi-step process from investigation of initial requirements through analysis, design, implementation and maintenance. These activities are carried out in different phases, which are mentioned below:
1. Problem Definition
2. System Analysis
3. System Design
4. System Development
5. System Testing
6. System Implementation
7. System Evaluation
8. System Support & Maintenance
All these phases, together, are called a life cycle because they cover the entire life of an Information System.
Fig: Steps involved in SDLC
1. Problem Definition:
System definition is the process of defining the current problem, determining why a new system is needed and identifying the objectives of the proposed system. During Problem Definition Project team (members responsible for Systems Study) focus on completing the task, investigating the problem and deciding whether to proceed. In this phase the main aim is to answer “Why do we need a new system?” and “What are the objectives of the new system? ” .
2. System Analysis:
During System Analysis Project team (members responsible for Systems Analysis) focus on completing two tasks:
• analysing the current system and developing possible solutions to the problem.
• selecting the best solution and defining its functionality
This phase starts when the current computerised system is to be modified or current manual system is to be computerised. Systems Analysts then begin investigation, talking with the users. The first challenge is to define the problem accurately. When the problem of the current system is accurately defined, the users can decide whether to proceed or not.
Systems study is carried out by a small group of people who are familiar with Information System techniques, understand the part of the business and skilled Systems Analysts. Main activities included in the phase are; understanding the problem, feasibility analysis or study and system requirements.
3. System Design:
Systems Design is the process of planning a new business system to replace the old. But before this planning can be done, we must thoroughly understand the old system. Once the analysis is completed, the Systems Analyst has a firm understanding of what is to be done. The next step is how the problem can be solved.
The major objectives of Systems Design are:
• identification of reports and outputs the new system should produce.
• sketch the input screen and layout of menus options.
• description of data to be input, calculated and stored.
• individual data items, database and calculation procedures.
Major activities of Systems design are carried out by the Systems Designer. The Project team (members responsible for Systems Design), at this phase, finds the answers of problems like – how application accepts input data and stores in database, how many input screens are required, how the screen looks like? What kind of menus and options must there be? What kind of database will the system use? etc.
The Designers and programmers may use a top-down design or bottom-up design or the combination of both. In top-down design, the team starts with the large picture and moves to the detail. They look at major functions that the system must provide and break down these into smaller activities. Each of these activities will then be programmed in the next phase of SDLC.
In bottom-up design, the team starts with the details (for example, the reports to be produced by the system), then moves out to the big picture (major functions or process). This approach is particularly appropriate when users have very specific requirements for output – for example, payroll checks, which must contain certain pieces of information.
4. System Development:
During the development phase, Programmers play a key role. They create and customize the software for all the parts of the system. The actual coding and writing of the program is done at this stage.
The overall system is broken up into number of components. Then the programmers on the project team are assigned to specific components. The programmers write the necessary code. Technical writers and work with the programmers to produce the technical documentation for the system. The technical documentation includes information about software features and programming, about the data flow and processing, about the design and layout of the necessary hardware.
5. System Testing:
Testing is the process of executing a program with the intent of finding an error. Testing is an integral part. The testing process move from the individual component out to the system as a whole. The project team tests each component separately (unit testing), and then tests the components of the system with each other (system testing).
The major objectives of Systems Testing are:
• Ensure that software does not fail.
• Verify whether the software is running according to its specification.
• Verify whether the software is built and run according to user’s expectation.
System Testing is primarily divided into two types. They are;
a). White Box Testing
In this testing, a programmer can test cases that guarantee that every individual part in a program has been exercised at least once, all logical decisions on their true and false sides are executed, all loops are executed properly or not and internal data structures to ensure their validity are exercised. In other words, white box testing is a method of testing software that is based on knowledge of how the software is intended to function. White box testing is also called as structural testing or glass-box testing.
b). Black Box Testing:
Black box testing focuses on how the software functions without reference to how it is designed. The primary concern is whether the program works or not, how it is constructed. Black box testing is also known as functional testing. A programmer attempts to find errors in the following categories:
• Incorrect or missing functions.
• Interface errors.
• Errors in data structures or external database access
• Performance errors
• Initialization and termination errors.
6. System Implementation:
In this phase, the project team (especially systems analysts) install the new software and hardware, which has been tested. The users, then, start using the system to perform their jobs in user environment. In this phase, the user moves from old system to new system. This is called conversion
System Conversion:
The process of moving from old system to new system is called conversion. Conversion, in an organization, takes places in the Phase System implementation. If the system is replacing an existing one, implementation becomes critical. In such case, there are four different types of conversion strategies:
a). Direct conversion:
All users stop using old system at the same time and then begin using the new. This option is very fast, less costly but more risky.
b). Parallel Conversion:
Users continue to use old system while an increasing amount of data is processed through the new system. Both the systems operate at the same time until the new system works smoothly. This option is costly but safe approach.
c). Phased conversion:
Users start using the new system component by component. This option works only for systems that can be compartmentalized. This option is safe and conservative approach.
d). Pilot conversion:
Personnel in a single pilot-site use the new system, and then the entire organization makes the switch. Although this option may take more time, it is very useful in big organizations where a large number of people make the conversion.
7. System Evaluation:
The system evaluation is performed to identify its strengths and weaknesses. The actual evaluation can occur along any of the following dimensions;
• Operational Evaluation
• Organizational Impact Evaluation
• User Manager Assessment Evaluation
• Development Performance Evaluation.
8. System Maintenance:
Once installed, the software is often used for many years. However, both the organization and the users change. The environment may also change over a period of time. Therefore, software has to be maintained time to time. That is, modifications and changes will be made to the software files or procedures to meet user’s requirement. All these activities fall within Systems Maintenance.
Some errors in the system are also corrected during this phase. Changes, or upgrades, to the systems are made regularly during the remaining life span of the system. At some point, however, repairs to the system no longer meet the user requirements. Users start calling for a major modification or new system. At this point, the SDLC has come full circle, and the Systems study (Phase 1) begins again.
Computer Aided Software Engineering (CASE)
CASE stands for Computer-Aided Software Engineering. CASE is the technology for automating software development and maintenance. Project teams (members who develop information system) use special software applications for creating prototypes quickly, building diagrams, writing codes and managing development. These applications are called CASE Tools. Thus CASE Tools are the type of software that automates the development of information system.
Some popular CASE Tools are- Excelerator, IE Work Bench, etc.
PROTOTYPES
Prototypes are the experimental version of new software (or information system). Prototypes are designed to show the structure and design projected for the final product. Prototyping is used in the development of both new hardware and software systems and new systems of information management.
A typical Prototype consists of screens with few items like: buttons, fields and options. Each item in the Prototype has minimal functions. By experimenting with a prototype, users become familiar with the end product long before it is actually developed. Prototyping is an important component of Rapid Application Development (RAD). CASE Tools are used to design Prototypes.
System Documentation:
System manual contain the detailed technical information for each application system. It describes each of the major functions performed by the application, the data affected by the application and logical flow of data within the system. These manuals usually include:
• Narrative describing the purpose of the application
• Description of the files, database and records within application
• Display format and uses
• Possible sample report of the program.
The various ways of documenting are:
• Presenting in the flowchart.
• Using pseudocode
• Using the structured English and algorithms.
System Analyst:
The Systems Analysis is the process of totally understanding the current systems by collecting the facts, diagnosing the problems, and using the facts to improve the current system. Systems Analysis is done by the Systems Analyst.
A System Analyst is the person who is responsible for the analysis, design and implementation of the business system to the computer. A system analyst can be described as the person who will solve the business problem using compute technology so we need someone who is good at problem solving, who knows about business operation and who has a strong background in relevant areas of computer science.
Qualities (Skills / Knowledge) of System Analysts:
Expertise in system analysis and design comes with experience and time. However, there are some essential qualities that a Systems Analysts should possess, they are:
1. Communication Skills:
The analysts must be a good communicator. The analyst is the medium through which communication should flow smoothly. He or she must be able to gain information requirements from users and to communicate well with programmers.
2. Problem Solving Skills:
Systems are developed to solve problem. The analyst is a problem solver. He or she views the analysis of problem as a challenge. An analyst must have wide experience in solving problems. The steps of solving problems:
1. Define the problem
2. Analyze problem
3. Consider alternatives for removing the cause
4. Evaluate these alternatives and try to know their benefits and disadvantages.
5. choose the best alternatives.
3. Technical Knowledge:
The analyst needs enough computer experience to program and understand the capabilities of the computers. Analyst must be familiar with the capabilities and administration of hardware and software products.
4. Business Knowledge: The analyst should be capable of handling the situation through skilful application of tools and techniques. It is important for an analyst to completely understand the business environment for which the system is being developed. They must be familiar with existing business operations so that they can decide if a computer can do the better job.
Duties and Responsibilities of System Analysts:
The duty of the system analyst is to co-ordinate the efforts of all groups to effectively develop and operate computer based information systems. The major duties and responsibilities of a system analyst are as follows;
a. Defining User’s Requirements:
This particular duty is the most difficult and analyst will have to use several fact-finding techniques like interview, questionnaire, observation and automation.
b. Prioritizing requirements by agreement:
By conducting common meeting and arriving at a agreement or consensus, analyst can prioritize the requirements.
c. Analysis and Evaluation:
On the basis of facts and opinions, system analyst finds the best characteristics of the new or modified system which will meet the user’s stated information needs.
d. Solving problems:
System analyst is basically a problem solver. He must study the problem in depth and suggest alternate solutions to management.
e. Drawing up functional specifications:
The main duty of the analyst is to obtain the functional specifications of the system to be designed and specification must be non-technical so that users and managers can understand.
f. Designing system:
One of the major duties of the analyst is to design the system and it must be understandable to the system implementer.
g. Evaluating System:
It is analyst critical duty to evaluate a system after it has been in operation for certain period of time.
Role of a System Analyst
Success of every system development depends on the role of system analyst. The major roles of system analyst are:
1. Plan and develop new system or devise ways to apply existing system resources to additional operations.
2. Keep constant track of the system and constant interaction with management, middle level manager and working level personnel to achieve the logical and accurate perspective of the system.
3. Use techniques like structured analysis, data modelling, information engineering, mathematical model building, sampling and cost accounting to plan the system.
4. Specify the inputs to be accessed by the system, design the processing steps, and format the output to meet the users need.
5. Prepare the cost benefit and return on investment analysis to help the management decide whether implementing the propose system will be financially feasible.
6. Co-ordinate tests and observes initial use of the system to ensure that it performs as planned.
7. Prepare specification, work diagrams and structure charts for computer programmers to follow and then work with them to ‘debug’ or eliminate errors from the system.
8. Diagnose problems, recommend solutions and determine if the program requirements have been met.
FEASIBILITY STUDY:
Feasibility study is carried by Systems Analysts. The feasibility study or analysis carefully examines technical, economic, operational, scheduling, legal and strategic factors of a system to make sure that the system can be successfully developed. There major areas are considered while determining the feasibility of a project. They are:
a. Technical Feasibility Study:
This study is done by Systems Analysts to find out whether current technical resources which are available in the organization are capable of handling the user’s requirements. If not, then the analysts confirm whether the technology is available in the market.
b. Economic Feasibility Study:
This study evaluates the financial aspects of the project by performing a cost benefit analysis and addressing both tangible (real) or intangible benefits of the system. Economic or Financial feasibility considers the following points:
• Cost of doing full system study.
• estimated cost of hardware,
• estimated cost of software tools and systems development
The concerned organization must be able to evaluate the investment before implementing the entire system. If the system is not economically feasible, the project should not be proceed further.
c. Operational Feasibility Study:
Once it is determined that the system is both technically and economically feasible then it has to be concluded if it is operationally feasible.
It determines whether there will be any problems in implementing the system in its operational environments, looks at issues such as integrating the new system with existing systems in the organization, and assess how the system fits with the strategic business plan and strategic information plan of the organization.
d. Schedule Feasibility Study:
It addresses the time it will take to complete the project, taking into consideration available resources, and additional resources required, if any.
e. Legal Feasible Study:
This study takes into account factors such as copyrights, patents and government regulations.
f). Strategic Feasibility Study:
This study looks into factors such as the ability of the system to increase market share, give the firm a competitive advantages in the marketplace, enhance the productivity of knowledge workers and achieve other strategic goals of the organization.
Aims of Feasibility Study
The aims of feasibility study are;
• Defining the major problem areas, so that the system analyst can plan the strategy for the field investigation.
• Discovering the areas where some specialist knowledge is required for the full investigation.
• Determining whether the objectives stated in the assignment brief are reasonably attainable within the limitations and financial constraints period.
• Determining the approximate time required for the full investigation and there cost.
System Security:
In a common sense, security is freedom from any risk or danger. In context of computer science, security is prevention of or protection against;
• Access to information by unauthorized people
• Unauthorized destruction or alteration of that information.
In other words, a secure system is a system on which enough trust can be put to use it together with sensitive information. Computer Security is frequently associated with three core of areas;
a). Confidentiality: Ensuring that the data cannot be accessed by unauthorized persons.
b). Integrity: Ensuring that information is not altered by unauthorized person in a way that is not detectable by authorized persons.
c). Authentication: Ensuring the users are the person they claim to be.
Computer Security is also defined as :
a). Physical Security: Controlling the coming and outgoing of people and materials, protection against the elements and manuals disasters.
b). System Security: User access and authentication controls, maintaining file and file system integrity, make backups, log keeping and auditing.
c). Personal Security: Hiring employee to background screening, monitoring and handling departure of persons.
d). Network Security: Protecting network and telecommunication equipment, controlling access from un-trusted.
Networking
Introduction of Networking
Today, Computer networks form the backbone of most enterprises big or small around the world. Computer networks allow people remote to the computer to access the information available to that computer. Computer networks are being used to provide resource sharing between systems separated from a few to thousands of kilometers. This technology is leading many corporations to take advantage of the reduced price and increased performance in the workplace.
The dictionary defines a network as a “group of computers and associated devices that are connected by communications facilities.” Thus, a network can be anything from two computers connected by a serial cable to thousands of computers connected by high-speed data communication links dispersed throughout the world. In other words, computer network is a group of computers and associated peripherals connected by a communications channel capable of sharing files and other resources between several users.
Benefits of Networking:
A network provides three principle benefits: the ability to communicate, the ability to share hardware and software, and administrative support.
a). Information sharing and communicating:
The ability to communicate and share of information, inexpensively is one fo the popular benefits of networking technology. A network supports communication among users in ways that other media cannot. E-mail, the most popular form of network communication, provides low-cost, printable correspondence with the capability for forwarding, acknowledgment, storage, retrieval, and attachments.
b). Sharing of hardware and software:
Sharing involves not only information (database records, e-mail, graphics, etc.), but also resources (applications, printers, modems, disk space, scanners, etc.) Through its ability to share, a network promotes collaboration. This is the main attraction of popular software called “groupware” that is designed to allow multiple users to hold electronic meetings and work concurrently on projects
c). Centralized administration and support:
Networking simplifies administration and support tasks. The network administrator can perform administrative tasks on any computer on the network from just a single location. Also, it is more efficient for personnel to support one version of OS or application than to oversee a number of individual and unique systems and setups.
Roles o f computers in a network:
The computers in a network functions as either clients or servers. The roles of computers in a network are;
a). Clients:
A client is a computer that uses the resources made available by a server. The client must have sufficient processing power on its own to run applications that interact with the resources on the server.
b). Server:
A server is a computer that makes its resources available to the network and responds to the commands of a client. The server in a network performs a variety of complex tasks. The following are some examples of different types of server included on many large networks:
i). File and Print Servers:
File and print servers provides file and printer resources from a centralized location. When a client sends a request for data to the file and print server, the entire database or file is downloaded to the computer making the request. Once the document is saved back on the server, anyone on the network who has the proper access, or permission, may look at the file. In other word, file and print servers are used to store and retrieve centralized file and data records.
ii). Database Servers:
Database servers can store large amount of data in a centralized location and make this data available to users so that they do not need to download the entire database. With a database server, the entire database stays on the server and only the results of a request are downloaded to the computer making the request.
iii). Mail Server:
Mail server operates like database servers. Mail servers manage the e-mail services for the network.
Types of Network:
Network models classify the network on the basis of services and geographical area.
1). Network based on services:
Based on how the computers in a network are configured and how they access information, networks are classified into two types;
a). Peer-to-Peer Network:
In a peer-to-peer network, all computers have an equal relation to one another. There is not any computer, which can be regarded, as superior to another computer. All computers are equal and therefore are known as peers. Any computer in peer-to-peer network can functions as both client and a server simultaneously. Any computer in the network is capable of accessing data, software and other resources directly without any central controlling mechanism. Peer-to-peer network are also called as workgroups.
Advantages of using peer-to-peer network:
• Peer-to-peer networks are easy to build and operate
• Peer-to-peer networks are inexpensive to operate
• The network software used to operate peer-to-peer networks are simple and easy to operate.
• If any computer in a peer-to-peer network fails, then the resources on only that computer becomes unavailable without hampering the availability of resources on other computers.
Disadvantages of using peer-to-peer network:
• The required resources are difficult to find quickly because it could be in any one of the computers.
• Peer-to-peer networks are not very secure.
• A peer-to-peer network becomes very difficult to manage and operate when the number of computer involved exceeds 15 to 20.
b). Client-Server Network:
Client server networks have become standard models for networking. In client-server network, there is a clear distinction between the computers depending upon their functionality; clients and servers. Servers are powerful computers dedicated to managing files or documents (file server), printers (print servers), web pages (web servers) etc. Client are less powerful computer on which users do their job. Client depends upon server computers to access required resources.
Advantages of using client-server network:
• Since the resources are usually located in servers, the resources are easy to find.
• Client-server network can be made very secure. The resources on the server can be controlled very tightly by identifying, who can access the resources and who cannot.
• Client-server network are very scalable. i.e. the number of clients that can be connected in a client-server network is not limited.
Disadvantages of using client-server network:
• It cost more to implement and operate than the peer-to-peer network.
• If the server in a client-server network fails, then the clients cannot access any resources.
• Specialized software is needed to implement a client-server network.
2. Network based on Geographical Area:
1). Network based on Geographical area:
Based on size and distance coverage of networks, the computer network is divided into three types:
a). Local Area Network:
A local area network (LAN) refers to a combination of computer hardware and transmission media that is relatively small. Normally, LAN is entirely contained within a school, college, building etc. LANs is typically comprised of only one transmission media type such as coaxial cable or twisted pair cable but never both. The features of LAN are;
• It covers short geographical area.
• LANs are characterized by comparatively high speed communication.
• LAN uses only one kinds of cable.
• Complete ownership by single organization.
b). Metropolitan Area Network:
A Metropolitan Area Network (MAN) is a network that is larger than a LAN. It is called metropolitan since it normally covers the area of city. Different hardware and transmission media are often used in MAN because they don’t require complete access to locations between the network sites. The features of the MAN are;
• It covers large geographical area with respect to LAN.
• MANs typically used when you need to connect dissimilar system within a single metropolitan.
• It is owned by single or multiple organizations.
• It uses private or public connection mediums.
c). Wide Area Network (WAN):
A Wide Area Network is a network of connecting two or more computers generally across a wide geographical area such as cities, districts and countries. WANs interconnect LANs which may be at the opposite side of a country or located around the world. It uses telephone lines, communication satellite and other long range communication links to connect the computers and network. Internet is an example of WAN. The characteristics of WAN are:
• It covers a large geographical area.
• Transmission cost is high
• Transmission error is higher than LAN
• It is owned by multiple organizations.
• It uses public connections mediums such as telephone lines, wireless technology etc.
• Owned by multiple organization.
Network Topologies:
A network topology is the physical arrangement of computers, cables and other components on a network. The type of topology you use affect the speed and performance of the computer network. The common used physical network topologies are; Bus Topology, Ring Topology, Star Topology, Mesh Topology, Tree Topology, Hybrid Topology
a). Bus Topology:
In a bus topology, all of the computers in a network are attached to a continuous cable or segment, that connects them in a linear format. It uses a common cable or backbone to connect all the nodes is called as Bus. In this topology, a packet or data is transmitted to all network adapter on that segment.
Advantages:
• Bus topology is simple, reliable (in very small network), easy to use and easy to understand.
• It is less expensive.
• It is easy to add a new node in the network.
Disadvantages:
• Heavy network traffic can slow a bus considerably.
• It is difficult to troubleshoot.
• If problems occurs on the backbone, the entire network will go down.
b). Star Topology:
In a star topology, all cables runs from the computer to a central location, where they are all connected by a device called a hub or switch. Each nodes on a star topology must be located relatively close to the hub.
Advantages:
• It is easy to set up and configure.
• It is easy to modify and add new computers to a start topology without disturbing the rest of the network.
• Single computer failure does not necessarily bring down the whole start network.
• It is easy to detect the errors in star topology
Disadvantages:
• It the central device fails, the whole network stops.
• It costs more to cable a start topology because all network cable must be pulled to central point (hub).
c). Ring Topology:
In a ring topology, each computer is connected to the next computer with the last one connected to the first. The ring topology provides equal access for all computers on the network. The information on a ring network travels in one direction either clockwise or anti clockwise direction.
Advantages:
• Ring topology is easy to setup and reconfigure.
• Each computer is given equal opportunity to access the network resources.
• Single cable connects between the nodes.
Disadvantages:
• Failure of one computer on the ring can affect the entire network.
• Adding or removing computers disturbs the networks.
• It is difficult to troubleshoot in a ring topology.
d). Mesh Topology:
In a mesh topology, each node is linked to other through intermediate nodes with redundant paths. All nodes are connected directly to one another, which helps fast communication between nodes.
Advantages:
• The mesh topology is fault tolerance.
• It is easy to troubleshoot.
Disadvantages:
• Difficult to installation and reconfigure
• It is costlier.
Components of Computer Network:
The communication between two computers is possible by interacting between hardware and software Components.
1). Hardware Components:
All the physical component of network that is used to connect or communicate is hardware components. The different hardware components are:
• Server:
A server is a computer that makes its resources available to the network and responds to the commands of a client. The server in a network performs a variety of complex tasks. It is the main computer in network which has high storage capacity and high processing speed. The following are some examples of different types of server included on many large networks:
i). File and Print Servers
ii). Database Servers
iii). Mail Server
• Client / Workstation:
A client is a computer that uses the resources made available by a server. The client must have sufficient processing power on its own to run applications that interact with the resources on the server. It is also called as work station
• Cables:
Cables are the pathway or channel along which the signals or data can be transmitted from one point to another. The most commonly used cables are coaxial, twisted pair and fiber optics.
• Network Interface Card:
Network Interface Card is the computer circuit board or card that is installed in a computer so that it can be connected to a network by using physical channel. Each NIC is assigned a unique MAC (Media Access Control) address by the manufacturer through which data is sent to the destination. The main function of NIC is to convert data into electrical signals and transfer them through cable and vice versa.
• Hub:
Hubs are centrally connectivity devices that connect computers in a star topology. Hub contains multiple ports for connecting to network components. It amplifies (/increase) the signals and sends them to all connected devices. Use of hub has become very common in most of the computer networking as it cost lower and easier to install.
• Connectors:
It is an interface between NIC of the computer and the cable that passes data from one computer to another. It depends on type of cable and devices used in the network. The different types of connectors are; BNC connector, RJ 45, ST, RJ 12 etc.
• Repeater:
A repeater is a physical layer device used to interconnect the media segments of an extended network. It amplifies the incoming signals, creates a new copy of it and transmits the signals on the network. A repeater essentially enables a series of cable segment to be treated as a single cable.
• Bridge:
A bridge is a device that passes data packets between multiple network segments that use the same communication protocol. A bridge passes one signal at a time. It filters the data or inspects incoming signals and decides whether to forward the signals or discard them.
• Switch:
Switches are similar to bridge but offer a more direct network connection between the source and destination computers. The main difference between bridge and switch is the way that filtering happens. With a switc0h, filtering and performance better than bridge.
• Router:
Router is a device that acts like a bridge or switch but provides more functionality. It uses addresses for filtering and forwarding the data. Router enable all user in a network to share a single connection to the Internet or a WAN.
• Gateway:
A gateway is a device that enables communication between different network architecture. A gateway takes the data from one network and repackages it, so that each network can understand the other network’s data.
• Modem: (Modulation-Demodulation)
A modem is a communication device that enables a computer to transmit information over a standard telephone line. A modem is required when connecting to the Internet using telephone line. It is an essential link between the computer running browser and dial up service providers. A modem is needed to convert digital signal to analog signal and vice versa. During the modulation phase, it is used to translate digital signals of a computer to analog signals, which are then transmit across the standard telephone line. The reverse takes place during its demodulation phase, as the MODEM receives analog signals from a phone line and converts them into digital signals for the computer. A modem speed is measured in terms of BPS (Bit Per Second). Speed of telephone service also affects the connection speed. ISDN (Integrated Service Digital Network) allows a modem to connect at 128 KBPS.
Analog Signal:
An analog signal is a constantly changing electrical wave signal that changes in a rounded or smooth pattern.
Digital Signal:
A digital signal uses a square waveform, which is reliably used to transmit electronic data.
Transmission Media / Communication Media / Network Media:
Communication media is the pathway or channel along which the signals or data can be transmitted from one point to another. The signal transmitted from one device to another is through electromagnetic signals. It includes voice, radio waves, infrared light etc. The transmission media is divided into two types:
1) Guided Media:
In guided media is a media that uses a transmission carrier to send data signals through a contained conductor. This conductor can be a metal wire through which electricity flows or a glass strand through which pulses of light flows. The different types of guided media are:
a). Twisted Pair:
Twisted pair cable is the oldest and common medium of transmission. Twisted pair cable consists of two insulated strands of copper wire twisted around each other. There are two types of twisted pair cable. There are:
i). Unshielded Twisted Pair (UTP):
UTP cable consists of a number of twisted pairs of wires with a simple plastic casing. UTP is commonly used in telephone system. It is suitable for both data and voice transmission. It comes in different categories (cat 1 to cat 7). The bandwidth of the cables depends upon the category of the cable. UTP is good for noise rejection and it covers a maximum distance of 100m.
ii). Shielded Twisted Pair (STP)
The STP cable is similar in construction to UTP except that the twisted pairs are enclosed in a woven copper and foil wrap shield for providing extra protection from external interference. STP is more difficult to install than UTP and Coaxial cable. It covers shorter distance than UTP, but it has better noise rejection capacity. The STP is more costlier than UTP cables.
b). Coaxial cable:
Coaxial cable (commonly called “coax”) is made of two conductors that share a common axis, hence the same (“co”, “axis”). Typically, the center of the cable is a relatively stiff solid copper wire or stranded wire encased in insulating plastic foam. The foam is surrounded by the second conductor, a wire mesh tube, which serves as a shield from electromagnetic interference (EMI). The coaxial cables are used in communication networks with single ended single reference where the central conductor carries the data signals. The Connectors used in Coaxial cable are BNC, T-connector and terminals.
c). Fiber Optics:
Fiber-optic cable is made of a light conducting glass or plastic core surrounded by more glass called cladding and a tough (hard) outer cover. A fiber optic consists of a bundle of glass threads, each of which is capable of transmitting message modulated onto light waves. Fiber optics uses light signals rather than electricity, so it offers high bandwidth and greatest distance of any transmission system. The main disadvantage of fiber optics are; it is costlier to produce, maintain and install. The connectors used in fiber optics are Screw Mounted Adaptors (SMA), Spring-loaded Twist (ST), SC and FC.
2) Unguided Media:
In unguided media, the data signals flows through the air instead of cables. It includes wireless transmission methods such as radio frequency, infrared transmission, microwaves and others.
C Fundamentals
A brief history of C
C evolved from a language called B, written by Ken Thompson at Bell Labs in 1970. Ken used B to write one of the first implementations of UNIX. B in turn was a descendant of the language BCPL (developed at Cambridge (UK) in 1967), with most of its instructions removed.
So many instructions were removed in going from BCPL to B, that Dennis Ritchie of Bell Labs put some back in (in 1972), and called the language C.
The famous book The C Programming Language was written by Kernighan and Ritchie in 1978, and was the definitive reference book on C for almost a decade.
The original C was still too limiting, and not standardized, and so in 1983 an ANSI committee was established to formalize the language definition.
It has taken until now (ten years later) for the ANSI ( American National Standard Institute) standard to become well accepted and almost universally supported by compilers.
Structure of a program
Every C program consists of one or more modules called functions. One of these functions is called main. The program begins by executing main function and access other functions, if any. Functions are written after or before main function separately. A function has (1) heading consists of name with list of arguments ( optional ) enclosed in parenthesis, (2) argument declaration (if any) and (3) compound statement enclosed in two braces { } such that each statement ends with a semicolon. Comments, which are not executable statement, of necessary can be placed in between /* and */.
Example
/* program to find the area pf a circle */
#include
#include
main( )
{
float r, a;
printf(“radius”);
scanf(“%f”, &r);
a=3.145*r*r;
printf(“area of circle=%f”, area);
}
The character set
C used the upper cases A,B,…….,Z, the lower cases a ,b,…..,z and certain special characters like + – * / = % & # ! ? ^ “ ‘ ~ \ ( ) = [ ] { } ; : . , _ blank space @ $ . also certain combinations of these characters like \b, \n, \t, etc…
Identities and key words
Identities are names given to various program elements like variables, arrays and functions. The name should begin with a letter and other charact4rs can be letters and digits and also can contain underscore character ( _ )
Exapmle: area, average, x12 , name_of_place etc………
Key words are reserved words in C language. They have predicted meanings and are used for the intended purpose. Standard keywords are auto, break, case, char, const, continue, default, do, double, else enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while. (Note that these words should not be used as identities.)
Data type
The variables and arrays are classified based on two aspects- first is the data type it stores and the second is the type of storage. The basic data types in C language are int, char, float and double. They are respectively concerned with integer quantity, single character, numbers, with decimal point or exponent number and double precision floating point numbers ( ie; of larger magnitude ). These basic data types can be augmented by using quantities like short, long, signed and unsigned. ( ie; long int, short int, long double etc…..).
CONSTANTS
There are 4 basic types of constants . they are int4ger constants, floating-point constants, character constants and string constants.
(a) integer constants: It is an integer valued numbers, written in three different number system, decimal (base 10) , octal(base8), and hexadecimal(base 16).
A decimal integer constant consists of 0,1,…..,9..
Example : 75 6,0,32, etc…..
5,784, 39,98, 2-5, 09 etc are not integer constants.
An octal integer constant consists of digits 0,1,…,7. with 1st digit 0 to indicate that it is an octal integer.
Example : 0, 01, 0756, 032, etc…..
32, 083, 07.6 etc….. are not valid octal integers.
A hexadecimal integer constant consists of 0,1, …,9,A, B, C, D, E, F. It begins with 0x.
Example: 0x7AA2, 0xAB, etc……
0×8.3, 0AF2, 0xG etc are not valid hexadecimal constants.
Usually negative integer constant begin with ( -) sign. An unsigned integer constant is identified by appending U to the end of the constant like 673U, 098U, 0xACLFU etc. Note that 1234560789LU is an unsigned integer constant.
( b) floating point constants : It is a decimal number (ie: base 10) with a decimal point or an exponent or both. Ex; 32.65, 0.654, 0.2E-3, 2.65E10 etc. These numbers have greater range than integer constants.
(c) character constants : It is a single character enclosed in single quotes like ‘a’. ‘3’, ‘?’, ‘A’ etc. each character has an ASCII to identify. For example ‘A’ has the ASCII code 65, ‘3’ has the code 51 and so on.
(d) escape sequences: An escape sequence is used to express non printing character like a new line, tab etc. it begin with the backslash ( \ ) followed by letter like a, n, b, t, v, r, etc. the commonly used escape sequence are
\a : for alert \n : new line : null
\b : backspace \f : form feed \? : question mark
\f : horizontal tab \r : carriage return \’ : single quote
\v : vertical tab \” : quotation mark
(e) string constants : it consists of any number of consecutive characters enclosed in double quotes .Ex : “ C program” , “mathematics” etc……
Variables and arrays
A variable is an identifier that is used to represent some specified type of information. Only a single data can be stored in a variable. The data stored in the variable is accessed by its name. before using a variable in a program, the data type it has to store is to be declared.
Example : int a, b, c,
a=3; b=4;
c=a+b
Note : A statement to declare the data types of the identifier is called declaration statement. An array is an identifier which is used to store a collection of data of the same type with the same name. the data stored is an array are distinguished by the subscript. The maximum size of the array represented by the identifier must be mentioned.
Example : int mark[100] .
With this declaration n, mark is an array of size 100, they are identified by nark[0], mark[1],……….,mark[99].
Note : along with the declaration of variable, it can be initialized too. For example
int x=10;
with this the integer variable x is assigned the value 10, before it is used. Also note that C is a case sensitive langauge. i.e. the variables d and D are different.
DECLARATIONS
This is for specifying data type. All the variables, functions etc must be declared before they are used. 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:
Example : int a,b,c;
Float mark, x[100], average;
char name[30];
char c;
int i;
float f;
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; it doesn’t have to try to intuit the programmer’s intentions.
2. It forces a bit of useful discipline on the programmer: you cannot introduce variables willy-nilly; you must think about them enough to pick appropriate types for them. (The compiler’s error messages to you, telling you that you apparently forgot to declare a variable, are as often helpful as they are a nuisance: they’re helpful when they tell you that you misspelled a variable, or forgot to think about exactly how you were going to use it.)
EXPRESSION
This consists of a single entity like a constant, a variable, an array or a function name. it also consists of some combinations of such entities interconnected by operators.
Example : a, a+b, x=y, c=a+b, x<=y etc……..
STATEMENTS
Statements are the “steps” of a program. Most statements compute and assign values or call functions, but we will eventually meet several other kinds of statements as well. By default, statements are executed in sequence, one after another
A statement causes the compiler to carry out some action. There are 3 different types of statements – expression statements compound statements and control statements. Every statement ends with a semicolon.
Example: (1) c=a + b;
(2) {
a=3;
b=4;
c=a+b;
}
(3) if (a<b)
{
printf(“\n a is less than b”);
}
Statement may be single or compound (a set of statements ).
Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf("Hello, world!\n");
are all expression statements
SYMBOLIC CONSTANTS
A symbolic constant is a name that substitutes for a sequence of characters, which represent a numeric, character or string constant. A symbolic constant is defined in the beginning of a program by using #define, without: at the end.
Example : #define pi 3.1459
#define INTEREST P*N*R/100
With this definition it is a program the values of p, n ,r are assigned the value of INTEREST is computed. Note : symbolic constants are not necessary in a C program.
OPERATORS AND EXPRESSIONS
ARITHMETIC OPERATORS
The basic operators for performing arithmetic are the same in many computer languages:
+ addition
– subtraction
* multiplication
/ division
% modulus (remainder)
For exponentiations we use the library function pow. The order of precedence of these operators is % / * + – . it can be overruled by parenthesis.
Integer division :
Division of an integer quantity by another is referred to integer division. This operation results in truncation. i.e.When applied to integers, the division operator / discards any remainder, so 1 / 2 is 0 and 7 / 4 is 1. But when either operand is a floating-point quantity (type float or double), the division operator yields a floating-point result, with a potentially nonzero fractional part. So 1 / 2.0 is 0.5, and 7.0 / 4.0 is 1.75.
Example : int a, b, c;
a=5;
b=2;
c=a/b;
Here the value of c will be 2
Actual value will be resulted only if a or b or a and b are declared floating type. The value of an arithmetic expression can be converted to different data type by the statement ( data type) expression.
Example : int a, b;
float c;a=5;b=2;
c=(float) a/b
Here c=2.5
Order of Precedence
Multiplication, division, and modulus all have higher precedence than addition and subtraction. The term “precedence” refers to how “tightly” operators bind to their operands (that is, to the things they operate on). In mathematics, multiplication has higher precedence than addition, so 1 + 2 * 3 is 7, not 9. In other words, 1 + 2 * 3 is equivalent to 1 + (2 * 3). C is the same way.
UNARY OPERATORS
A operator acts up on a single operand to produce a new value is called a unary operator.
(1) the decrement and increment operators – ++ and — are unary operators. They increase and decrease the value by 1. if x=3 ++x produces 4 and –x produces 2.
Note : in the place of ++x , x++ can be used, but there is a slight variation. In both csse x is incremented by 1, but in the latter case x is considered before increment.
(2) sizeof is another unary operator
int x, y;
y=sizeof(x);
The value of y is 2 . the sizeof an integer type data is 2 that of float is 4, that of double is 8, that of char is 1.
RELATIONAL AND LOGICAL OPERATORS
< ( less than ), (greater than ), >= ( greater than or equal to ), = = ( equal to ) and != (not equal to ) are relational operators.
A logical expression is expression connected with a relational operator. For example ‘b*b – 4*a*c4 has the value true k<=3 has the value false.
LOGICAL OERATORS
The relational operators work with arbitrary numbers and generate true/false values. You can also combine true/false values by using the Boolean operators, which take true/false values as operands and compute new true/false values. The three Boolean operators are:
&& and
|| or
! not (takes one operand; “unary”)
The && (“and”) operator takes two true/false values and produces a true (1) result if both operands are true (that is, if the left-hand side is true and the right-hand side is true). The || (“or”) operator takes two true/false values and produces a true (1) result if either operand is true. The ! (“not”) operator takes a single true/false value and negates it, turning false to true and true to false (0 to 1 and nonzero to 0).
&& (and ) and || (or) are logical operators which are used to connect logical expressions. Whereas! ( not) is unary operator, acts on a single logical expression.
For example, 1. (a-2)
2. (a2)
In the first example if a= -3 or a=6 the logical expression returns true.
ASSIGNMENT OPERATORS
These operators are used for assigning a value of expression to another identifier.
=, + =, – = , * =, /= and %= are assignment operators.
a = b+c results in storing the value of b+c in ‘a’.
a += 5 results in increasing the value of a by 5
a /= 3 results in storing the value a/3 in a and it is equivalent a=a/3
Note : 1. if a floating point number is assigned to a integer type data variable, the value will be truncated.
Example : float a=5.36;
int b;
b=a
It results in storing 5 to b.
Similarly if an integer value is a assigned to a float type like float x=3 the value of x stored is 3.0.
CONDITIONAL OPERATOR
The operator ?: is the conditional operator. It is used as variable 1 = expression 1 ? expression 2 : expression 3.
Here expression 1 is a logical expression and expression 2 and expression 3 are expressions having numerical values. If expression 1 is true, value of expression 2 is assigned to variable 1 and otherwise expression3 is assigned.
Example :
int a,b,c,d,e
a=3;b=5;c=8;
d=(ac) ? b : c;
Then d=3 and e=8
LIBRARY FUNCTIONS
They are built in programs readily available with the C compiler. These function perform certain operations or calculations. Some of these functions return values when they are accessed and some carry out certain operations like input, output.a library functions accessed in a used written program by referring its name with values assigned to necessary arguments.
Some of these library functions are : abs(i), ceil(d), cos(d), cosh(d), exp(d), fabs(d),floor(d), getchar( ), log(d), pow(d,d’), printf( ), putchar(c), rand( ), sin(d), sqrt(d), scanf( ), tan(d), toascii(c), toupper(c), tolower(c).
Note : the arguments i, c, d are respectively integer, char and double type.
Example:
#include
#include
#
main( )
{
float x, s;
printf(“ \n input the values of x :”);
scanf(“%f ”, &x);
s=sqrt(x);
printf(“\n the square root is %f ”,s);
}
Note that C language is case sensitive, which means ‘a’ and ‘A’ are different. Before the main program there are statements begin with # symbol. They are called preprocessor statements. Within the main program “ float r, a;” is a declaration statement. ‘include’ is a preprocessor statement. The syntax is #include. it is to tell the compiler looking for library functions, which are used in the program, included in the file, file name ( like stdio.h, conio.h, math.h, etc…).
Page No.12
DATA INPUT OUTPUT
For inputting and outputting data we use library function .the important of these functions are getch( ), putchar( ), scanf( ), printf( ), gets( ), puts( ). For using these functions in a C-program there should be a preprocessor statement
#include.
[A preprocessor statement is a statement before the main program, which begins with # symbol.]
stdio.h is a header file that contains the built in program of these standard input
output
function.
getchar function
It is used to read a single character (char type) from keyboard. The syntax is char variable name = getchar( );
Example:
char c;
c = getchar( );
For reading an array of characters or a string we can use getchar( ) function.
Example:
#include
main( )
{
char place[80];
int i;
for(i = 0;( place [i] = getchar( ))! = ‘\n’, ++i);
}
This program reads a line of text.
Page No.13
putchar function
It is used to display single character. The syntax is
putchar(char c);
Example:
char c;
c = ‘a’;
putchar(c);
Using these two functions, we can write a very basic program to copy the input, a character at a time, to the output:
#include
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
scanf function
This function is generally used to read any data type- int, char, double, float, string.
The syntax is
Page No.14
scanf (control string, list of arguments);
The control string consists of group of characters, each group beginning % sign and a conversion character indicating the data type of the data item. The conversion characters are c,d,e,f,o,s,u,x indicating the type resp. char decimal integer, floating point value in exponent form, floating point value with decimal point, octal integer, string, unsigned integer, hexadecimal integer. ie, “%s”, “%d” etc are such group of characters.
An example of reading a data:
#include
main( )
{
char name[30], line;
int x;
float y;
………
…….…
scanf(“%s%d%f”, name, &x, &y);
scanf(“%c”,line);
}
NOTE:
1. In the list of arguments, every argument is followed by & (ampersand symbol) except
string variable.
2. s-type conversion applied to a string is terminated by a blank space character. So string having blank space like “Govt. Victoria College” cannot be read in this manner. For reading such a string constant we use the conversion string as “%[^\n]” in place of “%s”.
Example:
char place[80];
…………….
scanf(“%[^\n]”, place);
……………..
with these statements a line of text (until carriage return) can be input the variable ‘place’.
Page No.15
printf function
This is the most commonly used function for outputting a data of any type.
The syntax is
printf(control string, list of arguments)
Here also control string consists of group of characters, each group having % symbol and conversion characters like c, d, o, f, x etc.
Example:
#include
main()
{
int x;
scanf(“%d”,&x);
x*=x;
printf(“The square of the number is %d”,x);
}
Note that in this list of arguments the variable names are without &symbol unlike in the case of scanf( ) function. In the conversion string one can include the message to be displayed. In the above example “The square of the number is” is displayed and is followed by the value of x.For writing a line of text (which include blank spaces) the conversion string is “%s” unlike in scanf function. (There it is “[^\n]”).
More about printf statement
There are quite a number of format specifiers for printf. Here are the basic ones :
%d print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %
Page No.16
To illustrate with a few more examples: the call
printf(“%c %d %f %e %s %d%%\n”, ’1′, 2, 3.14, 56000000., “eight”, 9);
would print
1 2 3.140000 5.600000e+07 eight 9%
The call
printf(“%d %o %x\n”, 100, 100, 100);
would print
100 144 64
Successive calls to printf just build up the output a piece at a time, so the calls
printf(“Hello, “);
printf(“world!\n”);
would also print Hello, world! (on one line of output).
While inputting or outputting data field width can also be specified.This is included in the conversion string.(if we want to display a floating point number convert to 3 decimal places the conversion string is “%.3f”).For assigning field width,width is placed before the conversion character like “%10f”,”%8d”,”%12e” and so on…Also we can display data making correct to a fixed no of decimal places.
For example if we want to display x=30.2356 as 30.24 specification may be “%5.2f” or simply “%.2f”.
Page No.17
CONTROL STATEMENTS
When we run a program,the statements are executed in the order in which they appear in the program.Also each statement is executed only once.But in many cases we may need a statement or a set of statements to be executed a fixed no of times or until a condition is satisfied.Also we may want to skip some statements based on testing a condition.For all these we use control statements .
Control statements are of two types – branching and looping.
BRANCHING
It is to execute one of several possible options depending on the outcome of a logical test ,which is carried at some particular point within a program.
LOOPING
It is to execute a group of instructions repeatedly,a fixed no of times or until a specified condition is satisfied.
BRANCHING
1. if else statement
It is used to carry out one of the two possible actions depending on the outcome of a logical test.The else portion is optional.
The syntax is
If (expression) statement1 [if there is no else part]
Or
If (expression)
Statement 1
else
Statement 2
Page No.18
Here expression is a logical expression enclosed in parenthesis.if expression is true ,statement 1 or statement 2 is a group of statements ,they are written as a block using the braces { }
Example: 1. if(x<0) printf(“\n x is negative”);
2. if(x<0)
printf(“\n x is negative”);
else
printf(“\n x is non negative”);
3.if(x=90) printf(“\n excellent”);
else if(mark>=80) printf(“\n very good”);
else if(mark>=70) printf(“\n good”);
else if(mark>=60) printf(“\n average”);
else
printf(“\n to be improved”);
SWITCH STATEMENT
It is used to execute a particular group of statements to be chosen from several available options. The selection is based on the current value of an expression with the switch statement.
The syntax is:
switch(expression)
{
case value1:
s1
break;
case value 2:
s2
break;
…….
……..
default:
sn
}
All the option are embedded in the two braces { }.Within the block each group is written after the label case followed by the value of the expression and a colon. Each group ends with ‘break’ statement. The last may be labeled ‘default’. This is to avoid error and to execute the group of statements in default if the value of the expression does not match value1, value2,……..
Page No.20
LOOPING
1. The while statement
This is to carry out a set of statements to be executed repeatedly until some condition is satisfied.
The syntax is:
While (expression) statement
The statement is executed so long as the expression is true. Statement can be simple or compound.
Example 1: #include
while(n > 0)
{
printf(“\n”);
n = n – 1;
}
Example 2: #include
main()
{
int i=1;
while(x<=10)
{
printf(“%d”,i);
++i;
}
}
Page No.21
2. do while statement
This is also to carry out a set of statements to be executed repeatedly so long as a condition is true.
The syntax is:
do statement while(expression)
Example: #include
main()
{
int i=1;
do
{
printf(“%d”,i);
++i;
}while(i<=10);
}
THE DIFFERENCE BETWEEN while loop AND do – while loop
1. In the while loop the condition is tested in the beginning whereas in the other case it is done at the end.
2. In while loop the statements in the loop are executed only if the condition is true.whereas in do – while loop even if the condition is not true the statements are executed atleast once.
3. for loop
It is the most commonly used looping statement in C. The general form is
For(expression1;expression2;expression3)statement
Here expression1 is to initialize some parameter that controls the looping action.expression2 is a condition and it must be true to carry out the action.expression3 is a unary expression or an assignment expression.
Page No.22
Example: #include
main()
{
int i;
for(i=1;i<=10;++i)
printf(“%d”,i);
}
Here the program prints i starting from 1 to 10.First i is assigned the value 1 and than it checks whether i<=10 If so i is printed and then i is increased by one. It continues until i<=10.
An example for finding the average of 10 numbers;
#include
main()
{
int i;
float x,avg=0;
for(i=1;i<=10;++i)
{
scanf(“%f”,&x);
avg += x;
}
avg /= 10;
printf(“\n average=%f”,avg);
}
Note: Within a loop another for loop can come
Page No.23
Example : for(i=1;i<=10;++i)
for(j=1;j<=10;++j);
The break statement
The break statement is used to terminate4 loop or to exit from a switch. It is used in for, while, do-while and switch statement.
The syntax is break;
Example 1: A program to read the sum of positive numbers only
#include
main()
{
int x, sum=0;
int n=1;
while(n<=10)
{
scanf(“%d”,&x);
if(x<0) break;
sum+=x;
}
printf(“%d”,sum);
}
Example 2 :A program for printing prime numbers between 1 and 100:
#include
#include
main()
{
int i, j;
printf(“%d\n”, 2);
for(i = 3; i <= 100; i = i + 1)
{
for(j = 2; j sqrt(i))
{
printf(“%d\n”, i);
break;
}
}
}
return 0;
}
Here while loop breaks if the input for x is –ve.
The continue statement
It is used to bypass the remainder of the current pass through a loop. The loop does not terminate when continue statement is encountered, but statements after continue are skipped and proceeds to the next pass through the loop.
In the above example of summing up the non negative numbers when a negative value is input, it breaks and the execution of the loop ends. In case if we want to sum 10 nonnegative numbers, we can use continue instead of break
Example : #include
main()
{
int x, sum=0, n=0;
while(n<10)
{
scanf(“%d”,x);
if(x<0) continue;
sum+=x;
++n;
}
printf(“%d”,sum);
}
Page No.25
GO TO statement
It is used to alter the normal sequence of program execution by transferring control to some other part of the program .The syntax is goto label ;
Example :
#include
main( )
{
int n=1,x,sum=0;
while(n<=10)
{
scanf(“%d” ,&x);
if(x=y)? x : y ;
return(z);
}
(3)
maximum( int x,int y)
{
int z;
z=(x>=y) ? x : y ;
printf(“\n maximum =%d”,z);
return ;
}
Note: In example (1) and (2) the function does not return anything.
Page No.28
Advantages of functions
1. It appeared in the main program several times, such that by making it a function, it can be written just once, and the several places where it used to appear can be replaced with calls to the new function.
2. The main program was getting too big, so it could be made (presumably) smaller and more manageable by lopping part of it off and making it a function.
3. It does just one well-defined task, and does it well.
4. Its interface to the rest of the program is clean and narrow
5. Compilation of the program can be made easier.
Accessing a function
A function is accessed in the program (known as calling program)by specifying its name with optional list of arguments enclosed in parenthesis. If arguments are not required then only with empty parenthesis.
The arguments should be of the same data type defined in the function definition.
Example:
1) int a,b,y;
y=maximum(a,b);
2) char name[50] ;
writecaption(name);
3) arrange();
Page No.29
If a function is to be accessed in the main program it is to be defined and written before the main function after the preprocessor statements.
Example:
#include
int maximum (int x,int y)
{
int z ;
z=(x>=y) ? x : y ;
return (z);
}
main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b);
c=maximum(a,b);
printf(“\n maximum number=%d”,c);
}
Function prototype
It is a common practice that all the function programs are written after the main( ) function .when they are accessed in the main program, an error of prototype function is shown by the compiler. It means the computer has no reference about the programmer defined functions, as they are accessed before the definition .To overcome this, i.e to make the compiler aware that the declerations of the function referred at the calling point follow, a decleration is done in the beginning of the program immediately after the preprocessor statements. Such a decleration of function is called prototype decleration and the corresponding functions are called function prototypes.
Page No.30
Example 1:
#include
int maximum(int x,int y);
main( )
{
int a,b,c;
scanf(“%d%d”,&a,&b);
c=maximum(a,b);
printf(“\n maximum number is : %d”,c);
}
int maximum(int x, int y)
{
int z;
z=(x>=y) ? x : y ;
return(z);
}
Example 2:
#include
void int factorial(int m);
main( )
{
int n;
scanf(“%d”,&n);
factorial(n);
}
void int factorial(int m)
{
int i,p=1;
for(i=1;i<=m;++i)
p*=i;
printf(“\n factorial of %d is %d “,m,p);
return( );
}
Note: In the prototype decleration of function, if it return no value, in the place of data-type we use void. Eg: void maximum(int x,int y);
Page No.31
Passing arguments to a function
The values are passed to the function program through the arguments. When a value is passed to a function via an argument in the calling statement, the value is copied into the formal argument of the function (may have the same name of the actual argument of the calling function).This procedure of passing the value is called passing by value. Even if formal argument changes in the function program, the value of the actual argument does not change.
Example:
#include
void square (int x);
main( )
{
int x;
scanf(“%d”,&x);
square(x):
}
void square(int x)
{
x*=x ;
printf(“\n the square is %d”,x);
return;
}
In this program the value of x in the program is unaltered.
Page No.32
Recursion
It is the process of calling a function by itself ,until some specified condition is satisfied. It is used for repetitive computation ( like finding factorial of a number) in which each action is stated in term of previous result.
Example:
#include
long int factorial(int n);
main( )
{
int n;
long int m;
scanf(“%d”,&n);
m=factorial(n);
printf(“\n factorial is : %d”, m);
}
long int factorial(int n)
{
if (n<=1)
return(1);
else
return(n*factorial(n-1));
}
In the program when n is passed the function, it repeatedly executes calling the same function for n, n-1, n-2,………………..1.
Page No. 33
Arrays
An array is an identifier to store a set of data with common name. Note that a variable can store only a single data. Arrays may be one dimensional or multi dimensional.
Defining an array one dimensional arrays
Definition: Arrays are defined like the variables with an exception that each array name must be accompanied by the size (i.e. the max number of data it can store).For a one dimensional array the size is specified in a square bracket immediately after the name of the array.
The syntax is
data-type array name[size];
So far, we've been declaring simple variables: the declaration
int i;
declares a single variable, named i, of type int. It is also possible to declare an array of several elements. The declaration
int a[10];
declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an array is a variable that can hold more than one value. You specify which of the several values you're referring to at any given time by using a numeric subscript. (Arrays in programming are similar to vectors or matrices in mathematics.) We can represent the array a
above with a picture like this:
eg: int x[100];
float mark[50];
char name[30];
Page No.34
Note: With the declaration int x[100],computer creates 100 memory cells with name x[0],x[1],x[2],………,x[99].Here the same identifier x is used but various data are distinguished by the subscripts inside the square bracket.
Array Initialization
Although it is not possible to assign to all elements of an array at once using an assignment expression, it is possible to initialize some or all elements of an array when the array is defined. The syntax looks like this:
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
The list of values, enclosed in braces {}, separated by commas, provides the initial values for successive elements of the array.
If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to 0. For example,
int a[10] = {0, 1, 2, 3, 4, 5, 6};
would initialize a[7], a[8], and a[9] to 0. When an array definition includes an initializer, the array dimension may be omitted, and the compiler will infer the dimension from the number of initialisers. For example,
int b[] = {10, 11, 12, 13, 14};
Example :
int x[ ] ={0,1,2,3,4,5}; or
int x[6]={0,1,2,3,4,5};
Even if the size is not mentioned (former case) the values 0,1,2,3,4 are stored in x[0],x[1],x[2],x[3],x[4],x[5].If the statement is like
int x[3]={0,1,2,3,4,5};
then x[0],x[1],x[2] are assigned the values 0,1,2.
Note: If the statement is like
int x[6]={0,1,2};
then the values are stored like x[0]=0, x[1]=1, x[2]=2, x[3]=0, x[4]=0 and x[5]=0.
Page No.35
Processing one dimensional array
1. Reading arrays: For this normally we use for- loop.
If we want to read n values to an array name called ‘mark’ , the statements look like
int mark[200],i,n;
for(i=1;i<=n;++i)
scanf(“%d”,&x[i]);
Note: Here the size of array declared should be more than the number of values that are intended to store.
2. Storing array in another:
To store an array to another array. Suppose a and b are two arrays and we want to store that values of array a to array b. The statements look like
float a[100],b[100];
int I;
for(i=1;i<=100;++i)
b[i]=a[i];
Problem: To find the average of a set of values.
#include
main( )
{
int x,i;
float x[100],avg=0;
printf(“\n the no: of values “);
scanf(“%d”,&n);
printf(“\n Input the numbers”);
for(i=1;i<=n;++i)
{
scanf(“%f”,&x[i]);
avg=avg+x[i];
}
avg=avg/n;
printf(“\n Average=%f”,avg);
}
Page No.36
PASSING ARRAYS TO FUNCTION
Remember to pass a value to a function we include the name of the variable as an argument of the function.Similarly an array can be passed to a function by including arrayname (without brackets) and size of the array as arguments.In the function defined the arrayname together with empty square brackets is an argument.
Ex:
(calling function)-avg=average(n,x); where n is the size of the data stored in the array x[].
(function defined)- float average(int n,float x[]);
Now let us see to use a function program to calculate the average of a set of values.
#include
float average(int n,float y[]);
main()
{
int n;
float x[100],avg;
printf(“\n Input the no: of values”);
scanf(“%d”,&n);
printf(“\n Input the values”);
for(i=1;i<=n;++i)
scanf(“%f”,&x[i]);
avg=average(n,x);
printf(“\n The average is %f”,avg);
}
float average(int n, float y[]);
{
float sum=0;
int i;
for(i=1;i<=n;++i)
sum=sum+y[i];
sum=sum/n;
return(sum);
}
Page No.37
Note:
1. In the function definition the array name together with square brackets is the argument. Similarly in the prototype declaration of this function too, the array name with square brackets is the argument
2. We know that changes happened in the variables and arrays that are in function will not be reflected in the main (calling) program even if the same names are usual. If we wish otherwise the arrays and variables should be declared globally. This is done by declaring them before the main program.
Ex:
#include
void arrange(int n,float x[]);
main();
{
………..
arrange(n,x);
…………..
}
arrange(int n,float x[]);
{
……….
return;
}
Problem : Write a program to arrange a set of numbers in ascending order by using a function program with global declaration.
Page No.38
MULTI-DIMENSIONAL ARRAYS
Multi-dimensional arrays are defined in the samemanner as one dimensional arrays except that a separate pairof square brackets is required to each subscript.
Example: float matrix[20][20] (two dimensional)
Int x[10][10][5] (3-dimensional)
Initiating a two dimensional array we do as int x[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}
Or
int x[3][4]={
{1,2,3,4};
{5,6,7,8};
{89,10,11,12};
}
NOTE: The size of the subscripts is not essential for initialization. For reading a two dimensional array we use two for-loop.
Example:
for(i=1;i<=2;++i)
for(j=1;j<=3;++j)
scanf(“%f”,&A[i][j]);
NOTE: If x[2][3] is a two dimensional array, the memory cells are identified with
name x[0][0],x[0][1],x[0][2],x[1][0],x[1][1] and x[1][2].
Page No.39
ARRAYS AND STRINGS.
A string is represented as a one dimensional array of character type.
Example : char name[20];
Here name is an array that can store a string of size 20.
If we want to store many strings(like many names or places) two dimensional array is used. Suppose we want to store names of 25 persons, then declare name as char name[25][ ].
Note that the second square bracket is kept empty if the length of string is not specified.
If the declaration is char name[25][30], 25 names of maximum size 30 can be
stored. The various names are identified by name[0], name[1], name[2],……..,
name[24]. These names are read by the command
For( i=0; i<25,++i)
Scanf( “%[^\n]”, name(i));
PROBLEM: Write a program to store the names and places of students in your class.
Page No.40
PROGRAM STRUCTURE
STORAGE CLASS
Earlier we mentioned that variables are characterized by their data type like integer, floating point type, character type etc. Another characteristic of variables or arrays is done by storage class. It refers to the permanence and scope of variables or arrays within a program. There are 4 different storage class specification in C – automatic, external, static, and register. They are identified by the key words auto, external, static, and register respectively.
AUTOMATIC VARIABLES
They are declared in a function. It is local and its scope is restricted to that function. They are called so because such variables are created inside a function and destroyed automatically when the function is exited. Any variable declared in a function is interpreted as an automatic variable unless specified otherwise. So the keyword auto is not required at the beginning of each declaration.
EXTERNAL VARIABLE (GLOBAL VARIABLE)
The variables which are alive and active through out the entire program are called external variables. It is not centered to a single function alone, but its scope extends to any function having its reference. The value of a global variable can be accessed in any program which uses it. For moving values forth and back between the functions, the variables and arrays are declared globally i.e., before the main program. The keyword external is not necessary for such declaration, but they should be mentioned before the main program.
STATIC VARIABLES
It is, like automatic variable, local to functions is which it is defined. Unlike automatic variables static variable retains values throughout the life of the program, i.e. if a function is exited and then re-entered at a later time the static variables defined within the function will retain their former values. Thus this feature of static variables allows functions to retain information permanently through out the execution of the program. Static variable is declared by using the keyword static.
Example : static float a ;
Static int x ;
Page No.41
Consider the function program:
# include
long int Fibonacci (int count )
main()
{
int i, m=20;
for (i =1 ; i < m ; ++i)
printf( “%ld\t”,fibonacci(i));
}
long int Fibonacci (int count )
{
static long int f1=1, f2=1 ;
long int f ;
f = (count < 3 ) ? 1 : f1 + f2 ;
f2 = f1
f1= f ;
return (f ) ;
}
In this program during the first entry to the function f1 and f2 are assigned 1, later they are replaced by successive values of f1 and f. as f1 and f2 are declared static storage class. When the function is exited the latest values stored in f1 and f2 will be retained and used when the function is re-entered.
Page No.42
Pointers
A pointer is a variable that represents the location or address of a variable or array element.
Uses
1. They are used to pass information back and forth between a function and calling point.
2. They provide a way to return multiple date items.
3. They provide alternate way to access individual array elements.
When we declare a variable say x, the computer reserves a memory cell with name x. the data stored in the variable is got through the name x. another way to access data is through the address or location of the variable. This address of x is determined by the expression &x, where & is a unary operator (called address operator). Assign this expression &x to another variable px(i.e. px=&x).this new variable px is called a pointer to x (since it points to the location of x. the data stored in x is accessed by the expression *px where * is a unary operator called the indirection operator.
Ex: if x=3 and px=&x then *px=3
Declaration and Initialisation
A pointer variable is to be declared initially. It is done by the syntax.
Data type *pointer variable
Int *p declares the variable p as pointer variable pointing to a an integer type data. It is made point to a variable q by p= &q. In p the address of the variable q is stored.
The value stored in q is got by *p.
If y is a pointer variable to x which is of type int, we declare y as int *y ;
Ex: float a;
float *b;
b=&a;
Note : here in ‘b’ address of ‘a’ is stored and in ‘*b’ the value of a is stored.
Page No.43
Passing pointers to a function
Pointers are also passed to function like variables and arrays are done. Pointers are normally used for passing arguments by reference (unlike in the case if variable and arrays, they are passed by values). When data are passed by values the alteration made to the data item with in the function are not carried over to the calling point; however when data are passed by reference the case is otherwise. Here the address of data item is passed and hence whatever changes occur to this with in the function, it will be retained through out the execution of the program. So generally pointers are used in the place of global variables.
Ex: ):
#include
void f(int*px, int *py
main()
{
int x = 1;
int y=2;
f(&X,&y);
printf(“\n %d%d”, x,y);
}
Void f(int *px, int *py);
*px=*px+1;
*py=*py+2;
return;}
Note:
1. here the values of x and y are increased by 1 and 2 respectively.
2. arithmetic operations *, +, -, / etc can be applied to operator variable also.
Passing function to other function
A pointer to a function can be passed to another pointer as an assignment. Here it allows one function to be transferred as if the function were a variable.
Page No.44
Pointer and one dimensional arrays
An array name is really a pointer to the first element in the array i.e. if x is a one dimensional array, the name x is &x[0] and &x[i] are x + i for i= 1,2,……. So to read array of numbers we can also use the following statements
int x[100],n;
for (i=1 ; i<=n; ++i)
scanf (‘%d”, x + i ) (in the place of scanf (“%d”, &x[i] ) )
Note : the values stored in the array are got by * ( x + i ) in the place x[i].
Dynamic memory allocation
Usually when we use an array in c program, its dimension should be more than enough or may not be sufficient. To avoid this drawback we allocate the proper ( sufficient) dimensions of an array during the run time of the program with the help of the library functions called memory management functions like ‘malloc’, ‘calloc’, ‘realloc’ etc. The process of allocating memory at run time is known as dynamic memory allocation.
Ex;
to assign sufficient memory for x we use the following statement
x= (int *) malloc (n* sizeof (int) ) , for in the place of initial declaration int x[n]
Similarly in the place of float y [100] we use y = (float *) malloc (m* sizeof (float) );
Example to read n numbers and find their sun
main()
{
int *x, n, i, sum=0;
printf(“\n Enter number of numbers”);
scanf(“%d”, &n);
x=(int *)malloc(n * sizeof(int));
for(i=1;i<=n,++i)
{
scanf(“%d”, x+i):
sum += *(x+i);
}
Printf(“\nThe sum is %d ”, sum);
}
Page No. 45
Structures and Unions
We know an array is used to store a collection of data of the same type. But if we want to deal with a collection of data of various type such as integer, string, float etc we use structures in C language. It is a method of packing data of different types. It is a convenient tool for handling logically related data items of bio-data people comprising of name, place, date etc. , salary details of staff comprising of name, pay da, hra etc.
Defining a structure.
In general it is defined with the syntax name struct as follows
Struct structure_name
{
Data type variable1;
Data type variable2;
…
}
For example :
1. Struct account
{
int account no.
char name[50];
float balance;
}customer[20]
Note :1 here account no., name and balance are called members of the structure
2. struct date
{
int month;
int day;
int year;
}dateofbirth;
Page No.6
In these examples customer is a structure array of type account and dateofbirth is a structural type of date. Within a structure members can be structures. In the following example of biodata structure date which is a structure is a member.
For example
struct date
{
int day;
int month;
int year;
}
Struct biodata
{
name char[30];
int age ;
date birthdate;
}staff[30];
Here staff is an array of structure of type biodata
Note: we can declare other variables also of biodata type structure as follows.
Struct biodata customer[20]; , Struct biodata student; etc
Processing a structure
The members of a structure are themselves not variable. They should be linked to the structure variable to make them meaningful members. The linking is done by period (.)
If staff[] is structure array then the details of first staff say staff[1] is got by
staff[1].name, staff[1].age, staff[1].birthdate.day, staff[1].birthdate.month,
staff[1].birthdate.year . we can assign name, age and birthdate of staff[1] by Staff[1].name=”Jayachandran”
staff[1].age=26
staff[1].birthdate.day=11
staff[1].birthdate.month=6
staff[1].birthdate.year=1980
Page No.47
If ‘employee’ is a structure variable of type biodata as mentioned above then the details of ‘employee’ is got by declaring ‘employee as biodata type by the statement
biodata employee;
The details of employee are got by employee.name, employee.age, employee.birthdate.year etc.
Structure initialisation
Like any other variable or array a structure variable can also be initalised.by using syntax static
Struct record
{
char name[30];
int age;
int weight;
}
Static struct record student1={“rajan”, 18, 62}
Here student1 is of record structure and the name,age and weight are initialised as “rajan”, 18 and 62 respectively.
1 Write a c program to read biodata of students showing name, place, pin, phone and grade
Solution
#include
main()
{
Struct biodata
{
Char name[30];
Char Place[40];
Int pin;
Long Int phone;
Char grade;
};
Page No. 48
Struct biodata student[50];
Int n;
Prinf(“\n no of students”);
Scanf(“%d”,n);
For(i=1;i<=n;++i)
{
Scanf(“%s”,student[i].name);
Scanf(“%s”,student[i].place);
Scanf(“%d”,student[i].pin);
Scanf(“%ld”,student[i].phone);
Scanf(“%c”,student[i].grade);
}
}
User Defiined Data Type
This is to define new data type equivalent to existing data types. Once defined a user-defined data type then new variables can be declared in terms of this new data type. For defining new data type we use the syntax typedef as flollows
typedef type new-type.
Here type refers to existing data type
For example
Ex1:
Typedef int integer;
Now integer is a new type and using this type variable, array etc can be defined as
Integer x;
Integer mark[100];
Page No.49
Ex2:
Typedef struct
{
Int accno;
Char name[30];
Float balance;
}record;
Now record is structure type using this type declare customer, staff as record type
Record customer;
Record staff[100];
Passing structures to functions
Mainly there are two methods by which structures can be transferred to and from a function.
1 Transfer structure members individually
2 Passing structures as pointers (ie by reference)
Example 1
#include
Typedef struct
{
Int accno;
Char name[30];
Float balance;
}record;
Main()
{
…..
Record customer;
. . . . .
Customer.balance=adjust(customer.name,customer.accno,balance)
. . . . .
}
Page No.50
Float adjust(char name[], int accnumber, float bal)
{
Float x;
. . . . .
X=
. . . . .
Return(x);
}
Example 2
#include
Typedef struct
{
Int accno;
Char name[30];
Float balance;
}record;
Main()
{
Record customer;
Void adjust(record *cust)
. . . . . .
Adjust(&customer);
Printf(“\n %s\t%f”,coustomer.name,customer.balance)
}
Void adjust(record *cust)
{
Float x;
. . . .
Cust->balance=…
. . . .
Return;
}
Page No. 51
In the first example structure members are passed individually where as in the second case customer is passed entirely as a pointer named cust. The values of structure members are accessed by using -> symbol like cust->.name, cust->balance etc.
Unions
Union is a concept similar to a structure with the major difference in terms of storage. In the case of structures each member has its own storage location, but a union may contain many members of different types but can handle only one at a time. Union is also defined as a structure is done but using the syntax union.
Union var
{
Int m;
Char c;
Float a;
}
Union var x;
Now x is a union containing three members m,c,a. But only one value can be stored either in x.m, x.corx.a
Page No.52
Data Files
Data Files are to store data on the memory device permanently and to access whenever is required. There are two types of data files
1 Stream Oriented data files
2 System Oriented data files
Stream oriented data files are either text files or unformatted files. System oriented data files are more closely related to computer’s operating system and more complicated to work with. In this session we go through stream oriented data files.
Opening and Closing data files
The first step is to create a buffer area where information is stored temporarily before passing to computer memory. It is done by writing
File *fp;
Here fp is the pointer variable to indicate the beginning of the buffer area and called stream pointer . The next step is to open a data file specifying the type i.e. read only file , write only file , read /write file. This is done by using the library function fopen
The syntax is
fp=fopen(filename,filetype)
the filetype can be
1. ‘r’ ( to open an existing file for reading only)
2. ‘w’ ( to open a new file for writing only. If file with filename exists, it will be destroyed and a new file is created in its place)
3. ‘a’ ( to open an existing file for appending. If the file name does not exist a new file with that file name will be created)
4. ‘r+’ ( to open an existing file for both reading and writing)
5. ‘w+’ ( to open a new file for reading and writing. If the file exists with that name, it will be destroyed and a new one will be created with that name)
6. 6 ‘a+’ ( to open an existing file for reading and writing. If the file does not exist a new file will be created).
Page No.53
For writing formatted data to a file we use the function fprintf. The syntax is
Fprintf(fp,”conversion string”, value);
For example to write the name “rajan” to the file named ‘st.dat’
File *fp;
Fp=fopen(“st.dat”,’w’);
Fprintf(fp,”%[^\n]”,”rajan”);
The last step is to close the file after the desired manipulation. This is done by the library function fclose. The syntax is
fclose(fp);
Example 1
To create a file of biodata of students with name ‘st.dat’.
#include
#include
Tpedef struct
{
Int day;
Int month;
Int year;
}date;
Typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
Main()
{
File *fp;
biodata student;
fp=fopen(“st.dat”,’w’);
Printf(“Input data”);
Scanf(“%[^\n]”,student.name);
Scanf(“%[^\n]”,student.place);
Scanf(“%d”,&student.age);
Scanf(“%d”,&student.birthdate.day);
Page No.54
Scanf(“%d”,&student.birthdate.month);
Scanf(“%d”,&student.birthdate.year);
Fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.age,student.birthdate.day, student.birthdate.month, student.birthdate.year)
Fclose(fp);
}
Example 2:
To write a set of numbers to a file.
#include
main()
{
file *fp;
Int n; float x
fp=fopen(“num.dat”,’w’);
Printf(“Input the number of numbers”);
Scanf(“%d”,&n);
For(i=1;i<=n;++i)
{
Scanf(“%d”,&x);
Fprintf(fp,”%f\n”,x);
}
Fclose(fp);
}
Processing formatted data File
To read formatted data from a file we have to follow all the various steps that discussed above. The file should be opened with read mode. To open the existing file ‘st.dat’ write the following syntax
file *fp;
fp=fopen(“st.dat”, ‘r+’);
For reading formatted data from a file we use the function fscanf
Page No.55
Example:
Tpedef struct
{
Int day;
Int month;
Int year;
}date;
Typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
Main()
{
File *fp;
biodata student;
fp=fopen(“st.dat”,’r+’);
fscanf(fp,”%s”,student.name);
printf(“%s”,student.name);
fclose(fp);
}
Processing Unformatted data files
For reading and writing unformatted data to files we use the library functions fread and fwrite in the place of fscanf and fprintf.
The syntax for writing data to file ‘st.dat’ with stream pointer fp is
Fwrite(&student, sizeof(record),1,fp);
Here student is the structure of type biodata
Page No.56
Example:
To write biodata to a file
Tpedef struct
{
Int day;
Int month;
Int year;
}date;
Typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
Main()
{
File *fp;
fp=fopen(“st.dat”,’a+’);
biodata student;
Printf(“Input data”);
Scanf(“%[^\n]”,student.name);
Scanf(“%[^\n]”,student.place);
Scanf(“%d”,&student.age);
Scanf(“%d”,&student.birthdate.day);
Scanf(“%d”,&student.birthdate.month):
Scanf(“%d”,&student.birthdate.year);
Fwrite(&student,sizeof(record),1,fp);
Fclose(fp);
}
Page No.57
Example 2:
To read biodata from the file.
Tpedef struct
{
Int day;
Int month;
Int year;
}date;
Typedef Struct
{
char name(30);
char place(30);
int age;
date birthdate;
}biodata;
Main()
{
File *fp;
fp=fopen(“st.dat”,’a+’)
biodata student;
fread(&student,sizeof(record),1,fp);
printf(“%s\n”,student.name);
printf(“%s\n]”,student.place);
printf(“%d\n”,&student.age);
printf(“%d\n”,&student.birthdate.day);
printf(“%d\n”,&student.birthdate.month):
printf(“%d\n”,&student.birthdate.year);
fclose(fp);
}
Page No.58
Some problems and solutions of C:
1. WAP to input an integer and check whether number is above 50 or not. [ Using if loop statement]
Ans:
#include
#include
void main()
{
int a;
printf(“Enter a value for a: ”);
scanf(“%d”,&a);
if(a>=51)
{
printf(“%d is greater than 50”,a);
}
else
{
printf(“%d is less than or equal to 50”,a);
}
getch()
}
2. WAP for finding factorial of a given number using while statement.
Ans:
#include
#include
void main()
{
clrscr();
int number;
long int factorial=1;
printf(“\nEnter the number:”);
scanf(“%d,&number);
while (number>1)
Page No.59
{
factorial=factorial * number –;
printf(“\nThe factorial is %d”, factorial);
}
getch();
}
Output:
Enter the number =4
The factorial is 24
3. WAP in C to input any five number in an array, find the average and if the average is greater than 50 print good otherwise print bad.
Ans:
#include
#include
void main()
{
clrscr();
int a[5],ar,s=0,i,j;
printf(“Enter any five number”);
for (i=0;i50)
{
printf(“Good”);
else
printf(“Bad”);
}
Output:
Enter any five numbers 1 4 10 15 25
Bad
Page No.60
Discussion:
In this program first five numbers is asked to the user. Which was kept is an array. Since the sum is to be done repeatedly so the sum is also kept inside loop body where first the entered number is scaned and added to the sum. Finally, the sum is divided by five to find out the average of the entered number. If the average is greater than ‘50’ it display “Good” otherwise it display “Bad”.
4. WAP in C to accept a string and check if the string is palindrome or not.
Ans:
#include
#include
#include
void main()
{
clrscr();
char a[20],b[20];
puts(“Enter a string”);
gets(a);
strcpy(b,a);
strrev(a);
if (strcmp(a,b)=0)
printf(“The entered string is palindrome”);
else
printf(“The entered string is not palindrome”);
getch();
}
Output:
Enter a string pen
The entered string is not palindrome.
Enter a string dad
The entered string is palindrome.
Page No.61
Discussion:
This is the program to check whether the entered word is palindrome or not. Palindrome means such words whose reverse is also same. First of all user is asked to entered a string after that it is copied in other variable using strcpy() function and then it is reversed using strrev() function. At last it is compared that the entered string and the reverse of entered is equal to 0 or not. If yes it is palindrome otherwise it is not.
5. WAP to input the number and display the simple interest using function with argument.
Ans:
#include
#include
void S.I(int,int,int)
void main()
{
clrscr();
int p,t,r;
printf(“Enter the principle amount”);
scanf(“%d”,&p);
printf(“Enter the time”);
scanf(“%d”,&t);
printf(“Enter the rate”);
scanf(“%d”,&r);
S.I(p,t,r);
getch();
}
void S.I(int p,int t,int r)
{
int s;
s=(p*t*r)/100
printf(“Simple interest is %d”,s);
}
Output:
Enter the principle amount 23
Enter the time 5
Enter the rate 12
Simple interest is 1380
Page No: 62
Discussion:
This is the program to find out the simple interest using function with argument. First of all, user is asked to enter principle amt. After that user is asked to enter the time and rate. After giving the value of principle amt, time and rate, given variable s multiplied their value using (p*t*r)/100.
6. WAP to input the number and get area of circle and rectangle using menu.( using function without argument)
Ans:
#include
#include
void rect();
void circle();
void main()
{
clrscr();
printf(“Menu”);
printf(“\n 1. Area of rectangle”);
printf(“\n 2. Area of circle”);
printf(“\n 3. Exit”);
int n;
printf(“Select the option”);
scanf(“%d”,&n);
if(n==1)
{
rect();
}
else if (n==2)
{
circle();
}
else
{
printf(“This program is designed by………..”);
}
getch();
}
Page No. 63
Void circle()
{
float r,a;
printf(“Enter the no.”);
scanf(“%f”,&r);
a=3.1416*r*r;
printf(“Area of circle is %f”,a);
}
void rect()
{
int l,b,x;
printf(“Enter the length”);
scanf(“%d”,&l);
printf(“Enter the breadth”);
scanf(“%d”,&b);
a=l*b
printf(“Area of rectangle is %d”,a);
}
Output:
Menu
1. Area of rectangle
2. Area of circle
3. Exit
Select the option 1
Enter the length 12
Enter the breadth 15
Area of rectangle is 180
OR
Select the option 2
Enter the number 3
Area of circle is 28.2744
Page No. 64
7. WAP to input sum of n numbers using function with return type and array.
Ans:
#include
#include
int sum();
void main()
{
clrscr();
int a;
a=sum();
printf(“Sum is %d”,a);
getch();
}
int sum()
{
int n,I,s=0;
int ar[100];
printf(“How many number you want to get sum”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the number”);
scanf(“%d”,&ar[i]);
s=s+ar[i];
}
return(s);
}
Page No.65
8. WAP to create a structure named employee with number as name,address,age and gender.Create two variables,accept their records and print them.
Ans:
#include
#include
void main()
{
struct employee
{ char n[20],a[20],g[10];
in tag;
}x,y;
printf(“Enter name,address,age and gender of 1st employee\n”);
scanf(“%s %s %d %s”,x.n,x.a,&x.ag,x.g);
printf(“Enter name,address,age and gender of 2nd employee”);
scanf(“%s %s %d %s”,y.n,y.a,&y.ag,y.g);
printf(“name=%s ,%s\n address=%s,%s\n age=%d,%d \n gender=%s,%s”,
x.n,y.n,x.a,y.a,x.ag,y.ag,x.g,y.g);
getch();
}
Output:
Enter name, address, age and gender of 1st employee
Page No.66
Discussion:
It is a program written using structure. It helps us to enter different data types under one variable. In this program a structure is made named employee which contain 3 character string and one integer data types. All the process is same only difference is in argument in the function
9. WAP to display the context of the file “practical.txt”
Ans
#include
#include
void main()
{
clrscr();
int i,ag[6];
char n[6].ad[6];
file *fp;
fp=fopen(“practical.txt”, “r”);
for(i=0;i<6;i++)
{ fscanf (fp, “%s,%d,%s”, n,&ag,ad);
printf(“ name=%s \t age=%d\t address=%s”, n,ag,ad);}
fclose(fp);
getch();
}
No comments:
Post a Comment
Rahul-Notes