Audience: III Year II sem engg. students + MCA II year Student
Jayaprakash narayan College of Engg. Mahboobnagar
Jpnce, 20-12-2007
CS05158: Data Warehousing and Mining
Lecture 1
• Course syllabus
• Overview of data warehousing and mining
Lecture slides modified from:
– Jiawei Han (http://www-sal.cs.uiuc.edu/~hanj/DM_Book.html)
– Vipin Kumar (http://www-users.cs.umn.edu/~kumar/csci5980/index.html)
– Ad Feelders (http://www.cs.uu.nl/docs/vakken/adm/)
– Zdravko Markov (http://www.cs.ccsu.edu/~markov/ccsu_courses/DataMining-1.html)
Rajesh Kulkarni
rrkpv2002@gmail.com
http://rkstechnofusion.blogspot.com
http://children-off-lesser-gods.blogspot.com
Course Syllabus
Textbook:
(required) J. Han, M. Kamber, Data Mining: Concepts and Techniques, 2001.
Data Mining Techniques by Arun K Pujari.
Datawarehousing in the Real World S Anahorey and D Murray
Topics: Unit 1
– Overview of data warehousing and mining
– Data Mining Functionalities
– Classification of Data Mining Systems
– Major Issues in Data Mining
– Data warehouse and OLAP technology for data mining
Motivation:
“Necessity is the Mother of Invention”
• Data explosion problem
– Automated data collection tools and mature database technology lead to tremendous amounts of data stored in databases, data warehouses and other information repositories
• We are drowning in data, but starving for knowledge!
• Solution: Data warehousing and data mining
– Data warehousing and on-line analytical processing
– Extraction of interesting knowledge (rules, regularities, patterns, constraints) from data in large databases
Why Mine Data? Commercial Viewpoint
• Lots of data is being collected
and warehoused
– Web data, e-commerce
– purchases at department/
grocery stores
– Bank/Credit Card
transactions
• Computers have become cheaper and more powerful
• Competitive Pressure is Strong
– Provide better, customized services for an edge (e.g. in Customer Relationship Management)
Why Mine Data? Scientific Viewpoint
• Data collected and stored at
enormous speeds (GB/hour)
– remote sensors on a satellite
– telescopes scanning the skies
– microarrays generating gene
expression data
– scientific simulations
generating terabytes of data
• Traditional techniques infeasible for raw data
• Data mining may help scientists
– in classifying and segmenting data
– in Hypothesis Formation
What Is Data Mining?
• Data mining (knowledge discovery in databases):
– Extraction of interesting (non-trivial, implicit, previously unknown and potentially useful) information or patterns from data in large databases
• Alternative names and their “inside stories”:
– Data mining: a misnomer?
– Knowledge discovery(mining) in databases (KDD), knowledge extraction, data/pattern analysis, data archeology, business intelligence, etc.
Examples: What is (not) Data Mining?
Data Mining: Classification Schemes
• Decisions in data mining
– Kinds of databases to be mined
– Kinds of knowledge to be discovered
– Kinds of techniques utilized
– Kinds of applications adapted
• Data mining tasks
– Descriptive data mining
– Predictive data mining
Decisions in Data Mining
• Databases to be mined
– Relational, transactional, object-oriented, object-relational, active, spatial, time-series, text, multi-media, heterogeneous, legacy, WWW, etc.
• Knowledge to be mined
– Characterization, discrimination, association, classification, clustering, trend, deviation and outlier analysis, etc.
– Multiple/integrated functions and mining at multiple levels
• Techniques utilized
– Database-oriented, data warehouse (OLAP), machine learning, statistics, visualization, neural network, etc.
• Applications adapted
– Retail, telecommunication, banking, fraud analysis, DNA mining, stock market analysis, Web mining, Weblog analysis, etc.
Data Mining Tasks
• Prediction Tasks
– Use some variables to predict unknown or future values of other variables
• Description Tasks
– Find human-interpretable patterns that describe the data.
Common data mining tasks
– Classification [Predictive]
– Clustering [Descriptive]
– Association Rule Discovery [Descriptive]
– Sequential Pattern Discovery [Descriptive]
– Regression [Predictive]
– Deviation Detection [Predictive]
Classification: Definition
• Given a collection of records (training set )
– Each record contains a set of attributes, one of the attributes is the class.
• Find a model for class attribute as a function of the values of other attributes.
• Goal: previously unseen records should be assigned a class as accurately as possible.
– A test set is used to determine the accuracy of the model. Usually, the given data set is divided into training and test sets, with training set used to build the model and test set used to validate it.
Classification Example
Classification: Application 1
• Direct Marketing
– Goal: Reduce cost of mailing by targeting a set of consumers likely to buy a new cell-phone product.
– Approach:
• Use the data for a similar product introduced before.
• We know which customers decided to buy and which decided otherwise. This {buy, don’t buy} decision forms the class attribute.
• Collect various demographic, lifestyle, and company-interaction related information about all such customers.
– Type of business, where they stay, how much they earn, etc.
• Use this information as input attributes to learn a classifier model.
Classification: Application 2
• Fraud Detection
– Goal: Predict fraudulent cases in credit card transactions.
– Approach:
• Use credit card transactions and the information on its account-holder as attributes.
– When does a customer buy, what does he buy, how often he pays on time, etc
• Label past transactions as fraud or fair transactions. This forms the class attribute.
• Learn a model for the class of the transactions.
• Use this model to detect fraud by observing credit card transactions on an account.
Classification: Application 3
• Customer Attrition/Churn:
– Goal: To predict whether a customer is likely to be lost to a competitor.
– Approach:
• Use detailed record of transactions with each of the past and present customers, to find attributes.
– How often the customer calls, where he calls, what time-of-the day he calls most, his financial status, marital status, etc.
• Label the customers as loyal or disloyal.
• Find a model for loyalty.
Classification: Application 4
• Sky Survey Cataloging
– Goal: To predict class (star or galaxy) of sky objects, especially visually faint ones, based on the telescopic survey images (from Palomar Observatory).
– 3000 images with 23,040 x 23,040 pixels per image.
– Approach:
• Segment the image.
• Measure image attributes (features) - 40 of them per object.
• Model the class based on these features.
• Success Story: Could find 16 new high red-shift quasars, some of the farthest objects that are difficult to find!
Classifying Galaxies
Clustering Definition
• Given a set of data points, each having a set of attributes, and a similarity measure among them, find clusters such that
– Data points in one cluster are more similar to one another.
– Data points in separate clusters are less similar to one another.
• Similarity Measures:
– Euclidean Distance if attributes are continuous.
– Other Problem-specific Measures.
Illustrating Clustering
Clustering: Application 1
• Market Segmentation:
– Goal: subdivide a market into distinct subsets of customers where any subset may conceivably be selected as a market target to be reached with a distinct marketing mix.
– Approach:
• Collect different attributes of customers based on their geographical and lifestyle related information.
• Find clusters of similar customers.
• Measure the clustering quality by observing buying patterns of customers in same cluster vs. those from different clusters.
Clustering: Application 2
• Document Clustering:
– Goal: To find groups of documents that are similar to each other based on the important terms appearing in them.
– Approach: To identify frequently occurring terms in each document. Form a similarity measure based on the frequencies of different terms. Use it to cluster.
– Gain: Information Retrieval can utilize the clusters to relate a new document or search term to clustered documents.
Association Rule Discovery: Definition
• Given a set of records each of which contain some number of items from a given collection;
– Produce dependency rules which will predict occurrence of an item based on occurrences of other items.
Association Rule Discovery: Application 1
• Marketing and Sales Promotion:
– Let the rule discovered be
{Bagels, … } --> {Potato Chips}
– Potato Chips as consequent => Can be used to determine what should be done to boost its sales.
– Bagels in the antecedent => Can be used to see which products would be affected if the store discontinues selling bagels.
– Bagels in antecedent and Potato chips in consequent => Can be used to see what products should be sold with Bagels to promote sale of Potato chips!
Association Rule Discovery: Application 2
• Supermarket shelf management.
– Goal: To identify items that are bought together by sufficiently many customers.
– Approach: Process the point-of-sale data collected with barcode scanners to find dependencies among items.
– A classic rule --
• If a customer buys diaper and milk, then he is very likely to buy beer:
The Sad Truth About Diapers and Beer
• So, don’t be surprised if you find six-packs stacked next to diapers!
Sequential Pattern Discovery: Definition
Given is a set of objects, with each object associated with its own timeline of events, find rules that predict strong sequential dependencies among different events:
– In telecommunications alarm logs,
• (Inverter_Problem Excessive_Line_Current)
(Rectifier_Alarm) --> (Fire_Alarm)
– In point-of-sale transaction sequences,
• Computer Bookstore:
(Intro_To_Visual_C) (C++_Primer) --> (Perl_for_dummies,Tcl_Tk)
• Athletic Apparel Store:
(Shoes) (Racket, Racketball) --> (Sports_Jacket)
Regression
• Predict a value of a given continuous valued variable based on the values of other variables, assuming a linear or nonlinear model of dependency.
• Greatly studied in statistics, neural network fields.
• Examples:
– Predicting sales amounts of new product based on advetising expenditure.
– Predicting wind velocities as a function of temperature, humidity, air pressure, etc.
– Time series prediction of stock market indices.
Deviation/Anomaly Detection
• Detect significant deviations from normal behavior
• Applications:
– Credit Card Fraud Detection
– Network Intrusion
Detection
Data Mining and Induction Principle
Induction vs Deduction
• Deductive reasoning is truth-preserving:
– All horses are mammals
– All mammals have lungs
– Therefore, all horses have lungs
• Induction reasoning adds information:
– All horses observed so far have lungs.
– Therefore, all horses have lungs.
The Problems with Induction
From true facts, we may induce false models.
Prototypical example:
– European swans are all white.
– Induce: ”Swans are white” as a general rule.
– Discover Australia and black Swans...
– Problem: the set of examples is not random and representative
Another example: distinguish US tanks from Iraqi tanks
– Method: Database of pictures split in train set and test set; Classification model built on train set
– Result: Good predictive accuracy on test set;Bad score on independent pictures
– Why did it go wrong: other distinguishing features in the pictures (hangar versus desert)
Hypothesis-Based vs. Exploratory-Based
• The hypothesis-based method:
– Formulate a hypothesis of interest.
– Design an experiment that will yield data to test this hypothesis.
– Accept or reject hypothesis depending on the outcome.
• Exploratory-based method:
– Try to make sense of a bunch of data without an a priori hypothesis!
– The only prevention against false results is significance:
• ensure statistical significance (using train and test etc.)
• ensure domain significance (i.e., make sure that the results make sense to a domain expert)
Hypothesis-Based vs. Exploratory-Based
• Experimental Scientist:
– Assign level of fertilizer randomly to plot of land.
– Control for: quality of soil, amount of sunlight,...
– Compare mean yield of fertilized and unfertilized plots.
• Data Miner:
– Notices that the yield is somewhat higher under trees where birds roost.
– Conclusion: droppings increase yield.
– Alternative conclusion: moderate amount of shade increases yield.(“Identification Problem”)
Data Mining: A KDD Process
– Data mining: the core of knowledge discovery process.
Steps of a KDD Process
• Learning the application domain:
– relevant prior knowledge and goals of application
• Creating a target data set: data selection
• Data cleaning and preprocessing: (may take 60% of effort!)
• Data reduction and transformation:
– Find useful features, dimensionality/variable reduction, invariant representation.
• Choosing functions of data mining
– summarization, classification, regression, association, clustering.
• Choosing the mining algorithm(s)
• Data mining: search for patterns of interest
• Pattern evaluation and knowledge presentation
– visualization, transformation, removing redundant patterns, etc.
• Use of discovered knowledge
Data Mining and Business Intelligence
Data Mining: On What Kind of Data?
• Relational databases
• Data warehouses
• Transactional databases
• Advanced DB and information repositories
– Object-oriented and object-relational databases
– Spatial databases
– Time-series data and temporal data
– Text databases and multimedia databases
– Heterogeneous and legacy databases
– WWW
Data Mining: Confluence of Multiple Disciplines
Data Mining vs. Statistical Analysis
Statistical Analysis:
• Ill-suited for Nominal and Structured Data Types
• Completely data driven - incorporation of domain knowledge not possible
• Interpretation of results is difficult and daunting
• Requires expert user guidance
Data Mining:
• Large Data sets
• Efficiency of Algorithms is important
• Scalability of Algorithms is important
• Real World Data
• Lots of Missing Values
• Pre-existing data - not user generated
• Data not static - prone to updates
• Efficient methods for data retrieval available for use
Data Mining vs. DBMS
• Example DBMS Reports
– Last months sales for each service type
– Sales per service grouped by customer sex or age bracket
– List of customers who lapsed their policy
• Questions answered using Data Mining
– What characteristics do customers that lapse their policy have in common and how do they differ from customers who renew their policy?
– Which motor insurance policy holders would be potential customers for my House Content Insurance policy?
Data Mining and Data Warehousing
• Data Warehouse: a centralized data repository which can be queried for business benefit.
• Data Warehousing makes it possible to
– extract archived operational data
– overcome inconsistencies between different legacy data formats
– integrate data throughout an enterprise, regardless of location, format, or communication requirements
– incorporate additional or expert information
• OLAP: On-line Analytical Processing
• Multi-Dimensional Data Model (Data Cube)
• Operations:
– Roll-up
– Drill-down
– Slice and dice
– Rotate
DBMS, OLAP, and Data Mining
Example of DBMS, OLAP and Data Mining: Weather Data
Example of DBMS, OLAP and Data Mining: Weather Data
• By querying a DBMS containing the above table we may answer questions like:
• What was the temperature in the sunny days? {85, 80, 72, 69, 75}
• Which days the humidity was less than 75? {6, 7, 9, 11}
• Which days the temperature was greater than 70? {1, 2, 3, 8, 10, 11, 12, 13, 14}
• Which days the temperature was greater than 70 and the humidity was less than 75? The intersection of the above two: {11}
Example of DBMS, OLAP and Data Mining: Weather Data
OLAP:
• Using OLAP we can create a Multidimensional Model of our data (Data Cube).
• For example using the dimensions: time, outlook and play we can create the following model.
Major Issues in Data Warehousing and Mining
• Mining methodology and user interaction
– Mining different kinds of knowledge in databases
– Interactive mining of knowledge at multiple levels of abstraction
– Incorporation of background knowledge
– Data mining query languages and ad-hoc data mining
– Expression and visualization of data mining results
– Handling noise and incomplete data
– Pattern evaluation: the interestingness problem
• Performance and scalability
– Efficiency and scalability of data mining algorithms
– Parallel, distributed and incremental mining methods
Major Issues in Data Warehousing and Mining
• Issues relating to the diversity of data types
– Handling relational and complex types of data
– Mining information from heterogeneous databases and global information systems (WWW)
• Issues related to applications and social impacts
– Application of discovered knowledge
• Domain-specific data mining tools
• Intelligent query answering
• Process control and decision making
– Integration of the discovered knowledge with existing knowledge: A knowledge fusion problem
– Protection of data security, integrity, and privacy
Sunday, January 6, 2008
Thursday, November 15, 2007
tcp/ip overview 14th nov' 2007
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.
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.
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
Subscribe to:
Posts (Atom)