course: refresher course on intranet applications with java
venue: academic staff college, jntu kukkatpally, hyderabad
TCP/IP
Transmission Control Protocol / Internet Protocol
• Rajesh Kulkarni
TCP/IP & OSI
• In OSI reference model terminology -the TCP/IP protocol suite covers the network and transport layers.
• TCP/IP can be used on many data-link layers (can support many network hardware implementations).
Internet Protocol
The IP in TCP/IP
• IP is the network layer
• packet delivery service (host-to-host).
• translation between different data-link protocols.
IP Datagrams
• IP provides connectionless, unreliable delivery of IP datagrams.
• Connectionless: each datagram is independent of all others.
• Unreliable: there is no guarantee that datagrams are delivered correctly or even delivered at all.
IP Addresses
• IP addresses are not the same as the underlying data-link (MAC) addresses.
Why ?
IP Addresses
• IP is a network layer - it must be capable of providing communication between hosts on different kinds of networks (different data-link implementations).
• The address must include information about what network the receiving host is on. This is what makes routing feasible.
IP Addresses
• IP addresses are logical addresses (not physical)
• 32 bits.
• Includes a network ID and a host ID.
• Every host must have a unique IP address.
• IP addresses are assigned by a central authority (American Registry for Internet Numbers for North America).
The four formats of IP Addresses
Class A
128 possible network IDs
over 4 million host IDs per network ID
Network and Host IDs
• A Network ID is assigned to an organization by a global authority.
• Host IDs are assigned locally by a system administrator.
• Both the Network ID and the Host ID are used for routing.
IP Addresses
• IP Addresses are usually shown in dotted decimal notation:
1.2.3.4 00000001 00000010 00000011 00000100
• cs.rpi.edu is 128.213.1.1
10000000 11010101 00000001 00000001
Host and Network Addresses
• A single network interface is assigned a single IP address called the host address.
• A host may have multiple interfaces, and therefore multiple host addresses.
• Hosts that share a network all have the same IP network address (the network ID).
Subnet Addresses
• An organization can subdivide it’s host address space into groups called subnets.
• The subnet ID is generally used to group hosts based on the physical network topology.
Subnetting
Subnetting
• Subnets can simplify routing.
• IP subnet broadcasts have a hostID of all 1s.
• It is possible to have a single wire network with multiple subnets.
Mapping IP Addresses to Hardware Addresses
• IP Addresses are not recognized by hardware.
• If we know the IP address of a host, how do we find out the hardware address ?
• The process of finding the hardware address of a host given the IP address is called
Address Resolution
Reverse Address Resolution
• The process of finding out the IP address of a host given a hardware address is called
Reverse Address Resolution
• Reverse address resolution is needed by diskless workstations when booting (which used to be quite common).
ARP
• The Address Resolution Protocol is used by a sending host when it knows the IP address of the destination but needs the Ethernet (or whatever) address.
• ARP is a broadcast protocol - every host on the network receives the request.
• Each host checks the request against it’s IP address - the right one responds.
ARP (cont.)
• ARP does not need to be done every time an IP datagram is sent - hosts remember the hardware addresses of each other.
• Part of the ARP protocol specifies that the receiving host should also remember the IP and hardware addresses of the sending host.
ARP conversation
RARP conversation
Services provided by IP
• Connectionless Delivery (each datagram is treated individually).
• Unreliable (delivery is not guaranteed).
• Fragmentation / Reassembly (based on hardware MTU).
• Routing.
• Error detection.
IP Datagram
IP Datagram Fragmentation
• Each fragment (packet) has the same structure as the IP datagram.
• IP specifies that datagram reassembly is done only at the destination (not on a hop-by-hop basis).
• If any of the fragments are lost - the entire datagram is discarded (and an ICMP message is sent to the sender).
IP Flow Control & Error Detection
• If packets arrive too fast - the receiver discards excessive packets and sends an ICMP message to the sender (SOURCE QUENCH).
• If an error is found (header checksum problem) the packet is discarded and an ICMP message is sent to the sender.
ICMP
Internet Control Message Protocol
• ICMP is a protocol used for exchanging control messages.
• ICMP uses IP to deliver messages.
• ICMP messages are usually generated and processed by the IP software, not the user process.
ICMP Message Types
• Echo Request
• Echo Response
• Destination Unreachable
• Redirect
• Time Exceeded
• Redirect (route change)
• there are more ...
IP/BYE-BYE
• IP/BYE-BYE is a lecture protocol used to signal the class that we have just finished our discussion of IP - the network layer of TCP/IP.
• The appropriate response to an IP/BYE-BYE request is immediate applause, although simply opening your eyes is enough (known as a WAKEUP response).
Transport Layer & TCP/IP
Q: We know that IP is the network layer - so TCP must be the transport layer, right ?
A: No… well, almost.
TCP is only part of the TCP/IP transport layer - the other part is UDP (User Datagram Protocol).
UDP User Datagram Protocol
• UDP is a transport protocol
• communication between processes
• UDP uses IP to deliver datagrams to the right host.
• UDP uses ports to provide communication services to individual processes.
Ports
• TCP/IP uses an abstract destination point called a protocol port.
• Ports are identified by a positive integer.
• Operating systems provide some mechanism that processes use to specify a port.
Ports
UDP
• Datagram Delivery
• Connectionless
• Unreliable
• Minimal
TCP
Transmission Control Protocol
• TCP is an alternative transport layer protocol supported by TCP/IP.
• TCP provides:
• Connection-oriented
• Reliable
• Full-duplex
• Byte-Stream
Connection-Oriented
• Connection oriented means that a virtual connection is established before any user data is transferred.
• If the connection cannot be established - the user program is notified (finds out).
• If the connection is ever interrupted - the user program(s) is finds out there is a problem.
Reliable
• Reliable means that every transmission of data is acknowledged by the receiver.
• If the sender does not receive acknowledgement within a specified amount of time, the sender retransmits the data.
Byte Stream
• Stream means that the connection is treated as a stream of bytes.
• The user application does not need to package data in individual datagrams (as with UDP).
Buffering
• TCP is responsible for buffering data and determining when it is time to send a datagram.
• It is possible for an application to tell TCP to send the data it has buffered without waiting for a buffer to fill up.
Full Duplex
• TCP provides transfer in both directions (over a single virtual connection).
• To the application program these appear as 2 unrelated data streams, although TCP can piggyback control and data communication by providing control information (such as an ACK) along with user data.
TCP Ports
• Interprocess communication via TCP is achieved with the use of ports (just like UDP).
• UDP ports have no relation to TCP ports (different name spaces).
TCP Segments
• The chunk of data that TCP asks IP to deliver is called a TCP segment.
• Each segment contains:
• data bytes from the byte stream
• control information that identifies the data bytes
TCP Segment Format
Addressing in TCP/IP
• Each TCP/IP address includes:
• Internet Address
• Protocol (UDP or TCP)
• Port Number
TCP vs. UDP
Q: Which protocol is better ?
A: It depends on the application.
TCP provides a connection-oriented, reliable, byte stream service (lots of overhead).
UDP offers minimal datagram delivery service (as little overhead as possible).
TCP/IP Summary
• IP: network layer protocol
• unreliable datagram delivery between hosts.
• UDP: transport layer protocol
• unreliable datagram delivery between processes.
• TCP: transport layer protocol
• reliable, byte-stream delivery between processes.
Thursday, November 15, 2007
Intranet
topic: intranet
course:refresher course on intranet applications with java at jntu kukkatpally, hyderabad
audience: professors from jntu, engineering colleges.
venue: academic staff college jntu hyderabad
What is an Intranet?
What is an Intranet?
• A private network; a LAN or WAN.
• A website on a private network, often called a Corporate Portal.
What can an Intranet display?
• Practically anything!
– documents
– forms
– charts and graphs
– pictures & scanned images
– databases
– downloadable files
What can an Intranet display?
• Relatively static information
– benefits descriptions
– policies & procedures
– forms
– org charts
– newsletters
– document templates
– facility locations & maps
What can an Intranet display?
• Somewhat dynamic information
– phone & staff lists
– internal job postings
– driver signup lists
– run or line schedules
– turn-by-turn route directions
– project summaries and schedules
What can an Intranet display?
• Highly dynamic information
– daily performance metrics (rollout, attendance, stock levels, etc.)
– vehicle status & location
– on-board equipment monitoring alerts
– individual employee data (sick leave & vacation accrual, etc.)
How do I sell the idea?
• Operations:
– better, faster access to data
• Finance:
– Web-based reporting & OLAP tools allow users to query across all enterprise databases
• Information Services:
– reduced desktop support costs for browser-based applications
– a central source for user self-help (online training, User Guides, FAQs)
How do I sell the idea?
• Management:
– faster, easier access to all enterprise data for local, remote and mobile users
– reduced employee training costs due to a single, unified application interface
• All areas:
– post the material and the answers that people ask for over and over
How do I build an Intranet?
• The free, 10-minute, no-excuses Intranet
–
• The cheap, D-I-Y Intranet
–
• The scalable, Enterprise solution
–
How do I build an Intranet?
• The free, 10-minute, no-excuses Intranet
– Intranets.com, eGroups.com
• The cheap, D-I-Y Intranet
– a server, an HTML editor, and an Intern
• The scalable, Enterprise solution
– Xerox DocuSource, Plumtree, Hummingbird, WebUpdate or the like
A free intranets.com Intranet
AC Transit’s D-I-Y Intranet
How do I get users to visit?
• Start with a handful of things staff are always looking for:
– phone lists & org charts
– benefits info and health plan contacts
– internal job postings
• For some of these, make the Intranet the only place to get them
• Always, always keep it current
How will I know it’s a success?
• When you no longer have to explain what an Intranet is
• When you don’t have to go looking for content, it finds you
• When it’s the first place people look for information!
Driving the Intranet
Is your intranet
business positive?
Is your intranet business positive?
Intranets can be a very effective strategic resource within an organisation
An intranet can be a key business tool for achieving corporate goals
The reality, however, is that many intranets are not currently delivering on this ideal
This can be fixed
By using appropriate techniques and approaches, an intranet can be made business positive
History of the intranet
Most intranets have grown organically
With no overall strategy or direction, individual additions have been made ad-hoc
Common intranet problems:
• Unstructured, and inconsistent
• Out-of-date, inaccurate and incomplete
• Content authoring processes not working
• Information is hard to find
• Not widely used by staff
Bringing it into focus
The first step to building a better intranet is determining a strategic plan
This must be driven by staff needs
The organisation also has requirements that
must be met
Intranets are not a technology problem
Much more important are people and processes
Improving intranet design
There are a number of techniques that can be used to improve the design and structure of an intranet:
information architecture
usability
content writing
indexing
Beyond usable
A good intranet is usable: information is easy to find, the intranet is well-structured, and consistent
This is not enough
An intranet can be perfectly designed, but if the content is not right, it is entirely useless
An intranet must be useful: it meets the real needs of staff throughout the organisation
There are a range of practical techniques for ensuring this
Intranet goals
Intranet goals
Many intranets were established with a single goal:
“Deliver information effectively and efficiently to all staff”
Most intranets have now met this goal, and yet are still not delivering real benefits
An intranet must meet wider business goals to be effective
These must be aligned with corporate strategies
Good goals are a strategic “land grab”
Possible intranet goals
Better communication
Improve productivity
Better decision making
Enable feedback
Facilitate business processes
Meet budget
Reduce need for support
Reduce paper consumption
Reduce e-mail overload
Enhance collaboration
Support knowledge sharing
Build corporate identity
Create a single culture
Improve distribution of news
Support systems integration
Align with organisational strategy
Facilitate change management
More intranet goals
Provide a reference tool for staff
Achieve business improvements
Provide best practice information
Support geographically isolated staff
Support skills sharing
Support networking
Improve public image
Help staff to do their jobs
Support staff orientation
Improve information accessibility
Support training
Provide social environment
Become a focus for organisational systems
Act as an archive
Support business processes
Metrics & measures
Metrics are a way of defining what the intranet will achieve, and whether it met those goals
Also known as:
• Measures
• Key Performance Indicators (KPIs)
Often, but not always, numerical
Increasingly important in an environment of tight budgets
Key part of “Balanced Scorecard”
Benefits of metrics
Allows:
Targets to be set
Success to be assessed
ROI to be estimated
Ongoing viability to be tracked
Lessons to be learnt
Some sample metrics
System usage
Number of users
Information quality
Information currency
User feedback
Maintenance costs
Staff efficiency
Printing costs
Distributed authoring
Process efficiency
Transaction costs
Product sales
Customer satisfaction
Consistency of advice
Call handling time
Success stories, anecdotes
Staff morale
Cultural change
Staff learning
Guidelines & tips
Business-focused metrics are best
Determine a baseline
Automate measures
Measure the right things
Less, not more
Recognise the impact on staff
Re-evaluate measures every 6-12 months
Identifying staff needs
Identifying needs
An intranet will only be used if it meets actual
staff needs
It must also match organisational goals and strategies
Don’t ask staff what they need
Even if they want to, they can’t describe what they actually use and need
Use structured investigation methods
Structured techniques
Reviewing the existing environment
Expert site review
Focus groups & surveys
Usage & search statistics
Stakeholder interviews
Workplace observation
Process & knowledge mapping
Beyond surveys & focus groups
There are two traditional investigation methods:
Focus groups
• unstructured
• often does not reach consensus
• can be dominated by a few vocal members
Surveys
• staff will tell you what you want hear
• results don’t match reality
• difficult to create, time-consuming to analyse
Stakeholder interviews
Conduct stakeholder interviews with actual users
Focus on jobs, not intranet, with questions like:
• What are the main activities that make up your job?
• Who do you communicate most frequently with?
• What information do you use during a normal working day?
• Where do you obtain this information from?
• How do you find out about what’s happening in the organisation?
This is a simple form of knowledge mapping
Can be the first time staff are actually listened to
Workplace observation
Involves going ‘out into the field’, and watching staff conduct their normal activities
It is a holistic approach that can identify many issues and needs
Need to spend enough time to ‘blend in’
Must be done ethically
Very effective in a ‘front line’ environment, such as call centres, branches, etc.
Bringing it all together
Bringing it all together
Having a set of business-focused goals ensures that the intranet is positioned as a strategic asset
Goals also clarifies the direction to take
Taking a step back, and spending the time to understand staff needs is always enlightening
In this way, the intranet is driven from the ‘top down’ and the ‘bottom up’
This is much more effective than ‘sitting in a room and thinking hard about the intranet’
Bringing it all together (cont)
Maintaining an intranet is not enough
Improving structure, design & content of a site can be pointless if the site is not delivering the resources that staff need
There are thousands of ‘good ideas’ for an intranet
By understanding staff needs and intranet goals, priorities can be set, and resources applied effectively
This ensures that the intranet is business positive
Australian KM, CM & intranet groups
groups.yahoo.com/group/intranet-peers
A peer group of hands-on intranet managers in the public sector. Online list and forums in a major capital city every quarter.
groups.yahoo.com/group/NSW-KM-Forum-Announce
Announce list for NSW KM Forum meetings held in Sydney, 1st Thursday of each month
groups.yahoo.com/group/act-km
Australian mailing list for knowledge management
Questions?
Visit www.steptwo.com.au for more content management and intranet whitepapers
What’s Wrong with Intranets:
Users’ perspective
Users can’t find what they need (information architecture problem)
• “How come I didn’t know your department was developing a product similar to ours?”
• “Why couldn’t we find any relevant case studies to show that important prospect?”
• “Why do our sales and support staff keep giving our customers inconsistent information?”
What’s Wrong with Intranets:
Owners’ perspectives
Owners are overwhelmed (enterprise management problem)
• Content management pressures
• Resource allocation
• Technology selection
• Challenge of creating a unified intranet in a highly distributed environment
Users’ Problems
+ Owners’ Problems
= Enterprise IA (EIA)
The EIA Framework
Seven issues
• EIA governance: how the work and staff are structured
• EIA services: how work gets done in an enterprise environment
• EIA staffing: who handles strategic and tactical efforts
• EIA funding model: how it gets paid for
• EIA marketing and communications: how it gets adopted by the enterprise
• EIA workflow: how it gets maintained
• EIA design and timing: what gets created and when
EIA Governance:
Questions
What sort of individuals or group should be responsible for the EIA?
Where should they be located within the organization? How should they address strategic issues? Tactical issues?
Can they get their work done with carrots, sticks, or both as they try to work with somewhat autonomous business units?
EIA Governance:
A separate business unit 1/2
Logical outgrowth of
• Web or portal team
• Design or branding group
• E-services, e-business or e-commerce unit
Goals
• Ensure that IA is primary goal of the unit
• Retain organizational learning
• Avoid political baggage
• Maintain independence
EIA Governance:
A separate business unit 2/2
Ambitious, fool-hardy, unrealistic? Necessary!
• Models of successful new organizational efforts often start as separate entities
• Alternatives (none especially attractive)
• Be a part of IT or information services
• Be a part of marketing and communications
• Be a part of each business unit
EIA Governance:
Balancing strategic and tactical
Strategic: Model on Board of Directors
• 5-7 representatives of key constituencies
• Track record with successes, mistakes with organization’s prior centralization efforts
• Mix of visionaries, people who understand money
Tactical: Start with staff who “do stuff”
• Extend as necessary by outsourcing
• Enables logical planning of hiring and use of consultants and contractors
EIA Governance:
Board of directors 1/2
Goals
• Understand the strategic role of information architecture within the enterprise
• Promote information architecture services as a permanent part of the enterprise’s infrastructure
• Align the group and its services with those goals
• Ensure the group’s financial and political viability
• Help develop the group’s policies
• Support the group’s management
Makeup
• Draw first from effective leaders
• Then from major units that would be strategic partners
EIA Governance:
Board of directors 2/2
Qualities
• Experience and duration in the enterprise
• Wide visibility and extensive network
• Can draw on institutional memories and experiences
• Track record of involvement with successful initiatives
• Entrepreneurial (can read and write a business plan)
• Experienced with centralization efforts
• Does not shy away from political situations
• Can “sell” a new concept and find internal funding
• Is like the people you need to “sell” to
• Has experience with consulting operations
• Has experience negotiating with vendors
EIA Services:
Questions
What should a team responsible for EIA actually do?
How do their “services” fit with work that happens within business units? Or with outside contractors and consultants?
What kind of people should manage these efforts?
How do IA generalists and specialists fit together?
EIA Services:
From overwhelming to digestible
EIA Services:
Modular service plan
Avoid “monolithic” approach: “Hi, we’re the EIA team and we’re here to help… and we’re going to centralize all of your information…”
Break IA and CM into digestible, non-threatening tasks and sell those
• Allows you to divide and conquer clients…
• …and helps you understand IA challenges better (e.g., applying metadata in a centralized environment)
EIA Services:
Potential service offerings 1/2
User-oriented
• Persona and scenario development
• User testing and task analysis
• Search and server log analysis
Content-oriented
• Content inventory and analysis
• Content evaluation and assessment
• Content model design
• Content development policy (creation, maintenance)
• Content weeding, ROT removal, and archiving
• Content management tool (acquisition, maintenance)
• Metadata development
• Metadata maintenance
• Manual tagging
• Automated categorization and classification
EIA Services:
Potential service offerings 2/2
Context-oriented
• Business metrics development and analysis
• Internal marketing strategy and implementation
• Stakeholder and decision-maker interviews
• Business rules development (for best bets, content models, etc.)
Production/Maintenance
• Template design and application
• Training
• Policy/procedure/standards development and acceptance
• Publicity of new/changed content
• Tool analysis/acquisition (CMS, search, portal)
• Quality control and editing
• Link checking
• HTML validation
• Liaison with visual design staff, IT staff, vendors
EIA Services:
Assessing departmental IA needs
EIA Services:
Basic & premium levels
EIA Services:
Phased demand for IA services
EIA Staffing:
Questions
Who should be involved: in-house, consultant, contractor? What type of specialization should the staff have?
Should they be centralized or located within business units or both?
EIA Staffing:
Tactical team 1/4
Goals
• Delivers IA services to the enterprise in content, users, and context areas
• Implements the strategic team’s policies
• Works directly with clients to understand their needs and develop new services to meet those needs
EIA Staffing:
Tactical team 2/4
Make-up driven by “market demand,” existing resources
“Vertical” IA generalists: split between EIA project enterprise business units
“Horizontal” IA specialists: “consultants” for both groups of generalists
• Tools (e.g., search, portal, CMS)
• Metrics
• Evaluation
• Metadata development
• XML and other markup languages
EIA Staffing:
Tactical team 3/4
EIA Staffing:
Tactical team 4/4
Qualities for member of tactical team
• Entrepreneurial mindset
• Ability to consult (i.e., do work and justify IA and navigate difficult political environments)
• Willingness to acknowledge ignorance and seek help
• Ability to communicate with people from other fields
• Sensitivity to users’ needs
• …and know about IA and related fields
EIA Staffing:
Team Structure 1/2
EIA Staffing:
Team structure 2/2
EIA Funding Model:
Questions
How should this group be funded?
How should other expenses (e.g., software licenses) be covered? Charge-back fees for individual services? Flat “tax” paid by business units? Covered by general administration's tab? Some hybrid thereof?
Should certain services be performed gratis, while others require payment?
EIA Funding Model:
Looking for inspiration
Study the successes/failures of the enterprise’s other centrally funded services
Possible plan
• Initially: “tax” on business units and/or “seed capital” from senior management
• Ultimately: self-funding (models: IT, HR, special projects)
Key: funding should be from central group (e.g., senior management) or self-funded; else too much dependency on business units
EIA Funding Model:
Ensuring independence
Potential models already in existence in the enterprise
• Charge-back
• Tax on business units
• Money from general fund
• Hybrids
Charge-back model is attractive
• Increasing perceived value of IA by charging fees
• Compares well with duplicated expenses incurred by business units
EIA Funding Model:
Diversify revenue streams
EIA Marketing & Communications:
Questions
How to position this work and the group that supports it: IA? User Experience? Web Design? How do these terms affect the scope of the work/charter of the group?
How does a plan like this get “sold,” and to whom?
Whose support is needed, and what tactics are useful in convincing them to support EIA work?
How to prioritize which business units around the enterprise to work with?
EIA Marketing & Communications:
Positioning the EIA initiative
Approaching “clients”
• No carrot or stick
• Offer services and consulting that save money, reduce tedium
Branding: choose the term that is
• Hottest
• Has least baggage
• Steps on fewest toes
EIA Marketing & Communications:
Selling IA
Concrete
• We can make work easier and save money for individual business units
• We can improve the user experience and build brand loyalty among customers, organizational loyalty among employees
• We can minimize the enterprise’s habit of purchasing redundant licenses and services
EIA Marketing & Communications:
One unit at a time
Start with low-hanging fruit
• Killer content
• Plentiful or influential users
• Strategic value (business context)
Determine current status of the “client”
• What are they doing now?
• What expertise is in-house?
• What relevant tools do they own (extend licenses)?
• Are they enlightened?
EIA Marketing & Communications:
Illustrating the concept
Select an initial model for centralized approach that’s familiar, accessible
Staff directory often the best
• Serves all enterprise users
• Useful, highly structured content which may have significant metadata, searching and browsing capabilities
• Has high value in context of the enterprise’s daily operations
EIA Design/Timing:
Questions
An EIA design is an overwhelmingly large undertaking; how might it be broken into more digestible pieces?
How should they be sequence: what makes sense to take on now, later, or perhaps not at all?
EIA Design/Timing:
Modular, phased
EIA Design/Timing:
3-6 years, not months
Use early successes as models
Anticipate greater centralization among and within business units over time
Support different levels of centralization concurrently (Neanderthals coexist with Space Agers)
EIA Workflow:
Questions
How does the content authoring and publishing process work now?
Who and how many are involved?
How can the group support that work, and determine the best mix of centralized and autonomous responsibilities within that workflow?
EIA Workflow:
Deconstruct, then assign
Determine roles, then responsibilities among local and central units
Strive for evolution toward centralization
EIA Framework:
Summary
Entrepreneurial
• Services marketed to internal clients
• Goal of self-sustainability
Modular
• Specific services, not full package
• Logical migration path
Phased
• Projects that are low hanging fruit
• Selective roll-out
course:refresher course on intranet applications with java at jntu kukkatpally, hyderabad
audience: professors from jntu, engineering colleges.
venue: academic staff college jntu hyderabad
What is an Intranet?
What is an Intranet?
• A private network; a LAN or WAN.
• A website on a private network, often called a Corporate Portal.
What can an Intranet display?
• Practically anything!
– documents
– forms
– charts and graphs
– pictures & scanned images
– databases
– downloadable files
What can an Intranet display?
• Relatively static information
– benefits descriptions
– policies & procedures
– forms
– org charts
– newsletters
– document templates
– facility locations & maps
What can an Intranet display?
• Somewhat dynamic information
– phone & staff lists
– internal job postings
– driver signup lists
– run or line schedules
– turn-by-turn route directions
– project summaries and schedules
What can an Intranet display?
• Highly dynamic information
– daily performance metrics (rollout, attendance, stock levels, etc.)
– vehicle status & location
– on-board equipment monitoring alerts
– individual employee data (sick leave & vacation accrual, etc.)
How do I sell the idea?
• Operations:
– better, faster access to data
• Finance:
– Web-based reporting & OLAP tools allow users to query across all enterprise databases
• Information Services:
– reduced desktop support costs for browser-based applications
– a central source for user self-help (online training, User Guides, FAQs)
How do I sell the idea?
• Management:
– faster, easier access to all enterprise data for local, remote and mobile users
– reduced employee training costs due to a single, unified application interface
• All areas:
– post the material and the answers that people ask for over and over
How do I build an Intranet?
• The free, 10-minute, no-excuses Intranet
–
• The cheap, D-I-Y Intranet
–
• The scalable, Enterprise solution
–
How do I build an Intranet?
• The free, 10-minute, no-excuses Intranet
– Intranets.com, eGroups.com
• The cheap, D-I-Y Intranet
– a server, an HTML editor, and an Intern
• The scalable, Enterprise solution
– Xerox DocuSource, Plumtree, Hummingbird, WebUpdate or the like
A free intranets.com Intranet
AC Transit’s D-I-Y Intranet
How do I get users to visit?
• Start with a handful of things staff are always looking for:
– phone lists & org charts
– benefits info and health plan contacts
– internal job postings
• For some of these, make the Intranet the only place to get them
• Always, always keep it current
How will I know it’s a success?
• When you no longer have to explain what an Intranet is
• When you don’t have to go looking for content, it finds you
• When it’s the first place people look for information!
Driving the Intranet
Is your intranet
business positive?
Is your intranet business positive?
Intranets can be a very effective strategic resource within an organisation
An intranet can be a key business tool for achieving corporate goals
The reality, however, is that many intranets are not currently delivering on this ideal
This can be fixed
By using appropriate techniques and approaches, an intranet can be made business positive
History of the intranet
Most intranets have grown organically
With no overall strategy or direction, individual additions have been made ad-hoc
Common intranet problems:
• Unstructured, and inconsistent
• Out-of-date, inaccurate and incomplete
• Content authoring processes not working
• Information is hard to find
• Not widely used by staff
Bringing it into focus
The first step to building a better intranet is determining a strategic plan
This must be driven by staff needs
The organisation also has requirements that
must be met
Intranets are not a technology problem
Much more important are people and processes
Improving intranet design
There are a number of techniques that can be used to improve the design and structure of an intranet:
information architecture
usability
content writing
indexing
Beyond usable
A good intranet is usable: information is easy to find, the intranet is well-structured, and consistent
This is not enough
An intranet can be perfectly designed, but if the content is not right, it is entirely useless
An intranet must be useful: it meets the real needs of staff throughout the organisation
There are a range of practical techniques for ensuring this
Intranet goals
Intranet goals
Many intranets were established with a single goal:
“Deliver information effectively and efficiently to all staff”
Most intranets have now met this goal, and yet are still not delivering real benefits
An intranet must meet wider business goals to be effective
These must be aligned with corporate strategies
Good goals are a strategic “land grab”
Possible intranet goals
Better communication
Improve productivity
Better decision making
Enable feedback
Facilitate business processes
Meet budget
Reduce need for support
Reduce paper consumption
Reduce e-mail overload
Enhance collaboration
Support knowledge sharing
Build corporate identity
Create a single culture
Improve distribution of news
Support systems integration
Align with organisational strategy
Facilitate change management
More intranet goals
Provide a reference tool for staff
Achieve business improvements
Provide best practice information
Support geographically isolated staff
Support skills sharing
Support networking
Improve public image
Help staff to do their jobs
Support staff orientation
Improve information accessibility
Support training
Provide social environment
Become a focus for organisational systems
Act as an archive
Support business processes
Metrics & measures
Metrics are a way of defining what the intranet will achieve, and whether it met those goals
Also known as:
• Measures
• Key Performance Indicators (KPIs)
Often, but not always, numerical
Increasingly important in an environment of tight budgets
Key part of “Balanced Scorecard”
Benefits of metrics
Allows:
Targets to be set
Success to be assessed
ROI to be estimated
Ongoing viability to be tracked
Lessons to be learnt
Some sample metrics
System usage
Number of users
Information quality
Information currency
User feedback
Maintenance costs
Staff efficiency
Printing costs
Distributed authoring
Process efficiency
Transaction costs
Product sales
Customer satisfaction
Consistency of advice
Call handling time
Success stories, anecdotes
Staff morale
Cultural change
Staff learning
Guidelines & tips
Business-focused metrics are best
Determine a baseline
Automate measures
Measure the right things
Less, not more
Recognise the impact on staff
Re-evaluate measures every 6-12 months
Identifying staff needs
Identifying needs
An intranet will only be used if it meets actual
staff needs
It must also match organisational goals and strategies
Don’t ask staff what they need
Even if they want to, they can’t describe what they actually use and need
Use structured investigation methods
Structured techniques
Reviewing the existing environment
Expert site review
Focus groups & surveys
Usage & search statistics
Stakeholder interviews
Workplace observation
Process & knowledge mapping
Beyond surveys & focus groups
There are two traditional investigation methods:
Focus groups
• unstructured
• often does not reach consensus
• can be dominated by a few vocal members
Surveys
• staff will tell you what you want hear
• results don’t match reality
• difficult to create, time-consuming to analyse
Stakeholder interviews
Conduct stakeholder interviews with actual users
Focus on jobs, not intranet, with questions like:
• What are the main activities that make up your job?
• Who do you communicate most frequently with?
• What information do you use during a normal working day?
• Where do you obtain this information from?
• How do you find out about what’s happening in the organisation?
This is a simple form of knowledge mapping
Can be the first time staff are actually listened to
Workplace observation
Involves going ‘out into the field’, and watching staff conduct their normal activities
It is a holistic approach that can identify many issues and needs
Need to spend enough time to ‘blend in’
Must be done ethically
Very effective in a ‘front line’ environment, such as call centres, branches, etc.
Bringing it all together
Bringing it all together
Having a set of business-focused goals ensures that the intranet is positioned as a strategic asset
Goals also clarifies the direction to take
Taking a step back, and spending the time to understand staff needs is always enlightening
In this way, the intranet is driven from the ‘top down’ and the ‘bottom up’
This is much more effective than ‘sitting in a room and thinking hard about the intranet’
Bringing it all together (cont)
Maintaining an intranet is not enough
Improving structure, design & content of a site can be pointless if the site is not delivering the resources that staff need
There are thousands of ‘good ideas’ for an intranet
By understanding staff needs and intranet goals, priorities can be set, and resources applied effectively
This ensures that the intranet is business positive
Australian KM, CM & intranet groups
groups.yahoo.com/group/intranet-peers
A peer group of hands-on intranet managers in the public sector. Online list and forums in a major capital city every quarter.
groups.yahoo.com/group/NSW-KM-Forum-Announce
Announce list for NSW KM Forum meetings held in Sydney, 1st Thursday of each month
groups.yahoo.com/group/act-km
Australian mailing list for knowledge management
Questions?
Visit www.steptwo.com.au for more content management and intranet whitepapers
What’s Wrong with Intranets:
Users’ perspective
Users can’t find what they need (information architecture problem)
• “How come I didn’t know your department was developing a product similar to ours?”
• “Why couldn’t we find any relevant case studies to show that important prospect?”
• “Why do our sales and support staff keep giving our customers inconsistent information?”
What’s Wrong with Intranets:
Owners’ perspectives
Owners are overwhelmed (enterprise management problem)
• Content management pressures
• Resource allocation
• Technology selection
• Challenge of creating a unified intranet in a highly distributed environment
Users’ Problems
+ Owners’ Problems
= Enterprise IA (EIA)
The EIA Framework
Seven issues
• EIA governance: how the work and staff are structured
• EIA services: how work gets done in an enterprise environment
• EIA staffing: who handles strategic and tactical efforts
• EIA funding model: how it gets paid for
• EIA marketing and communications: how it gets adopted by the enterprise
• EIA workflow: how it gets maintained
• EIA design and timing: what gets created and when
EIA Governance:
Questions
What sort of individuals or group should be responsible for the EIA?
Where should they be located within the organization? How should they address strategic issues? Tactical issues?
Can they get their work done with carrots, sticks, or both as they try to work with somewhat autonomous business units?
EIA Governance:
A separate business unit 1/2
Logical outgrowth of
• Web or portal team
• Design or branding group
• E-services, e-business or e-commerce unit
Goals
• Ensure that IA is primary goal of the unit
• Retain organizational learning
• Avoid political baggage
• Maintain independence
EIA Governance:
A separate business unit 2/2
Ambitious, fool-hardy, unrealistic? Necessary!
• Models of successful new organizational efforts often start as separate entities
• Alternatives (none especially attractive)
• Be a part of IT or information services
• Be a part of marketing and communications
• Be a part of each business unit
EIA Governance:
Balancing strategic and tactical
Strategic: Model on Board of Directors
• 5-7 representatives of key constituencies
• Track record with successes, mistakes with organization’s prior centralization efforts
• Mix of visionaries, people who understand money
Tactical: Start with staff who “do stuff”
• Extend as necessary by outsourcing
• Enables logical planning of hiring and use of consultants and contractors
EIA Governance:
Board of directors 1/2
Goals
• Understand the strategic role of information architecture within the enterprise
• Promote information architecture services as a permanent part of the enterprise’s infrastructure
• Align the group and its services with those goals
• Ensure the group’s financial and political viability
• Help develop the group’s policies
• Support the group’s management
Makeup
• Draw first from effective leaders
• Then from major units that would be strategic partners
EIA Governance:
Board of directors 2/2
Qualities
• Experience and duration in the enterprise
• Wide visibility and extensive network
• Can draw on institutional memories and experiences
• Track record of involvement with successful initiatives
• Entrepreneurial (can read and write a business plan)
• Experienced with centralization efforts
• Does not shy away from political situations
• Can “sell” a new concept and find internal funding
• Is like the people you need to “sell” to
• Has experience with consulting operations
• Has experience negotiating with vendors
EIA Services:
Questions
What should a team responsible for EIA actually do?
How do their “services” fit with work that happens within business units? Or with outside contractors and consultants?
What kind of people should manage these efforts?
How do IA generalists and specialists fit together?
EIA Services:
From overwhelming to digestible
EIA Services:
Modular service plan
Avoid “monolithic” approach: “Hi, we’re the EIA team and we’re here to help… and we’re going to centralize all of your information…”
Break IA and CM into digestible, non-threatening tasks and sell those
• Allows you to divide and conquer clients…
• …and helps you understand IA challenges better (e.g., applying metadata in a centralized environment)
EIA Services:
Potential service offerings 1/2
User-oriented
• Persona and scenario development
• User testing and task analysis
• Search and server log analysis
Content-oriented
• Content inventory and analysis
• Content evaluation and assessment
• Content model design
• Content development policy (creation, maintenance)
• Content weeding, ROT removal, and archiving
• Content management tool (acquisition, maintenance)
• Metadata development
• Metadata maintenance
• Manual tagging
• Automated categorization and classification
EIA Services:
Potential service offerings 2/2
Context-oriented
• Business metrics development and analysis
• Internal marketing strategy and implementation
• Stakeholder and decision-maker interviews
• Business rules development (for best bets, content models, etc.)
Production/Maintenance
• Template design and application
• Training
• Policy/procedure/standards development and acceptance
• Publicity of new/changed content
• Tool analysis/acquisition (CMS, search, portal)
• Quality control and editing
• Link checking
• HTML validation
• Liaison with visual design staff, IT staff, vendors
EIA Services:
Assessing departmental IA needs
EIA Services:
Basic & premium levels
EIA Services:
Phased demand for IA services
EIA Staffing:
Questions
Who should be involved: in-house, consultant, contractor? What type of specialization should the staff have?
Should they be centralized or located within business units or both?
EIA Staffing:
Tactical team 1/4
Goals
• Delivers IA services to the enterprise in content, users, and context areas
• Implements the strategic team’s policies
• Works directly with clients to understand their needs and develop new services to meet those needs
EIA Staffing:
Tactical team 2/4
Make-up driven by “market demand,” existing resources
“Vertical” IA generalists: split between EIA project enterprise business units
“Horizontal” IA specialists: “consultants” for both groups of generalists
• Tools (e.g., search, portal, CMS)
• Metrics
• Evaluation
• Metadata development
• XML and other markup languages
EIA Staffing:
Tactical team 3/4
EIA Staffing:
Tactical team 4/4
Qualities for member of tactical team
• Entrepreneurial mindset
• Ability to consult (i.e., do work and justify IA and navigate difficult political environments)
• Willingness to acknowledge ignorance and seek help
• Ability to communicate with people from other fields
• Sensitivity to users’ needs
• …and know about IA and related fields
EIA Staffing:
Team Structure 1/2
EIA Staffing:
Team structure 2/2
EIA Funding Model:
Questions
How should this group be funded?
How should other expenses (e.g., software licenses) be covered? Charge-back fees for individual services? Flat “tax” paid by business units? Covered by general administration's tab? Some hybrid thereof?
Should certain services be performed gratis, while others require payment?
EIA Funding Model:
Looking for inspiration
Study the successes/failures of the enterprise’s other centrally funded services
Possible plan
• Initially: “tax” on business units and/or “seed capital” from senior management
• Ultimately: self-funding (models: IT, HR, special projects)
Key: funding should be from central group (e.g., senior management) or self-funded; else too much dependency on business units
EIA Funding Model:
Ensuring independence
Potential models already in existence in the enterprise
• Charge-back
• Tax on business units
• Money from general fund
• Hybrids
Charge-back model is attractive
• Increasing perceived value of IA by charging fees
• Compares well with duplicated expenses incurred by business units
EIA Funding Model:
Diversify revenue streams
EIA Marketing & Communications:
Questions
How to position this work and the group that supports it: IA? User Experience? Web Design? How do these terms affect the scope of the work/charter of the group?
How does a plan like this get “sold,” and to whom?
Whose support is needed, and what tactics are useful in convincing them to support EIA work?
How to prioritize which business units around the enterprise to work with?
EIA Marketing & Communications:
Positioning the EIA initiative
Approaching “clients”
• No carrot or stick
• Offer services and consulting that save money, reduce tedium
Branding: choose the term that is
• Hottest
• Has least baggage
• Steps on fewest toes
EIA Marketing & Communications:
Selling IA
Concrete
• We can make work easier and save money for individual business units
• We can improve the user experience and build brand loyalty among customers, organizational loyalty among employees
• We can minimize the enterprise’s habit of purchasing redundant licenses and services
EIA Marketing & Communications:
One unit at a time
Start with low-hanging fruit
• Killer content
• Plentiful or influential users
• Strategic value (business context)
Determine current status of the “client”
• What are they doing now?
• What expertise is in-house?
• What relevant tools do they own (extend licenses)?
• Are they enlightened?
EIA Marketing & Communications:
Illustrating the concept
Select an initial model for centralized approach that’s familiar, accessible
Staff directory often the best
• Serves all enterprise users
• Useful, highly structured content which may have significant metadata, searching and browsing capabilities
• Has high value in context of the enterprise’s daily operations
EIA Design/Timing:
Questions
An EIA design is an overwhelmingly large undertaking; how might it be broken into more digestible pieces?
How should they be sequence: what makes sense to take on now, later, or perhaps not at all?
EIA Design/Timing:
Modular, phased
EIA Design/Timing:
3-6 years, not months
Use early successes as models
Anticipate greater centralization among and within business units over time
Support different levels of centralization concurrently (Neanderthals coexist with Space Agers)
EIA Workflow:
Questions
How does the content authoring and publishing process work now?
Who and how many are involved?
How can the group support that work, and determine the best mix of centralized and autonomous responsibilities within that workflow?
EIA Workflow:
Deconstruct, then assign
Determine roles, then responsibilities among local and central units
Strive for evolution toward centralization
EIA Framework:
Summary
Entrepreneurial
• Services marketed to internal clients
• Goal of self-sustainability
Modular
• Specific services, not full package
• Logical migration path
Phased
• Projects that are low hanging fruit
• Selective roll-out
Wednesday, May 2, 2007
WASE C 25-03-7
BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
C Programming Language
Rajesh Kulkarni
Recommended Text Book
Reference Text Books
Why Learn C?
Feature of C Program
1. Every c program requires a main() function
2. The execution of a function begins at ( and ends t )
3. Programs should written in lowercase and uppercase are used for defining symbolic constants.
4. All the words in a program line must be separated from other by
at least one space or tab or punctuation mark.
5. Every statement must ends with a semi colon.
6. C is a free form language
a=b;
a=b+1; can be written in one line as a=b; a=b+1;
Character Set
The Character set in C are grouped into
1.Letters A,B,C…….Z; a, b, c ……z.
2.Digits 0,1,2……..9.
3.Special characters @,#,$,^………….etc
4.White Spaces
C Tokens (KISSCO)
Smallest individual units in c programming known as Tokens
1.Keywords
2.identifiers
3.Strings
4.Special Symbols
5.Constants
6.Operators
Key words
These are pre defined words have a fixed meanings.
All key words must be written in lower case letters.
Every word in c is either a keyword or identifier
Auto break case char const
char 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
Identifiers
Identifier refers to the names of variables ,functions ,and arrays.
Upper case and lower case letters are permited,but commonly lowercase letters we used.
It consists of letters and digits with letter as a first character.
Underscore also used as first letter
Constants
Constants in C refer to fixed values do not change during the execution of the program.
Integer constant: It refer to a sequence of digits, 0 through 9 preceded
by - or +. Ex: 149, -980, +45.
Real constants: the quantities which are represented by numbers
containing fractional part. Ex:0.78, 2.45.
It is also represented in exponential notation
Ex: the value 4356.78 can represented as 4.35678e3.
Single character constant: It contains a character enclosed within a pair
of single quote marks. Ex: '2' , 'a' .
String constant: It is a sequence of characters enclosed in double quotes.
Ex: "india" , "2*3", "n".
Back slash character constant (Escape sequences):
'\n' for new line
'\t' for horizontal tabulator
'\v ' for vertical tabulator
'\0' Null character.
Constants (Cont.)
Integer Constants
1.Decimal
2.Octal( Leading with 0)
3.HexaDecimal(Leading with 0x/oX)
Embedded spaces ,commas,nondigit characters are not permitted
Data Types
Data type size range
int 2 bytes -32,768 to 32,767
char 1 byte -128 to 128
float 4 bytes 3.4e-38 to 3.4e+38
double 8 bytes -1.7e-308 to1.7e+308
Variables
It is a data name that may be used to store value. Variable name may consist of letters ,digits, underscore(_) characters subject to the following conditions:
Variable must begin with letter.
Variable name should not be more than 8 characters.
Upper case and Lower case are significant.
Variable name should not be key word.
White space is not allowed.
Declaration of variables
Declaration tells to the compiler variable name with specifying data type.
a) Primary type : Syntax : data-type variable1,variable2,……..variable n;
Ex : float marks;
b) User defined type : C supports a feature known as type definition that
allows user to define an identifier.
Syntax : typedef data-type identifier;
Ex: typedef int units;
c) Enumerated data type: It contains enumeration constants represented
by identifiers.
Syntax: enum identifier { value 1,value 2,…..value n};
Ex: enum day { Monday, Tuesday,……Sunday};
d) Declaring variable as constant: The value of variable can be made to
remain constant.
syntax: const data-type variable = value;
Ex : const int max = 40;
e) Declaring variable as volatile :The value of variable may be changed
by some external reasons from out side.
Syntax : volatile data-type variable;
Ex : volatile int date ;
Declaration of Storage Classes
Automatic variable: Local variable known to only to the function in which is declared default is auto .
syntax : auto data-type variable;
Ex : auto int number;
Extern variables: Global variable known to all functions in the file. It is used to crossing files.
Syntax: extern data-type variable;
Ex: extern int number;
Static variables: Local variable, which exists and retains its value even after the control is transferred to the calling function.
Syntax : static data-type variable;
Ex : static int x;
Register variables: Local variable, which is stored in the CPU register. It is fast access variable.
Syntax : register data-type variable;
Ex : register int x;
Value can be assigned to variables using the assignment operator.
Syntax : data-type variable-name =constant;
Ex: int units =123;
Multiple assigning : Ex: x = y= z = max;
Type casting: C allows, if the operation are of different it types the lower type
is converted to the higher type to before operation proceed.
Syntax : (type-name) expression/value;
Ex: x = (int) 7.5 result = 7
Abstract data type: It is a tool which specifies the logical properties of a data type .
Syntax: abstract typedef < integer , integer > RATIONAL
Defining symbolic constants: This is useful when a constant will be used number
of places in a program.
# define symbolic-name value
Ex : #define MAX 100
# define PI 3.14159
Operators
Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.
Expressions operators along with the variables or operands is said to be expressions.
1.Arithemetic Operators
2.Relational Operators
3.Logical Operators
4.Assignment Operators
5.Increment & Decrement Operators
6.Conditional Operators
7.Bitwise Operators
8.Special Operators
Operators (Cont.)
Operators (cont.)
Special Operators in C
C Special Conditional Expression
Associativity and Precedence Rules
Order of Evaluation
Order of Evaluation
Comments
Good CommentingChapter 11
Introduction to
Programming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even though
LC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.
It is a general purpose programming language.
C is not tied to any particular hardware or system.
BCPL and B are type less languages while C is has data types.
C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded
In C % operator can not be applied on float.
In C % operator can not be applied with real operands.
% operator takes the sign of the I operand.
Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.
If one of them is negative then direction of truncation is implementation dependant. That is
-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions
Robust: built in functions, operators, middle level features
Efficient: data types and operators
Extensible: libraries, functions can be added
Portable: Can be run on any machine
Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.
Comments do not effect the execution size and speed.
Comments aid in debugging and testing.
C is a case sensitive language
\n new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Function
function Heading(Argument list)
• Compound statement
compound statement = { …..}
{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/
Structure of a C Program
• Documentation
nesting of comments not allowed
• Definition
symbolic constants
• Link section
links header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }
Structure…
The program will always begin by executing the main function.
The format of a C Program is
main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces
Tokens are smallest individual units of C. There are six tokens: Keywords, Identifiers, strings, special symbols, constants,Operators
Keywords: In ANSI C there are 32 keyword
Identifiers: names of variables, functions and arrays.
Strings: sequence of characters surrounded by double quotes.
keywords
Auto break case char const
char 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
Constants and variables
Special symbols: @,#,$,^
Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• Numeric
Integer
Real
• Character
Single
String
Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.
Integers may be decimal(0..9), octal(0..7), hex(0..15)
Real: Fractional parts represented using mantissa and
exponent form
Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’
Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.
Backslash character constants: escape sequences like /n, /t, /f.
Variables
Variables are data names for data types.
They change during the execution of programs.
Variable names start with a letter or underscore.
variable length is 31 characters, usage is 8 characters.
variable name must not be a keyword.
White spaces are not allowed.
Data types
ANSI C supports four classes of data types
• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values
Data types.. Sizes and ranges
• Char 1 byte. -128 to 127
• Int 2 bytes. -32768 to 32767
• Float 4 bytes 3.4e-38 to 3.4e+38
• Double 8 bytes. 1.7e-308 to 1.7e+308
Preprocessor directives
#include
#include indicates to the compiler the nature of the library functions being used like printf().
Stdio.h is a header file consisting of library functions like printf() and scanf()
Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.
#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);
#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);
#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1
Int 2 signed int 2 unsigned int 2
short int 2 long int 4
Float 4
Double 8 long double 10
Data types
Sizeof() is a special operator which gives the size of the data
sizeof(char) 1
sizeof(int) 2
sizeof(float) 4
sizeof(double) 8
…
File.c compile file.obj link file.exe
Int data type occupies how many bytes…
.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.
If interpreting, how many arithmetic operations occur?
If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single
arithmetic operation?
Compiling a C Program
Entire mechanism is usually called
the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
output is still C
Compiler
• generates object file
machine instructions
Linker
• combine object files
(including libraries)
into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0
/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)
into source code.
• Header files typically contain descriptions of functions and
variables needed by the program.
no restrictions -- could be any C source code
#define STOP 0
• Before compiling, replace all instances of the string
"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,
but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */
Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"
would be printed as: my/*don't print this*/string
As before, use comments to help reader, not to confuse
or to restate the obvious
main Function
Every C program must have a function called main().
This is the code that is executed
when the program is run.
The code for the function lives within brackets:
main()
{
/* code goes here */
}
Variable Declarations
Variables are used as names for data items.
Each variable has a type,
which tells the compiler how the data is to be interpreted
(and how much space it needs, etc.).
int counter;
int startPoint;
int is a predefined integer type in C.
Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.
printf("%d\n", counter);
• String contains characters to print and
formatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).
scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to the
variable startPoint. (Don't worry about the & yet.)
More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);
Print multiple expressions with a single statement
printf("%d %d\n", counter,
startPoint - counter);
Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);
produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.
Examples of Input
Many of the same formatting characters are
available for user input.
scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace),
stores the first one in length and the second in width
Must use ampersand (&) for variables being modified.
(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h
Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch() does not echo character to screen.
Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x) %d %e %f %g %i %o
%u %x %D %E %G %O %I %X %U
%field width format specifier printf(“%10f”,num);
%field width.precision format code printf(“%12.5”,num);
ALGORITHM
Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.
Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.
Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
ALGORITHM
Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
ALGORITHM
Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm
FLOWCHART
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:
FLOWCHART SYMBOLS
..\cds lab theory pavan sir's.DOC
Some examples c1.doc
C Programming Language
Rajesh Kulkarni
Recommended Text Book
Reference Text Books
Why Learn C?
Feature of C Program
1. Every c program requires a main() function
2. The execution of a function begins at ( and ends t )
3. Programs should written in lowercase and uppercase are used for defining symbolic constants.
4. All the words in a program line must be separated from other by
at least one space or tab or punctuation mark.
5. Every statement must ends with a semi colon.
6. C is a free form language
a=b;
a=b+1; can be written in one line as a=b; a=b+1;
Character Set
The Character set in C are grouped into
1.Letters A,B,C…….Z; a, b, c ……z.
2.Digits 0,1,2……..9.
3.Special characters @,#,$,^………….etc
4.White Spaces
C Tokens (KISSCO)
Smallest individual units in c programming known as Tokens
1.Keywords
2.identifiers
3.Strings
4.Special Symbols
5.Constants
6.Operators
Key words
These are pre defined words have a fixed meanings.
All key words must be written in lower case letters.
Every word in c is either a keyword or identifier
Auto break case char const
char 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
Identifiers
Identifier refers to the names of variables ,functions ,and arrays.
Upper case and lower case letters are permited,but commonly lowercase letters we used.
It consists of letters and digits with letter as a first character.
Underscore also used as first letter
Constants
Constants in C refer to fixed values do not change during the execution of the program.
Integer constant: It refer to a sequence of digits, 0 through 9 preceded
by - or +. Ex: 149, -980, +45.
Real constants: the quantities which are represented by numbers
containing fractional part. Ex:0.78, 2.45.
It is also represented in exponential notation
Ex: the value 4356.78 can represented as 4.35678e3.
Single character constant: It contains a character enclosed within a pair
of single quote marks. Ex: '2' , 'a' .
String constant: It is a sequence of characters enclosed in double quotes.
Ex: "india" , "2*3", "n".
Back slash character constant (Escape sequences):
'\n' for new line
'\t' for horizontal tabulator
'\v ' for vertical tabulator
'\0' Null character.
Constants (Cont.)
Integer Constants
1.Decimal
2.Octal( Leading with 0)
3.HexaDecimal(Leading with 0x/oX)
Embedded spaces ,commas,nondigit characters are not permitted
Data Types
Data type size range
int 2 bytes -32,768 to 32,767
char 1 byte -128 to 128
float 4 bytes 3.4e-38 to 3.4e+38
double 8 bytes -1.7e-308 to1.7e+308
Variables
It is a data name that may be used to store value. Variable name may consist of letters ,digits, underscore(_) characters subject to the following conditions:
Variable must begin with letter.
Variable name should not be more than 8 characters.
Upper case and Lower case are significant.
Variable name should not be key word.
White space is not allowed.
Declaration of variables
Declaration tells to the compiler variable name with specifying data type.
a) Primary type : Syntax : data-type variable1,variable2,……..variable n;
Ex : float marks;
b) User defined type : C supports a feature known as type definition that
allows user to define an identifier.
Syntax : typedef data-type identifier;
Ex: typedef int units;
c) Enumerated data type: It contains enumeration constants represented
by identifiers.
Syntax: enum identifier { value 1,value 2,…..value n};
Ex: enum day { Monday, Tuesday,……Sunday};
d) Declaring variable as constant: The value of variable can be made to
remain constant.
syntax: const data-type variable = value;
Ex : const int max = 40;
e) Declaring variable as volatile :The value of variable may be changed
by some external reasons from out side.
Syntax : volatile data-type variable;
Ex : volatile int date ;
Declaration of Storage Classes
Automatic variable: Local variable known to only to the function in which is declared default is auto .
syntax : auto data-type variable;
Ex : auto int number;
Extern variables: Global variable known to all functions in the file. It is used to crossing files.
Syntax: extern data-type variable;
Ex: extern int number;
Static variables: Local variable, which exists and retains its value even after the control is transferred to the calling function.
Syntax : static data-type variable;
Ex : static int x;
Register variables: Local variable, which is stored in the CPU register. It is fast access variable.
Syntax : register data-type variable;
Ex : register int x;
Value can be assigned to variables using the assignment operator.
Syntax : data-type variable-name =constant;
Ex: int units =123;
Multiple assigning : Ex: x = y= z = max;
Type casting: C allows, if the operation are of different it types the lower type
is converted to the higher type to before operation proceed.
Syntax : (type-name) expression/value;
Ex: x = (int) 7.5 result = 7
Abstract data type: It is a tool which specifies the logical properties of a data type .
Syntax: abstract typedef < integer , integer > RATIONAL
Defining symbolic constants: This is useful when a constant will be used number
of places in a program.
# define symbolic-name value
Ex : #define MAX 100
# define PI 3.14159
Operators
Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.
Expressions operators along with the variables or operands is said to be expressions.
1.Arithemetic Operators
2.Relational Operators
3.Logical Operators
4.Assignment Operators
5.Increment & Decrement Operators
6.Conditional Operators
7.Bitwise Operators
8.Special Operators
Operators (Cont.)
Operators (cont.)
Special Operators in C
C Special Conditional Expression
Associativity and Precedence Rules
Order of Evaluation
Order of Evaluation
Comments
Good CommentingChapter 11
Introduction to
Programming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even though
LC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.
It is a general purpose programming language.
C is not tied to any particular hardware or system.
BCPL and B are type less languages while C is has data types.
C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded
In C % operator can not be applied on float.
In C % operator can not be applied with real operands.
% operator takes the sign of the I operand.
Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.
If one of them is negative then direction of truncation is implementation dependant. That is
-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions
Robust: built in functions, operators, middle level features
Efficient: data types and operators
Extensible: libraries, functions can be added
Portable: Can be run on any machine
Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.
Comments do not effect the execution size and speed.
Comments aid in debugging and testing.
C is a case sensitive language
\n new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Function
function Heading(Argument list)
• Compound statement
compound statement = { …..}
{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/
Structure of a C Program
• Documentation
nesting of comments not allowed
• Definition
symbolic constants
• Link section
links header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }
Structure…
The program will always begin by executing the main function.
The format of a C Program is
main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces
Tokens are smallest individual units of C. There are six tokens: Keywords, Identifiers, strings, special symbols, constants,Operators
Keywords: In ANSI C there are 32 keyword
Identifiers: names of variables, functions and arrays.
Strings: sequence of characters surrounded by double quotes.
keywords
Auto break case char const
char 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
Constants and variables
Special symbols: @,#,$,^
Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• Numeric
Integer
Real
• Character
Single
String
Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.
Integers may be decimal(0..9), octal(0..7), hex(0..15)
Real: Fractional parts represented using mantissa and
exponent form
Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’
Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.
Backslash character constants: escape sequences like /n, /t, /f.
Variables
Variables are data names for data types.
They change during the execution of programs.
Variable names start with a letter or underscore.
variable length is 31 characters, usage is 8 characters.
variable name must not be a keyword.
White spaces are not allowed.
Data types
ANSI C supports four classes of data types
• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values
Data types.. Sizes and ranges
• Char 1 byte. -128 to 127
• Int 2 bytes. -32768 to 32767
• Float 4 bytes 3.4e-38 to 3.4e+38
• Double 8 bytes. 1.7e-308 to 1.7e+308
Preprocessor directives
#include
#include indicates to the compiler the nature of the library functions being used like printf().
Stdio.h is a header file consisting of library functions like printf() and scanf()
Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.
#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);
#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);
#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1
Int 2 signed int 2 unsigned int 2
short int 2 long int 4
Float 4
Double 8 long double 10
Data types
Sizeof() is a special operator which gives the size of the data
sizeof(char) 1
sizeof(int) 2
sizeof(float) 4
sizeof(double) 8
…
File.c compile file.obj link file.exe
Int data type occupies how many bytes…
.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.
If interpreting, how many arithmetic operations occur?
If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single
arithmetic operation?
Compiling a C Program
Entire mechanism is usually called
the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
output is still C
Compiler
• generates object file
machine instructions
Linker
• combine object files
(including libraries)
into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0
/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)
into source code.
• Header files typically contain descriptions of functions and
variables needed by the program.
no restrictions -- could be any C source code
#define STOP 0
• Before compiling, replace all instances of the string
"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,
but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */
Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"
would be printed as: my/*don't print this*/string
As before, use comments to help reader, not to confuse
or to restate the obvious
main Function
Every C program must have a function called main().
This is the code that is executed
when the program is run.
The code for the function lives within brackets:
main()
{
/* code goes here */
}
Variable Declarations
Variables are used as names for data items.
Each variable has a type,
which tells the compiler how the data is to be interpreted
(and how much space it needs, etc.).
int counter;
int startPoint;
int is a predefined integer type in C.
Input and Output
Variety of I/O functions in C Standard Library.
Must include
printf("%d\n", counter);
• String contains characters to print and
formatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).
scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to the
variable startPoint. (Don't worry about the & yet.)
More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);
Print multiple expressions with a single statement
printf("%d %d\n", counter,
startPoint - counter);
Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);
produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.
Examples of Input
Many of the same formatting characters are
available for user input.
scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace),
stores the first one in length and the second in width
Must use ampersand (&) for variables being modified.
(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h
Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch() does not echo character to screen.
Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x) %d %e %f %g %i %o
%u %x %D %E %G %O %I %X %U
%field width format specifier printf(“%10f”,num);
%field width.precision format code printf(“%12.5”,num);
ALGORITHM
Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.
Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.
Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
ALGORITHM
Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
ALGORITHM
Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm
FLOWCHART
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:
FLOWCHART SYMBOLS
..\cds lab theory pavan sir's.DOC
Some examples c1.doc
WASE CONTROL STMTS 08-04-07
#include
main()
{
printf("hello world\n");
printf("my age is 36\n");
getchar();
}
#include/*output*/
main()
{
int a;
printf("%d",a);
getchar();
}
#include
main()/* any errors*/
{
int 36age;
……
}
#include/* any errors!*/
main()/* any variable, define*/
{
age;
clrscr();
printf("hello world\n");
scanf("%d",age);
printf("the age u entered is %d",age);
fflush(stdin);
getchar();
}
#include
main()
{
int nob,nos,noc,ts,tc;
char name[10];
clrscr();
printf("enter your name:");
scanf("%s",&name);
printf("%s",name);
printf("\thow many brothers u have:",name);
scanf("%d",&nob);
printf("how many sisters u have:");
scanf("%d",&nos);
printf("how many children u have:");
scanf("%d",&noc);
ts=nob+nos;
tc=noc;
printf("total brothers and sisters are %d and total children are %d",ts,tc);
fflush(stdin);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter your age:");
scanf("%d",&age);
printf("the age you entered is %d");
fflush(stdin);
getchar();
}
#include
main()
{
printf("hello world\n");
getchar();
}
#include
main
(
)
{
printf(" he llo world\n");
getchar();
}
#include
main()
{
int age;
printf("hello world\n");
age=36;
printf("my age is %d\n",age);
getchar();
}
main()/*any interesting thing!*/
{
int age;
printf(“hello world\n”);
scanf(“%d\n”,age);
printf(“%d”,age);
#include
main()
{
char name[20],str2;
int length;
clrscr();
/* name ="rajesh";*/
strcpy(name,"rajesh");
strcpy(str2,"my name is\t");
strcat(str2,name);
printf(name);
printf("\n%s",str2);
length=strlen(str2);
printf("\n%d",length);
getchar();
}
#include
main()
{
int age,half,years;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
half=age/2;
years=age-5;
printf("\nhalf your age is %d",half);
printf("five years ago your age was %d",years);
getchar();
}
#include
main()
{
int x,y,z,p;
clrscr();
x=9;
y=x+6/3; /* divided by happens first result is 11*/
z=x*y+1+2-3*4;/*multiply happens first result is 90*/
printf("%d\t%d\t%d\n",x,y,z);
y=(x+6)/3;
p=15%6;
printf("%d\t%d\n",y,p);
p=(10+5)%12;
printf("%d\n",p);
printf("%d\n",3*17);
getchar();
}
#include
main()
{
int x=415;
double y=3.14159;
int len=1;
char string[30];
clrscr();
strcpy(string,"hello");
printf("12345678901234567890123456789\n");
printf("%s<<<<\n",string);
printf("%10s<<<<\n",string);/*right justified*/
printf("%-10s<<<<\n",string);/*left justified*/
printf("%.3s<<<\n",string);/*maximum number of characters*/
printf("%.*s",len,string);/*maximum characters specified by len */
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%d<<<<\n",x);
printf("%10d<<<<\n",x);
printf("%-10d<<<<\n",x);
printf("%010d<<<<\n",x);
printf("%.*d<<<<\n",len,x);
printf("%.1d<<<<\n",x);
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%c<<<<\n",string[0]);
printf("%10c<<<<\n",string[0]);
printf("%-10c<<<<\n",string[0]);
getchar();
}
#include
main()
{
int x;
double y;
char string[100];
clrscr();
printf("enter a word:");
scanf("%s",string);/*no ampersand is used*/
fflush(stdin);
printf("\n the word entered is %s\n",string);
printf("enter many words:");
scanf("%[^\n]",string);
fflush(stdin);
printf("%s\n",string);
getchar();
}
#include
main()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("you are %d years old!\n",age);
if (age > magic_age)
printf("you are very old!\n");
printf("you are %d older than %d\n",age-magic_age,magic_age);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
fflush(stdin);
if ( age > 30)
printf("you are older than 30\n");
age = age +5;
printf("\n\n=====block within a block====\n\n");
{
int newage;
newage=age+30;
printf("newage is %d\n",newage);
}
getchar();
}
#include
main ()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("your age is %d\n",age);
if (age < magic_age)
printf("you are young\n");
else
if (age > magic_age)
printf("you are old\n");
else
if (age == 40)
printf("perfect!!!\n");
else
printf("invalid age!\n");
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if (age <30);/* no error will be shown and wow! will be printed irrespective of whatever you enter*/
printf("wow!");
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if(age <= 1)
printf("kid\n");
else if (age <=18)
printf("youngster\n");
else if (age == 21)
printf("now you are grown up\n");
else if (age == 40)
printf(" you are getting older\n");
else
printf("invalid entry\n");
fflush(stdin);
getchar();
}
#include
main()
{
double x=5000.0,y=0.0025,num=13.4485;
clrscr();
printf("12345678901234567890123456789\n");
printf("%f %f\n",x,y);/* if %d is used output is 0*/
printf("%e %e\n",x,y);
printf("%f\n",num);
printf("%10f\n",num);
printf("%12.5f\n",num);
printf("%.3f\n",num);
getchar();
}
#include
main()
{
int i=12345;
float x=345.678;
clrscr();
printf("12345678901234567890123456789\n");
printf("%3d\n",i);
printf("%5d\n",i);
printf("%8d\n",i);
printf("%3g\n",x);
printf("%10g\n",x);
printf("%13g\n",x);
getchar();
}
#include
main()
{
float x=123.456;
clrscr();
printf("12345678901234567890123456789\n");
printf("%7f\n",x);
printf("%7.3f\n",x);
printf("%7.1f\n");
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
printf("\nyou are %d years old\n",age);
switch(age)
{
case 1:
case 2:
case 3:
printf("sorry you can not go to school\n");
break; /*if break is forgotten next stmt will be executed*/
case 5:
printf("you are now in I class\n");
break;
case 15:
printf("you must be in 10th standard now\n");
break;
case 18:
printf("ready to vote!!!\n");
break;
case 21:
printf("ready to get married\n");
break;
case 40:
printf("you have matured\n");
break;
case 58:
printf("you can retire, now!!!\n");
break;
default:
printf("your age is of no importance!\n");
}
fflush(stdin);
getchar();
}
#include
main()
{
int age;
int very_old = age >=80;
clrscr();
printf("enter your age:");
scanf("%d",&age);
if (very_old)/*if(3+4) will also give the same result*/
printf("you are very old as you are %d years old\n",age);
printf("the value of the variable very_old is %d\n",very_old);
fflush(stdin);
getchar();
}
/*correct the bug*/
main()
{
int x = 1:
if (x = 1);
printf("x equals 1\m")
otherwise
printf("x does not equal 1\m");
fflush(stdio);
getchar(char);
)
#include
main()
{
int x=5;
clrscr();
if(x=1)
printf("one\n");
getchar();
}
Exercise
Wap CD shop database.input the following details and print them again on the screen.
movie,director,number of songs,hit/fail,price.
/*use of got lable*/
main()
{
int age;
char name[41];
int very_old;
printf("Please enter your age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);
if (!(age <= 19 && age >= 13))
goto other;
if (age > 19 || age < 13)
printf("You are not a teenager\n");
up:
if (age == 10 || age == 20 || age == 30 || age > 100)
printf("You have a special age\n");
printf("Please enter your name: ");
scanf("%s", name);
if (!(strcmp(name, "Bruce") != 0 && age != 40))
printf("You not called Bruce and are aged 40.\n");
if (strcmp(name, "Bruce") == 0 || age == 40)
printf("You not called Bruce and are aged 40.\n");
other:
very_old = age > 80;
if (!very_old)
printf("You are not very old\n");
if (very_old == 0)
printf("You are not very old\n");
if (age > 10)
goto up;
fflush(stdin);
getchar();
}
two approaches of programming:
programmer’s perspective
• structured programming
• object oriented programming
end user’s perspective
• sequential
• event driven
. • Assignment operator =
. • Arithmetic operators +, -, *, /, %
. • Relational operators >, >=, <, <=, == , !=
. • Logical operators !, &&, ||
. • Address operator &
. • Increment and Decrement operators ++, -
. • Compound Assignment Operators =, +=, -=, /=, *=, %=
. • sizeof operator
The basic arithmetic operators help us in performing the arithmetic operations.The % (modulo operator) is used to find the reminder of a divide operation eg.
int x=5,y=2;
int z=5/2;
will store 2 in z
int z=5%2
will store 1 in z % operator cannot be applied to float data type. Hence the instruction
5.2 % 2.5
will result in error For comparing if 2 values are equal or not remember to use == and not a single =.
== indicates comparisons and
= indicates assignment operation
eg. int x=5,y=3 x==y
will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero)
x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3.
Logical operators available are
! (NOT), && (AND), || (OR) eg.
consider 3 variables x,y,z containing values 1,2,3 respectively
x=1, y=2, z=3
the condition x==1 && y == 3 will evaluate to false
the condition x==1 && z==3 will evaluate to true
the condition x==1 || y==3 will evaluate to true
the condition x==1 || z==3 will evaluate to true
the condition !(x <2 && y==2) will evaluate to false
Classification of Operators:
.(1) Based on the number of operands:
.
.Unary operators ++, -
.
.Binary operators +,-,*,/,%,==,<,>,>=,<=,!=,&&,||
.
.Ternary operators ? :
.
.(2) Based on the operations performed:
.
.Arithmetic operators
.
.Relational operators
.
.Logical operators
• Assign an expression to a variable
Syntax
Variable = Variable or constant or expression
data-type variable = constant
Example:
iNum = 10;
int i = 10;
float f = 13.24;
The statement i = f, will truncate the value .24 from f and i will have a value 13
Type Casting
. • Temporary conversion of one data type into another
. • In some situations, the compiler will automatically convert one data type into another
. • Type casting is an overhead for the compiler
. • Example:
float fResult;
fResult = 7 / 2 ;
The variable fResult will store 3.0 instead of 3.5
To get the ‘float’ value, the expression should be:
fResult = 7.0 / 2; or
fResult = 7 / 2.0; or
fResult = 7.0 / 2.0; or
fResult = (float) 7 / 2; or
fResult = 7 / (float) 2;
Precedence of Arithmetic Operators
Operator Priority
* , / and % Highest
+ and Lowest
Structured Programming
Rajesh Kulkarni
Control Structures: conditional constructs
if statement
if (expression) statement1
if (expression) statement1 else statement2
expression must have an integral type. Zero is false, nonzero is true.
Notes:
expression must be parenthesized
Examples
Examples
Which of the following code is preferred?why?
Examples
/* This program displays the absolute value of a number given by the user */
#include
int main()
{
double num;
printf("Please enter a real number: ");
scanf("%lf", &num);
if (num<0)
num = -num;
printf("The absolute value is %g\n", num);
return 0;
}
if-else statement
condition
True or false
In C, every expression has a numeric value
An expression is ‘true’ when its value is non-zero
If it is zero, it is false
Therefore, in the following –
if (expression) statement
statement is executed if expression is non zero.
More about operators
In C, every expression has a numeric value
When using arithmetical operators (+, -, *, /) this is straightforward
The value of A+B is the sum of A and B
And so on…
More about operators
Expressions with relational operators (<, <=, >, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’)
A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B
The exact non-zero value varies (and is not important for that matter)
Relational operators
They are:
A == B (Note the difference from A = B!!!!!)
A != B
A < B
A > B
A <= B
A >= B
The value of the expression is non-zero if it’s true, zero if it’s false
An example (fragment)
int first, second, min;
/* … */
if (first < second)
{
min = first;
printf ("The first number is smaller than the second.\n");
}
else
{
min = second;
printf ("The second number is smaller than the first\n");
}
printf("The smaller number is equal to %d\n", min);
An example
int a, b;
printf("Enter two numbers\n");
scanf("%d%d", &a, &b);
if (a == b)
{
printf("The numbers equal %d\n", a);
printf("The expression a == b is %d\n", a == b);
}
else
{
printf("The numbers are not equal\n");
printf("The expression a == b is %d\n", a == b);
}
The assignment operator =
The assignment operator is also an operator. Hence, expressions involving it have a numeric value.
This value equals to whatever appears on the right of the assignment operator
For example:
(x = 4) evaluates to 4
(y = 0) evaluates to 0
A very common mistake
Very often a programmer might confuse between the equality operator and the assignment operator:
if (x==4) …
if (x=4) …
The second is usually a mistake, but legal in C so the compiler doesn’t warn us about it!
Logical operators
Allows to evaluate two or more expressions -
!A – ‘not’ - True when A is not, and vice versa.
A && B – ‘and’ - True when both A and B are true
A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true
A silly example
#include
int main(void)
{
int grade;
printf("Please enter your grade: ");
scanf("%d", &grade);
if (grade < 0 || grade > 100)
printf("This is not a valid grade!\n");
else
printf("This is indeed a grade.\n");
return 0;
}
Example
main()
{ int x;
scanf(”%d”,&x);
if(x%2)
{
printf(“ the number %d is ODD\n”,x);
}
else
{
printf(“ the number %d is EVEN\n”,x);
}
}
Example
main()
{ int x,y;
x=10;y=20;
printf(“ %d%d are\n”,x,y);
x=x+y;
y=x-y;
x=x-y;
printf(“ %d%d are\n”,x,y);
}
Dangling else problem
if (exp1) if (exp2) stmta else stmtb
Avoiding the dangling else problem
Null statement
if (exp1)
if (exp2)
stmta
else
;
else
stmtb
else if statements
if statements distinguish between exactly 2 cases and execute different code in each case
The else-if construction allows for a multi-way decision
else if statements
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
An example
if (grade >= 90)
printf ("A\n");
else if (grade >= 80)
printf ("B\n");
else if (grade >= 70)
printf ("C\n");
else if (grade >= 60)
printf ("D\n");
else
printf ("F\n");
Validating input
When getting input from the user, it is highly recommended to check whether it is valid.
If it’s not, you should display an appropriate message and return a non-zero value.
For example –
if (grade < 0 || grade > 100)
{
printf(“Invalid input!\n”);
return 1;
}
The return keyword
For now, used to terminate the program and return a value to the operating system
If the program is successful the return value should be zero; non-zero otherwise
The exact nature of this keyword will become clear in the future
Exercise
Input –
An English letter
Output –
If input is a lowercase letter – the corresponding uppercase letter
If input is an uppercase letter - corresponding lowercase letter
Note –
Remember to check for input validity!
Exercise
Input
Two integers, A and B
Output
Their relation (i.e. displays A==B, AB)
Solution
#include
int main()
{
int A, B;
printf("Enter two Numbers\n");
scanf("%d%d", &A, &B);
if (A == B)
printf("A==B\n");
else if (A > B)
printf("A>B\n");
else
printf("A
return 0;
}
The switch statement
a multiway conditional statement
similar to if-else if-else
allows the selection of an arbitrary number
of choices based on an integer value
The switch statement
expression must have an integer value
when the switch statement is executed:
the expression is evaluated
if a case matches the value of the expression, the program jumps to the first statement after that case label
otherwise, the default case is selected
the default is optional
That grade example again
switch (grade/10) {
case 10:
case 9:
printf ("A\n");
break;
case 8:
printf ("B\n");
break;
case 7:
printf ("C\n");
break;
case 6:
printf ("D\n");
break;
default:
printf ("F\n");
}
Give me a break
when the switch transfers to the chosen case, it starts executing statements at that point
it will “fall through” to the next case unless you “break out”
break causes the program to immediately jump to the next statement after the switch statement
switch
switch (expression) {
case const-expr/: statements
case const-expr/: statements
default : statements
}
switch (digit)
{
case 0:
case 1:
case 2:
case 3:
case 4: printf (“Round down\n”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:printf(“Round up\n”);
}
Exercise
Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin
1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar
Remember to check for the validity of the input!
The ?: operator
expr1 ? expr2 : expr3
Nicer way to write:
(expr1)? expr2 : expr3
If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated
The ?: operator
#include
int main()
{
int i, j, min;
printf("Please enter two numbers: ");
scanf("%d%d", &i, &j);
min = (i < j)? i : j;
printf("The minimum between %d and %d is %d\n", i, j, min);
return 0;
}
Goto Statements
goto label;
………
……..
label : statements;
Goto Statements
Forward goto: if statement along with the label appear below the goto statement
Backward goto: if statement along with the label appear above the goto statement
Iteration Constructs
Iteration constructs repeat a sequence of code in a controlled manner.
while
for
do-while
while loop
while (expression)
statement
main()
{
printf("hello world\n");
printf("my age is 36\n");
getchar();
}
#include
main()
{
int a;
printf("%d",a);
getchar();
}
#include
main()/* any errors*/
{
int 36age;
……
}
#include
main()/* any variable, define*/
{
age;
clrscr();
printf("hello world\n");
scanf("%d",age);
printf("the age u entered is %d",age);
fflush(stdin);
getchar();
}
#include
main()
{
int nob,nos,noc,ts,tc;
char name[10];
clrscr();
printf("enter your name:");
scanf("%s",&name);
printf("%s",name);
printf("\thow many brothers u have:",name);
scanf("%d",&nob);
printf("how many sisters u have:");
scanf("%d",&nos);
printf("how many children u have:");
scanf("%d",&noc);
ts=nob+nos;
tc=noc;
printf("total brothers and sisters are %d and total children are %d",ts,tc);
fflush(stdin);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter your age:");
scanf("%d",&age);
printf("the age you entered is %d");
fflush(stdin);
getchar();
}
#include
main()
{
printf("hello world\n");
getchar();
}
#include
main
(
)
{
printf(" he llo world\n");
getchar();
}
#include
main()
{
int age;
printf("hello world\n");
age=36;
printf("my age is %d\n",age);
getchar();
}
main()/*any interesting thing!*/
{
int age;
printf(“hello world\n”);
scanf(“%d\n”,age);
printf(“%d”,age);
#include
main()
{
char name[20],str2;
int length;
clrscr();
/* name ="rajesh";*/
strcpy(name,"rajesh");
strcpy(str2,"my name is\t");
strcat(str2,name);
printf(name);
printf("\n%s",str2);
length=strlen(str2);
printf("\n%d",length);
getchar();
}
#include
main()
{
int age,half,years;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
half=age/2;
years=age-5;
printf("\nhalf your age is %d",half);
printf("five years ago your age was %d",years);
getchar();
}
#include
main()
{
int x,y,z,p;
clrscr();
x=9;
y=x+6/3; /* divided by happens first result is 11*/
z=x*y+1+2-3*4;/*multiply happens first result is 90*/
printf("%d\t%d\t%d\n",x,y,z);
y=(x+6)/3;
p=15%6;
printf("%d\t%d\n",y,p);
p=(10+5)%12;
printf("%d\n",p);
printf("%d\n",3*17);
getchar();
}
#include
main()
{
int x=415;
double y=3.14159;
int len=1;
char string[30];
clrscr();
strcpy(string,"hello");
printf("12345678901234567890123456789\n");
printf("%s<<<<\n",string);
printf("%10s<<<<\n",string);/*right justified*/
printf("%-10s<<<<\n",string);/*left justified*/
printf("%.3s<<<\n",string);/*maximum number of characters*/
printf("%.*s",len,string);/*maximum characters specified by len */
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%d<<<<\n",x);
printf("%10d<<<<\n",x);
printf("%-10d<<<<\n",x);
printf("%010d<<<<\n",x);
printf("%.*d<<<<\n",len,x);
printf("%.1d<<<<\n",x);
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%c<<<<\n",string[0]);
printf("%10c<<<<\n",string[0]);
printf("%-10c<<<<\n",string[0]);
getchar();
}
#include
main()
{
int x;
double y;
char string[100];
clrscr();
printf("enter a word:");
scanf("%s",string);/*no ampersand is used*/
fflush(stdin);
printf("\n the word entered is %s\n",string);
printf("enter many words:");
scanf("%[^\n]",string);
fflush(stdin);
printf("%s\n",string);
getchar();
}
#include
main()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("you are %d years old!\n",age);
if (age > magic_age)
printf("you are very old!\n");
printf("you are %d older than %d\n",age-magic_age,magic_age);
getchar();
}
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
fflush(stdin);
if ( age > 30)
printf("you are older than 30\n");
age = age +5;
printf("\n\n=====block within a block====\n\n");
{
int newage;
newage=age+30;
printf("newage is %d\n",newage);
}
getchar();
}
#include
main ()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("your age is %d\n",age);
if (age < magic_age)
printf("you are young\n");
else
if (age > magic_age)
printf("you are old\n");
else
if (age == 40)
printf("perfect!!!\n");
else
printf("invalid age!\n");
getchar();
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if (age <30);/* no error will be shown and wow! will be printed irrespective of whatever you enter*/
printf("wow!");
}
#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);
if(age <= 1)
printf("kid\n");
else if (age <=18)
printf("youngster\n");
else if (age == 21)
printf("now you are grown up\n");
else if (age == 40)
printf(" you are getting older\n");
else
printf("invalid entry\n");
fflush(stdin);
getchar();
}
#include
main()
{
double x=5000.0,y=0.0025,num=13.4485;
clrscr();
printf("12345678901234567890123456789\n");
printf("%f %f\n",x,y);/* if %d is used output is 0*/
printf("%e %e\n",x,y);
printf("%f\n",num);
printf("%10f\n",num);
printf("%12.5f\n",num);
printf("%.3f\n",num);
getchar();
}
#include
main()
{
int i=12345;
float x=345.678;
clrscr();
printf("12345678901234567890123456789\n");
printf("%3d\n",i);
printf("%5d\n",i);
printf("%8d\n",i);
printf("%3g\n",x);
printf("%10g\n",x);
printf("%13g\n",x);
getchar();
}
#include
main()
{
float x=123.456;
clrscr();
printf("12345678901234567890123456789\n");
printf("%7f\n",x);
printf("%7.3f\n",x);
printf("%7.1f\n");
#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
printf("\nyou are %d years old\n",age);
switch(age)
{
case 1:
case 2:
case 3:
printf("sorry you can not go to school\n");
break; /*if break is forgotten next stmt will be executed*/
case 5:
printf("you are now in I class\n");
break;
case 15:
printf("you must be in 10th standard now\n");
break;
case 18:
printf("ready to vote!!!\n");
break;
case 21:
printf("ready to get married\n");
break;
case 40:
printf("you have matured\n");
break;
case 58:
printf("you can retire, now!!!\n");
break;
default:
printf("your age is of no importance!\n");
}
fflush(stdin);
getchar();
}
#include
main()
{
int age;
int very_old = age >=80;
clrscr();
printf("enter your age:");
scanf("%d",&age);
if (very_old)/*if(3+4) will also give the same result*/
printf("you are very old as you are %d years old\n",age);
printf("the value of the variable very_old is %d\n",very_old);
fflush(stdin);
getchar();
}
/*correct the bug*/
main()
{
int x = 1:
if (x = 1);
printf("x equals 1\m")
otherwise
printf("x does not equal 1\m");
fflush(stdio);
getchar(char);
)
#include
main()
{
int x=5;
clrscr();
if(x=1)
printf("one\n");
getchar();
}
Exercise
Wap CD shop database.input the following details and print them again on the screen.
movie,director,number of songs,hit/fail,price.
/*use of got lable*/
main()
{
int age;
char name[41];
int very_old;
printf("Please enter your age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);
if (!(age <= 19 && age >= 13))
goto other;
if (age > 19 || age < 13)
printf("You are not a teenager\n");
up:
if (age == 10 || age == 20 || age == 30 || age > 100)
printf("You have a special age\n");
printf("Please enter your name: ");
scanf("%s", name);
if (!(strcmp(name, "Bruce") != 0 && age != 40))
printf("You not called Bruce and are aged 40.\n");
if (strcmp(name, "Bruce") == 0 || age == 40)
printf("You not called Bruce and are aged 40.\n");
other:
very_old = age > 80;
if (!very_old)
printf("You are not very old\n");
if (very_old == 0)
printf("You are not very old\n");
if (age > 10)
goto up;
fflush(stdin);
getchar();
}
two approaches of programming:
programmer’s perspective
• structured programming
• object oriented programming
end user’s perspective
• sequential
• event driven
. • Assignment operator =
. • Arithmetic operators +, -, *, /, %
. • Relational operators >, >=, <, <=, == , !=
. • Logical operators !, &&, ||
. • Address operator &
. • Increment and Decrement operators ++, -
. • Compound Assignment Operators =, +=, -=, /=, *=, %=
. • sizeof operator
The basic arithmetic operators help us in performing the arithmetic operations.The % (modulo operator) is used to find the reminder of a divide operation eg.
int x=5,y=2;
int z=5/2;
will store 2 in z
int z=5%2
will store 1 in z % operator cannot be applied to float data type. Hence the instruction
5.2 % 2.5
will result in error For comparing if 2 values are equal or not remember to use == and not a single =.
== indicates comparisons and
= indicates assignment operation
eg. int x=5,y=3 x==y
will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero)
x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3.
Logical operators available are
! (NOT), && (AND), || (OR) eg.
consider 3 variables x,y,z containing values 1,2,3 respectively
x=1, y=2, z=3
the condition x==1 && y == 3 will evaluate to false
the condition x==1 && z==3 will evaluate to true
the condition x==1 || y==3 will evaluate to true
the condition x==1 || z==3 will evaluate to true
the condition !(x <2 && y==2) will evaluate to false
Classification of Operators:
.(1) Based on the number of operands:
.
.Unary operators ++, -
.
.Binary operators +,-,*,/,%,==,<,>,>=,<=,!=,&&,||
.
.Ternary operators ? :
.
.(2) Based on the operations performed:
.
.Arithmetic operators
.
.Relational operators
.
.Logical operators
• Assign an expression to a variable
Syntax
Variable = Variable or constant or expression
data-type variable = constant
Example:
iNum = 10;
int i = 10;
float f = 13.24;
The statement i = f, will truncate the value .24 from f and i will have a value 13
Type Casting
. • Temporary conversion of one data type into another
. • In some situations, the compiler will automatically convert one data type into another
. • Type casting is an overhead for the compiler
. • Example:
float fResult;
fResult = 7 / 2 ;
The variable fResult will store 3.0 instead of 3.5
To get the ‘float’ value, the expression should be:
fResult = 7.0 / 2; or
fResult = 7 / 2.0; or
fResult = 7.0 / 2.0; or
fResult = (float) 7 / 2; or
fResult = 7 / (float) 2;
Precedence of Arithmetic Operators
Operator Priority
* , / and % Highest
+ and Lowest
Structured Programming
Rajesh Kulkarni
Control Structures: conditional constructs
if statement
if (expression) statement1
if (expression) statement1 else statement2
expression must have an integral type. Zero is false, nonzero is true.
Notes:
expression must be parenthesized
Examples
Examples
Which of the following code is preferred?why?
Examples
/* This program displays the absolute value of a number given by the user */
#include
int main()
{
double num;
printf("Please enter a real number: ");
scanf("%lf", &num);
if (num<0)
num = -num;
printf("The absolute value is %g\n", num);
return 0;
}
if-else statement
condition
True or false
In C, every expression has a numeric value
An expression is ‘true’ when its value is non-zero
If it is zero, it is false
Therefore, in the following –
if (expression) statement
statement is executed if expression is non zero.
More about operators
In C, every expression has a numeric value
When using arithmetical operators (+, -, *, /) this is straightforward
The value of A+B is the sum of A and B
And so on…
More about operators
Expressions with relational operators (<, <=, >, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’)
A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B
The exact non-zero value varies (and is not important for that matter)
Relational operators
They are:
A == B (Note the difference from A = B!!!!!)
A != B
A < B
A > B
A <= B
A >= B
The value of the expression is non-zero if it’s true, zero if it’s false
An example (fragment)
int first, second, min;
/* … */
if (first < second)
{
min = first;
printf ("The first number is smaller than the second.\n");
}
else
{
min = second;
printf ("The second number is smaller than the first\n");
}
printf("The smaller number is equal to %d\n", min);
An example
int a, b;
printf("Enter two numbers\n");
scanf("%d%d", &a, &b);
if (a == b)
{
printf("The numbers equal %d\n", a);
printf("The expression a == b is %d\n", a == b);
}
else
{
printf("The numbers are not equal\n");
printf("The expression a == b is %d\n", a == b);
}
The assignment operator =
The assignment operator is also an operator. Hence, expressions involving it have a numeric value.
This value equals to whatever appears on the right of the assignment operator
For example:
(x = 4) evaluates to 4
(y = 0) evaluates to 0
A very common mistake
Very often a programmer might confuse between the equality operator and the assignment operator:
if (x==4) …
if (x=4) …
The second is usually a mistake, but legal in C so the compiler doesn’t warn us about it!
Logical operators
Allows to evaluate two or more expressions -
!A – ‘not’ - True when A is not, and vice versa.
A && B – ‘and’ - True when both A and B are true
A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true
A silly example
#include
int main(void)
{
int grade;
printf("Please enter your grade: ");
scanf("%d", &grade);
if (grade < 0 || grade > 100)
printf("This is not a valid grade!\n");
else
printf("This is indeed a grade.\n");
return 0;
}
Example
main()
{ int x;
scanf(”%d”,&x);
if(x%2)
{
printf(“ the number %d is ODD\n”,x);
}
else
{
printf(“ the number %d is EVEN\n”,x);
}
}
Example
main()
{ int x,y;
x=10;y=20;
printf(“ %d%d are\n”,x,y);
x=x+y;
y=x-y;
x=x-y;
printf(“ %d%d are\n”,x,y);
}
Dangling else problem
if (exp1) if (exp2) stmta else stmtb
Avoiding the dangling else problem
Null statement
if (exp1)
if (exp2)
stmta
else
;
else
stmtb
else if statements
if statements distinguish between exactly 2 cases and execute different code in each case
The else-if construction allows for a multi-way decision
else if statements
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
An example
if (grade >= 90)
printf ("A\n");
else if (grade >= 80)
printf ("B\n");
else if (grade >= 70)
printf ("C\n");
else if (grade >= 60)
printf ("D\n");
else
printf ("F\n");
Validating input
When getting input from the user, it is highly recommended to check whether it is valid.
If it’s not, you should display an appropriate message and return a non-zero value.
For example –
if (grade < 0 || grade > 100)
{
printf(“Invalid input!\n”);
return 1;
}
The return keyword
For now, used to terminate the program and return a value to the operating system
If the program is successful the return value should be zero; non-zero otherwise
The exact nature of this keyword will become clear in the future
Exercise
Input –
An English letter
Output –
If input is a lowercase letter – the corresponding uppercase letter
If input is an uppercase letter - corresponding lowercase letter
Note –
Remember to check for input validity!
Exercise
Input
Two integers, A and B
Output
Their relation (i.e. displays A==B, AB)
Solution
#include
int main()
{
int A, B;
printf("Enter two Numbers\n");
scanf("%d%d", &A, &B);
if (A == B)
printf("A==B\n");
else if (A > B)
printf("A>B\n");
else
printf("A
return 0;
}
The switch statement
a multiway conditional statement
similar to if-else if-else
allows the selection of an arbitrary number
of choices based on an integer value
The switch statement
expression must have an integer value
when the switch statement is executed:
the expression is evaluated
if a case matches the value of the expression, the program jumps to the first statement after that case label
otherwise, the default case is selected
the default is optional
That grade example again
switch (grade/10) {
case 10:
case 9:
printf ("A\n");
break;
case 8:
printf ("B\n");
break;
case 7:
printf ("C\n");
break;
case 6:
printf ("D\n");
break;
default:
printf ("F\n");
}
Give me a break
when the switch transfers to the chosen case, it starts executing statements at that point
it will “fall through” to the next case unless you “break out”
break causes the program to immediately jump to the next statement after the switch statement
switch
switch (expression) {
case const-expr/: statements
case const-expr/: statements
default : statements
}
switch (digit)
{
case 0:
case 1:
case 2:
case 3:
case 4: printf (“Round down\n”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:printf(“Round up\n”);
}
Exercise
Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin
1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar
Remember to check for the validity of the input!
The ?: operator
expr1 ? expr2 : expr3
Nicer way to write:
(expr1)? expr2 : expr3
If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated
The ?: operator
#include
int main()
{
int i, j, min;
printf("Please enter two numbers: ");
scanf("%d%d", &i, &j);
min = (i < j)? i : j;
printf("The minimum between %d and %d is %d\n", i, j, min);
return 0;
}
Goto Statements
goto label;
………
……..
label : statements;
Goto Statements
Forward goto: if statement along with the label appear below the goto statement
Backward goto: if statement along with the label appear above the goto statement
Iteration Constructs
Iteration constructs repeat a sequence of code in a controlled manner.
while
for
do-while
while loop
while (expression)
statement
WASE FUNCTIONS 29-04-07
• Functions
• Function definition
• Calling function
• Global variables
• Function parameters
• Call by value
• Functions that return value
• Function prototype
• Assignment :- create a function that returns details of one cd.
/*
* double2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
return n1 * 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
printf("The doubled value is %d\n", double_it(num1));
fflush(stdin);
getchar();
}
/*
* double.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
n1 *= 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
double_it(num1);
printf("The doubled value is %d\n", num1);
fflush(stdin);
getchar();
}
/*
* average3.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average4.c
*
* Program to demonstrate the use of function prototypes
*
* by Rajesh Kulkarni
*/
#include
float average3(int n1, int n2, int n3);
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
printf("The average of 4, 3 and 5 is %f\n", average3(4, 3, 5));
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
float ave;
average3(int n1, int n2, int n3)
{
ave = (float)(n1 + n2 + n3) / 3;
}
main()
{
int num1, num2, num3;
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
average3(num1, num2, num3);
printf("The average is %f\n", ave);
fflush(stdin);
getchar();
}
/*
* average.c
*
* Program to demonstrate the use of global variables
*
* by Rajesh Kulkarni
*/
#include
int num1, num2, num3;
float ave;
input()
{
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
}
average()
{
ave = (float)(num1 + num2 + num3) / 3;
}
output()
{
printf("The average is %f\n", ave);
}
main()
{
input();
average();
output();
fflush(stdin);
getchar();
}
/*
* strlen.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int length;
strlength(char str[])
{
for (length = 0; str[length] != '\0'; length++)
; /* do nothing loop */
}
main()
{
char string[100];
printf("Please enter your first name: ");
scanf("%[^\n]", string);
strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
/*
* strlen2.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int strlength(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
; /* do nothing loop */
return i;
}
main()
{
char string[100];
int length;
printf("Please enter your first name: ");
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
printf("Please enter your last name: ");
fflush(stdin);
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
Functions
Class Test
on 7th February Thursday
5:30 to 6:30 pm
A Problem
Suppose we are writing a program that displays messages on the screen.
We want to display rows of =============================== to separate sections of output.
Solution
#include
int main (void)
{
/* produce some output */
/* print banner line */
printf(“==============\n”) ;
/* produce more output */
printf(“==============\n”);
/* produce even more output */
printf(“==============\n”);
/* produce final output */
}
Critique
Redundant code
What if we want to change the display
e.g. to print a blank line before and after each line with =’s ?
What if we want to print banner lines in some other program?
The Solution: Functions
Definition: A function is a named code sequence
A function can be executed by using its name as a statement or expression.
The function may have parameters - information that can be different each time the function is executed.
The function may compute and return a value.
Why use functions ?
Functions provide an abstraction when writing a program - allow low-level details to be packaged.
Able to package a computation we need to perform at multiple spots within a program.
Write once, use many times.
If changes are needed, they only have to be done once, in one place.
Why use functions ?
Allows the programmer to create a program from smaller, simpler sub-components.
Many programs are far too large to understand all at once.
Functions give us a way to break a large program into smaller pieces
A function should perform a well-defined task.
Common functions
int main (void)
{
. . .
}
More common functions
Every standard C compiler comes with a set of standard libraries.
#include
Tells the compiler you will use the standard IO library
#include
C’s standard math library functions:
sqrt, pow, sin, cos, exp, ...
isspace, ...
Defining your own functions
You may define your own functions in your programs
You define a function by giving its name and writing the code that is executed when the function is called.
High level programming structure
main ()
{
. . .
SetUpBoard ();
do {
redsTurn ();
blacksTurn ();
} while (gamenotover ());
}
Function definition
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
void
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
Calling a function
int main (void)
{
/* produce some output */
. . .
print_banner ();
/* produce more output */
. . .
print_banner ();
/* produce final output */
. . .
print_banner ();
}
Terminology
main () is the caller
print_banner() is the callee.
main() invokes / calls print_banner() 3 times.
print_banner() is called from main()
Function Control Flow
/* print banner line */
void print_banner (void)
{
printf(“**************\n”);
}
Control Flow
All C programs
Start at main () /*no matter where main()is */
Continue in top-to-bottom order, statement by statement, unless the order is changed by:
function call
function return
if
loops
Function Type and Value
A function can return a value.
Like all values in C, a function return value has a type.
The function has the type of its returned value.
Calling a function
A value-returning function is called by including it in an expression.
return
In a value-returning function (result type is not void) return does two distinct things :
1. specify the value returned by the execution of the function
2. terminate that execution of the function.
In a void function:
return is optional at the end of the function body.
return may also be used to terminate execution of the function explicitly.
No return value should appear following return.
void compute_and_print_itax ()
{
double income;
scanf (“%f”, &income);
if (income < 50000) {
printf (“Income tax = Nil\n”);
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000);
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
Function parameters
It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
The function specifies its inputs as parameters in the function declaration.
Arguments
The function call must include a matching argument for each parameter.
When the function is executed, the value of the argument is substituted for the parameter.
Functions
Lecture 10
Function parameters
It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
The function specifies its inputs as parameters in the function declaration.
Arguments
The function call must include a matching argument for each parameter.
When the function is executed, the value of the argument is substituted for the parameter.
Control and data flow
When a function is called:
(1) control transfers to the function body
(2) argument values are copied
(3) the function executes
(4) control and return value return to the point of call.
Control and data flow
int main (void)
{
double x, y, z;
y=6.0;
x = area(y/2.0);
. . .
z = area(7.88);
. . .
return (0);
}
Style notes
Put comments above a function body to specify completely what the function does, including the significance of all the parameters.
Multiple parameters
a function may have more than one parameter
arguments must match parameters in number, order and type.
Rules for using functions
Arguments must match parameters:
in number
in order
in type
A function can only return one value.
but it might contain more than one return statement.
In a function with return type T, the return expression must be of type T.
A function with return type T can be used anywhere an expression of type T can be used.
Local variables
A function can define its own local variables.
The locals have meaning only within the function.
Each execution of the function uses a new set of locals
Local variables cease to exist when the function returns
Parameters are also local.
Local variables
Defining function prototypes
Functions should be declared before they are used (invoked).
Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used.
It is a good programming style to use function prototypes.
Function prototypes
int operate (double x, double y, char op) ;
int operate (double, double, char);
void print_average (double, int);
int get_intput (void);
void print_banner (void);
Local Variables
Formal parameters and variables declared in a function are local to it.
cannot be accessed or used by other functions directly
Allocated (created) on function entry.
De-allocated (destroyed) on function return.
Formal parameters initialized by copying value of actual parameter. (“Call by value”)
Call by value
void printDouble (int x) {
printf (“Double of %d “, x);
x *= 2;
printf (“is %d\n”, x) ;
}
void main () {
int num=15;
printDouble (num);
printf (“ num = %d\n”, num);
}Functions
Functions
a group of declarations and statements that is assigned a name
effectively, a named statement block
usually has a value
a sub-program
when we write our program we always define a function named main
inside main we can call other functions
which can themselves use other functions, and so on…
Example - Square
#include
double square(double a)
{
return a*a;
}
int main(void)
{
double num;
printf("enter a number\n");
scanf("%lf",&num);
printf("square of %g is %g\n",num,square(num));
return 0;
}
Why use functions?
they can break your problem down into smaller sub-tasks
easier to solve complex problems
generalize a repeated set of instructions
we don’t have to keep writing the same thing over and over
printf and scanf are good examples…
they make a program much easier to read and maintain
Characteristics of Functions
return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …)
{
function body;
return value;
}
Return Statement
Return causes the execution of the function to terminate and returns a value to the calling function
The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)
In a function there may be any no of return statements but only one can be executed.
Return type is optional
Default return type is int
Exercise
Write a program that gets a positive integer from the user and prints all the prime numbers from 2 up to that integer.
(Use a function that returns 1 if its parameter is prime, 0 otherwise)
Solution
is_prime_func.c
The Great Void
Sometimes there’s no reason for a function to return a value
In these cases, the function return type should be ‘void’
If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified
The Great Void
Calling ‘return’ in a function returning void is not obligatory
If the function receives no parameters, the parameter list should be replaced by ‘void’ (or just nothing)
Example
void ShowHelp(void)
{
printf("This function explains what this program does…\n");
printf("Yadayadayada");
/* ... */
}
int main(void)
{
char choice;
printf("Please enter your selection: ");
scanf("%c", &choice);
if (choice==‘h’)
ShowHelp();
else if /* Program continues … */
}
Calling function: a function which is referring another function is called calling function
Called function: a function which is referenced by another function is called called function.
Function call:
Actual parameters:
Formal parameters;
Pass-by-value
Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables
A change to the value of an argument in a function body will not change the value of variables in the calling function
Example – add_one.c
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Riddle me this
#include
int factorial(int n)
{
int fact = 1;
while (n>1)
{
fact *= n;
n--;
}
return fact;
}
Scope of variables
A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name
A function cannot access variables that are declared in other functions
Example – scope.c
Call –by- Reference
Wrong way to do it
int add_one(int b)
{
a=b+1;
}
int main(void)
{
int a=34,b=1;
add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Function Declaration
Most software projects in C are composed of more than one file
We want to be able to define the function in one file, and to use it in all files
Function Declaration
For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time
the declaration contains:
Function Declaration
#include
int factorial(int a); /* Function Declaration! */
int main(void){
int num;
printf("enter a number\n");
scanf("%d", &num);
printf("%d != %d\n", num, factorial(num));
return 0;
}
int factorial(int a){
int i, b = 1;
for(i = 1; I <= a; i++)
b = b*i;
return b;
}
Function Declaration
stdio.h actually contains a large set of function declarations
The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called
The math library
A collection of mathematical functions
Need to include the header file math.h (#include)
Use functions of the library, e.g.
double s,p;
s = sqrt(p);
Declared in math.h :
double sqrt (double x);
The math library
sin(x), cos(x), tan(x)
x is given in radians
asin(x), acos(x), atan(x)
log(x)
sqrt(x)
pow(x,y) – raise x to the yth power.
ceil(x), floor(x) …and more
Exercise
Write a function that uses the formula
in order to approximate . The function should accept
an argument n which determines the number of terms in
the formula. It should return the approximation of .
Write a program that gets an integer n from the user,
and approximate using n terms of the above formula.
Solution
pi.c
Exercise
Modify the previous function that approximates
. The function should accept an argument
specifying the desired accuracy, and keep
adding terms until the contribution of the next
term drops below this level.
Write a program that gets a (small) double
epsilon from the user, and approximates
within this function.
Solution
pi_eps.c
The debugger
Some programs may compile correctly, yet not produce the desirable results.
These programs are valid and correct C programs, yet not the programs we meant to write!
The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program.
The debugger’s common features
Setting breakpoints (a point where the execution stops): bring the cursor to desired line and press the palm icon or F9. A dark red dot appears near the line.
Executing a debugged run: Build->start debug->go or F5. The program will run and stop at the first breakpoint.
The debugger’s common features (cont.)
Stopping at a specific line: Bringing the cursor to the line and press ctrl+F10, or Build->start debug->go to cursor. The program will stop at that point.
Stepping to the next line – F10.
Entering a function – F11.
Seeing variable values – quickwatch and/or debug window at the bottom.
The yellow arrow indicates our whereabouts at any given moment.
• Function definition
• Calling function
• Global variables
• Function parameters
• Call by value
• Functions that return value
• Function prototype
• Assignment :- create a function that returns details of one cd.
/*
* double2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
return n1 * 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
printf("The doubled value is %d\n", double_it(num1));
fflush(stdin);
getchar();
}
/*
* double.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
double_it(int n1)
{
n1 *= 2;
}
main()
{
int num1;
printf("Please enter the number: ");
scanf("%d", &num1);
double_it(num1);
printf("The doubled value is %d\n", num1);
fflush(stdin);
getchar();
}
/*
* average3.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average4.c
*
* Program to demonstrate the use of function prototypes
*
* by Rajesh Kulkarni
*/
#include
float average3(int n1, int n2, int n3);
input(int sequence)
{
int num;
char position[10];
switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}
printf("Please enter the %s number: ", position);
scanf("%d", &num);
printf("The average of 4, 3 and 5 is %f\n", average3(4, 3, 5));
return num;
}
float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}
output(float a)
{
printf("The average is %f\n", a);
}
main()
{
int num1, num2, num3;
float ave;
num1 = input(1);
num2 = input(2);
num3 = input(3);
ave = average3(num1, num2, num3);
output(ave);
fflush(stdin);
getchar();
}
/*
* average2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include
float ave;
average3(int n1, int n2, int n3)
{
ave = (float)(n1 + n2 + n3) / 3;
}
main()
{
int num1, num2, num3;
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
average3(num1, num2, num3);
printf("The average is %f\n", ave);
fflush(stdin);
getchar();
}
/*
* average.c
*
* Program to demonstrate the use of global variables
*
* by Rajesh Kulkarni
*/
#include
int num1, num2, num3;
float ave;
input()
{
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
}
average()
{
ave = (float)(num1 + num2 + num3) / 3;
}
output()
{
printf("The average is %f\n", ave);
}
main()
{
input();
average();
output();
fflush(stdin);
getchar();
}
/*
* strlen.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int length;
strlength(char str[])
{
for (length = 0; str[length] != '\0'; length++)
; /* do nothing loop */
}
main()
{
char string[100];
printf("Please enter your first name: ");
scanf("%[^\n]", string);
strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
/*
* strlen2.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include
int strlength(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
; /* do nothing loop */
return i;
}
main()
{
char string[100];
int length;
printf("Please enter your first name: ");
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
printf("Please enter your last name: ");
fflush(stdin);
scanf("%[^\n]", string);
length = strlength(string);
printf("Length of >>%s<< is %d\n", string, length);
fflush(stdin);
getchar();
}
Functions
Class Test
on 7th February Thursday
5:30 to 6:30 pm
A Problem
Suppose we are writing a program that displays messages on the screen.
We want to display rows of =============================== to separate sections of output.
Solution
#include
int main (void)
{
/* produce some output */
/* print banner line */
printf(“==============\n”) ;
/* produce more output */
printf(“==============\n”);
/* produce even more output */
printf(“==============\n”);
/* produce final output */
}
Critique
Redundant code
What if we want to change the display
e.g. to print a blank line before and after each line with =’s ?
What if we want to print banner lines in some other program?
The Solution: Functions
Definition: A function is a named code sequence
A function can be executed by using its name as a statement or expression.
The function may have parameters - information that can be different each time the function is executed.
The function may compute and return a value.
Why use functions ?
Functions provide an abstraction when writing a program - allow low-level details to be packaged.
Able to package a computation we need to perform at multiple spots within a program.
Write once, use many times.
If changes are needed, they only have to be done once, in one place.
Why use functions ?
Allows the programmer to create a program from smaller, simpler sub-components.
Many programs are far too large to understand all at once.
Functions give us a way to break a large program into smaller pieces
A function should perform a well-defined task.
Common functions
int main (void)
{
. . .
}
More common functions
Every standard C compiler comes with a set of standard libraries.
#include
Tells the compiler you will use the standard IO library
#include
C’s standard math library functions:
sqrt, pow, sin, cos, exp, ...
isspace, ...
Defining your own functions
You may define your own functions in your programs
You define a function by giving its name and writing the code that is executed when the function is called.
High level programming structure
main ()
{
. . .
SetUpBoard ();
do {
redsTurn ();
blacksTurn ();
} while (gamenotover ());
}
Function definition
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
void
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
Calling a function
int main (void)
{
/* produce some output */
. . .
print_banner ();
/* produce more output */
. . .
print_banner ();
/* produce final output */
. . .
print_banner ();
}
Terminology
main () is the caller
print_banner() is the callee.
main() invokes / calls print_banner() 3 times.
print_banner() is called from main()
Function Control Flow
/* print banner line */
void print_banner (void)
{
printf(“**************\n”);
}
Control Flow
All C programs
Start at main () /*no matter where main()is */
Continue in top-to-bottom order, statement by statement, unless the order is changed by:
function call
function return
if
loops
Function Type and Value
A function can return a value.
Like all values in C, a function return value has a type.
The function has the type of its returned value.
Calling a function
A value-returning function is called by including it in an expression.
return
In a value-returning function (result type is not void) return does two distinct things :
1. specify the value returned by the execution of the function
2. terminate that execution of the function.
In a void function:
return is optional at the end of the function body.
return may also be used to terminate execution of the function explicitly.
No return value should appear following return.
void compute_and_print_itax ()
{
double income;
scanf (“%f”, &income);
if (income < 50000) {
printf (“Income tax = Nil\n”);
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000);
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
Function parameters
It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
The function specifies its inputs as parameters in the function declaration.
Arguments
The function call must include a matching argument for each parameter.
When the function is executed, the value of the argument is substituted for the parameter.
Functions
Lecture 10
Function parameters
It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
The function specifies its inputs as parameters in the function declaration.
Arguments
The function call must include a matching argument for each parameter.
When the function is executed, the value of the argument is substituted for the parameter.
Control and data flow
When a function is called:
(1) control transfers to the function body
(2) argument values are copied
(3) the function executes
(4) control and return value return to the point of call.
Control and data flow
int main (void)
{
double x, y, z;
y=6.0;
x = area(y/2.0);
. . .
z = area(7.88);
. . .
return (0);
}
Style notes
Put comments above a function body to specify completely what the function does, including the significance of all the parameters.
Multiple parameters
a function may have more than one parameter
arguments must match parameters in number, order and type.
Rules for using functions
Arguments must match parameters:
in number
in order
in type
A function can only return one value.
but it might contain more than one return statement.
In a function with return type T, the return expression must be of type T.
A function with return type T can be used anywhere an expression of type T can be used.
Local variables
A function can define its own local variables.
The locals have meaning only within the function.
Each execution of the function uses a new set of locals
Local variables cease to exist when the function returns
Parameters are also local.
Local variables
Defining function prototypes
Functions should be declared before they are used (invoked).
Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used.
It is a good programming style to use function prototypes.
Function prototypes
int operate (double x, double y, char op) ;
int operate (double, double, char);
void print_average (double, int);
int get_intput (void);
void print_banner (void);
Local Variables
Formal parameters and variables declared in a function are local to it.
cannot be accessed or used by other functions directly
Allocated (created) on function entry.
De-allocated (destroyed) on function return.
Formal parameters initialized by copying value of actual parameter. (“Call by value”)
Call by value
void printDouble (int x) {
printf (“Double of %d “, x);
x *= 2;
printf (“is %d\n”, x) ;
}
void main () {
int num=15;
printDouble (num);
printf (“ num = %d\n”, num);
}Functions
Functions
a group of declarations and statements that is assigned a name
effectively, a named statement block
usually has a value
a sub-program
when we write our program we always define a function named main
inside main we can call other functions
which can themselves use other functions, and so on…
Example - Square
#include
double square(double a)
{
return a*a;
}
int main(void)
{
double num;
printf("enter a number\n");
scanf("%lf",&num);
printf("square of %g is %g\n",num,square(num));
return 0;
}
Why use functions?
they can break your problem down into smaller sub-tasks
easier to solve complex problems
generalize a repeated set of instructions
we don’t have to keep writing the same thing over and over
printf and scanf are good examples…
they make a program much easier to read and maintain
Characteristics of Functions
return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …)
{
function body;
return value;
}
Return Statement
Return causes the execution of the function to terminate and returns a value to the calling function
The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)
In a function there may be any no of return statements but only one can be executed.
Return type is optional
Default return type is int
Exercise
Write a program that gets a positive integer from the user and prints all the prime numbers from 2 up to that integer.
(Use a function that returns 1 if its parameter is prime, 0 otherwise)
Solution
is_prime_func.c
The Great Void
Sometimes there’s no reason for a function to return a value
In these cases, the function return type should be ‘void’
If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified
The Great Void
Calling ‘return’ in a function returning void is not obligatory
If the function receives no parameters, the parameter list should be replaced by ‘void’ (or just nothing)
Example
void ShowHelp(void)
{
printf("This function explains what this program does…\n");
printf("Yadayadayada");
/* ... */
}
int main(void)
{
char choice;
printf("Please enter your selection: ");
scanf("%c", &choice);
if (choice==‘h’)
ShowHelp();
else if /* Program continues … */
}
Calling function: a function which is referring another function is called calling function
Called function: a function which is referenced by another function is called called function.
Function call:
Actual parameters:
Formal parameters;
Pass-by-value
Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables
A change to the value of an argument in a function body will not change the value of variables in the calling function
Example – add_one.c
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}
int main(void)
{
int a=34,b=1;
a = add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Riddle me this
#include
int factorial(int n)
{
int fact = 1;
while (n>1)
{
fact *= n;
n--;
}
return fact;
}
Scope of variables
A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name
A function cannot access variables that are declared in other functions
Example – scope.c
Call –by- Reference
Wrong way to do it
int add_one(int b)
{
a=b+1;
}
int main(void)
{
int a=34,b=1;
add_one(b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Function Declaration
Most software projects in C are composed of more than one file
We want to be able to define the function in one file, and to use it in all files
Function Declaration
For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time
the declaration contains:
Function Declaration
#include
int factorial(int a); /* Function Declaration! */
int main(void){
int num;
printf("enter a number\n");
scanf("%d", &num);
printf("%d != %d\n", num, factorial(num));
return 0;
}
int factorial(int a){
int i, b = 1;
for(i = 1; I <= a; i++)
b = b*i;
return b;
}
Function Declaration
stdio.h actually contains a large set of function declarations
The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called
The math library
A collection of mathematical functions
Need to include the header file math.h (#include
Use functions of the library, e.g.
double s,p;
s = sqrt(p);
Declared in math.h :
double sqrt (double x);
The math library
sin(x), cos(x), tan(x)
x is given in radians
asin(x), acos(x), atan(x)
log(x)
sqrt(x)
pow(x,y) – raise x to the yth power.
ceil(x), floor(x) …and more
Exercise
Write a function that uses the formula
in order to approximate . The function should accept
an argument n which determines the number of terms in
the formula. It should return the approximation of .
Write a program that gets an integer n from the user,
and approximate using n terms of the above formula.
Solution
pi.c
Exercise
Modify the previous function that approximates
. The function should accept an argument
specifying the desired accuracy, and keep
adding terms until the contribution of the next
term drops below this level.
Write a program that gets a (small) double
epsilon from the user, and approximates
within this function.
Solution
pi_eps.c
The debugger
Some programs may compile correctly, yet not produce the desirable results.
These programs are valid and correct C programs, yet not the programs we meant to write!
The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program.
The debugger’s common features
Setting breakpoints (a point where the execution stops): bring the cursor to desired line and press the palm icon or F9. A dark red dot appears near the line.
Executing a debugged run: Build->start debug->go or F5. The program will run and stop at the first breakpoint.
The debugger’s common features (cont.)
Stopping at a specific line: Bringing the cursor to the line and press ctrl+F10, or Build->start debug->go to cursor. The program will stop at that point.
Stepping to the next line – F10.
Entering a function – F11.
Seeing variable values – quickwatch and/or debug window at the bottom.
The yellow arrow indicates our whereabouts at any given moment.
Subscribe to:
Posts (Atom)