It Content HTML
It Content HTML
What is HTML
HTML is an acronym which stands for Hyper Text Markup Language which is used for creating web
pages and web applications. Let's see what is meant by Hypertext Markup Language, and Web page.
Hyper Text: HyperText simply means "Text within Text." A text has a link within it, is a hypertext. Whenever
you click on a link which brings you to a new webpage, you have clicked on a hypertext. HyperText is a way to
link two or more web pages (HTML documents) with each other.
Markup language: A markup language is a computer language that is used to apply layout and formatting
conventions to a text document. Markup language makes text more interactive and dynamic. It can turn text into
images, tables, links, etc.
Web Page: A web page is a document which is commonly written in HTML and translated by a web browser. A
web page can be identified by entering an URL. A Web page can be of the static or dynamic type. With the help
of HTML only, we can create static web pages.
Hence, HTML is a markup language which is used for creating attractive web pages with the help of styling, and
which looks in a nice format on a web browser. An HTML document is made of many HTML tags and each
HTML tag contains different content.
Description of HTML Example
<!DOCTYPE>: It defines the document type or it instruct the browser about the version of HTML.
<html >: This tag informs the browser that it is an HTML document. Text between html tag describes the web
document. It is a container for all other elements of HTML except <!DOCTYPE>
<head>: It should be the first element inside the <html> element, which contains the metadata (information
about the document). It must be closed before the body tag opens.
<title>: As its name suggested, it is used to add title of that HTML page which appears at the top of the browser
window. It must be placed inside the head tag and should close immediately. (Optional)
<body>: Text between body tag describes the body content of the page that is visible to the end user. This tag
contains the main content of the HTML document.
<h1>: Text between <h1> tag describes the first level heading of the webpage.
<p>: Text between <p> tag describes the paragraph of the webpage.
Brief History of HTML
In the late 1980's, a physicist, Tim Berners-Lee who was a contractor at CERN, proposed a system for CERN
researchers. In 1989, he wrote a memo proposing an internet based hypertext system.
Tim Berners-Lee is known as the father of HTML. The first available description of HTML was a document
called "HTML Tags" proposed by Tim in late 1991. The latest version of HTML is HTML5, which we will learn
later in this tutorial.
Features of HTML
1) It is a very easy and simple language. It can be easily understood and modified.
2) It is very easy to make an effective presentation with HTML because it has a lot of formatting tags.
3) It is a markup language, so it provides a flexible way to design web pages along with the text.
4) It facilitates programmers to add a link on the web pages (by html anchor tag), so it enhances the interest of
browsing of the user.
5) It is platform-independent because it can be displayed on any platform like Windows, Linux, and Macintosh,
etc.
6) It facilitates the programmer to add Graphics, Videos, and Sound to the web pages which makes it more
attractive and interactive.
7) HTML is a case-insensitive language, which means we can use tags either in lower-case or upper-case.
NOTE: It is recommended to write all tags in lower-case for consistency, readability, etc.
HTML text Editors
o An HTML file is a text file, so to create an HTML file we can use any text editors.
o Text editors are the programs which allow editing in a written text, hence to create a web page we need
to write our code in some text editor.
o There are various types of text editors available which you can directly download, but for a beginner, the
best text editor is Notepad (Windows) or TextEdit (Mac).
o After learning the basics, you can easily use other professional text editors which are, Notepad++,
Sublime Text, Vim, etc.
Notepad is a simple text editor and suitable for beginners to learn HTML. It is available in all versions of
Windows, from where you easily access it.
Step 1: Open Notepad (Windows)
Step 2: Write code in HTML
Output:
The HTML <em> tag is a logical element, which will display the enclosed content in italic font, with added
semantics importance.
See this example:
Output:
Output:
4) Underlined Text
If you write anything within <u>.........</u> element, is shown in underlined text.
See this example:
Output:
5) Strike Text
Anything written within <strike>.......................</strike> element is displayed with strikethrough. It is a thin line
which cross the statement.
See this example:
Output:
6) Monospaced Font
If you want that each letter has the same width, then you should write the content within <tt>.............</tt>
element.
Note: We know that most of the fonts are known as variable-width fonts because different letters have different
width. (for example: 'w' is wider than 'i'). Monospaced Font provides similar space among every letter.
See this example:
Output:
7) Superscript Text
If you put the content within <sup>..............</sup> element, is shown in superscript; means it is displayed half a
character's height above the other characters.
See this example:
Output:
8) Subscript Text
If you put the content within <sub>..............</sub> element, is shown in subscript ; means it is displayed half a
character's height below the other characters.
See this example:
Output:
9) Deleted Text
Anything that puts within <del>..........</del> is displayed as deleted text.
See this example:
<!DOCTYPE>
<html>
<body>
<p>Hello <del>Delete your first paragraph</del></p>
</body>
</html>
Output:
Hello Delete your first paragraph.
10) Inserted Text
Anything that puts within <ins>..........</ins> is displayed as inserted text.
See this example:
Output:
Output:
Output:
A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to display on the
webpage. When you place the text within the heading tags <h1>.........</h1>, it is displayed on the browser in the
bold format and size of the text depends on the number of heading.
There are six different HTML headings which are defined with the <h1> to <h6> tags, from highest level h1
(main heading) to the least level h6 (least important heading).
h1 is the largest heading tag and h6 is the smallest one. So h1 is used for most important heading and h6 is used
for least important.
Headings in HTML helps the search engine to understand and index the structure of web page.
Note: The main keyword of the whole content of a webpage should be display by h1 heading tag.
Heading elements (h1....h6) should be used for headings only. They should not be used just to make text bold or
big.
Module 2 – Attributes, Colors, Hyperlinks
HTML Attribute
o HTML attributes are special words which provide additional information about the elements or attributes
are the modifier of the HTML element.
o Each element or tag can have attributes, which defines the behavior of that element.
o Attributes should always be applied with start tag.
o The Attribute should always be applied with its name and value pair.
o The Attributes name and values are case sensitive, and it is recommended by W3C that it should be
written in Lowercase only.
o You can add multiple attributes in one HTML element, but need to give space between two attributes.
Syntax
Example
In the above statement, we have used paragraph tags in which we have applied style attribute. This attribute is
used for applying CSS property on any HTML element. It provides height to paragraph element of 50px and
turns it colour to blue.
In the above statement we have again used style attribute in paragraph tag, which turns its colour red.
Note: There are some commonly used attributes are given below, and the complete list and explanation of all
attributes are given in HTML attributes List.
The title attribute in HTML
Description: The title attribute is used as text tooltip in most of the browsers. It display its text when user move
the cursor over a link or any text. You can use it with any text or link to show the description about that link or
text. In our example, we are taking this with paragraph tag and heading tag.
With <h1> tag:
which is required to display on browser. This attribute can contain image in same directory or another directory.
The image name or source should be correct else browser will not display the image.
Example
Note: The above example also have height and width attribute, which define the height and width of image on
web page.
Output:
HTML Colors
Colors are very important to give a good look and feel to your website. You can specify colors on page level
using <body> tag or you can set colors for individual tags using bgcolorattribute.
The <body> tag has following attributes which can be used to set different colors:
bgcolor - sets a color for the background of the page.
text - sets a color for the body text.
alink - sets a color for active links or selected links.
link - sets a color for linked text.
vlink - sets a color for visited links - that is, for linked text that you have already clicked on.
HTML Color Coding Methods
There are following three different methods to set colors in your web page:
Color names - You can specify color names directly like green, blue or red.
Hex codes - A six-digit code representing the amount of red, green, and blue that makes up the color.
Color decimal or percentage values - This value is specified using the rgb() property.
Now we will see these colouring schemes one by one.
HTML Colors - Color Names
You can specify direct a color name to set text or background color. W3C has listed 16 basic color names that
will validate with an HTML validator but there are over 200 different color names supported by major browsers.
Note: Check a complete list of HTML Color Names.
W3C Standard 16 Colors
Here is the list of W3C Standard 16 Colors names and it is recommended to use them.
hexadecimal notation.
Example
Here are the examples to set background of an HTML tag by color code in hexadecimal:
Border ColorExample
Output:
Note:
o The target attribute can only use with href attribute in anchor tag.
o If we will not use target attribute, then link will open in same page.
Appearance of HTML anchor tag
An unvisited link is displayed underlined and blue.
A visited link displayed underlined and purple.
An active link is underlined and red.
Module 3 - HTML Image
HTML img tag is used to display image on the web page. HTML img tag is an empty tag that contains attributes
only, closing tags are not used in HTML image element.
Let's see an example of HTML image.
Output:
Example: Output:
Use of alt attribute
We can use alt attribute with tag. It will display an alternative text in case if image cannot be displayed on
browser. Following is the example for alt attribute:
Output:
How to get image from another directory/folder?
To insert an image in your web, that image must be present in your same folder where you have put the HTML
file. But if in some case image is available in some other directory then you can access the image like this:
Output:
Use image as a link
Click on the image to know about robotics
You can also specify the background image in the <style> element, in the <head> section:
Background Image on a Page
If you want the entire page to have a background image, you must specify the background image on
the <body> element:
Background Cover
If you want the background image to cover the entire element, you can set the background-size property to cover.
Also, to make sure the entire element is always covered, set the background-attachment property to fixed:
This way, the background image will cover the entire element, with no stretching (the image will keep its
original proportions):
HTML Multimedia
Multimedia on the web is sound, music, videos, movies, and animations.
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see, like images, music,
sound, videos, records, films, animations, and more.
Web pages often contain multimedia elements of different types and formats.
Browser Support
The first web browsers had support for text only, limited to a single font in a single color.
Later came browsers with support for colors, fonts, images, and multimedia!
Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file extension.
Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.
Common Video Formats
There are many video formats out there.
The MP4, WebM, and Ogg formats are
supported by HTML.The MP4 format is
recommended by YouTube.
MPEG .mpg MPEG. Developed by the Moving Pictures Expert Group. The first popular video format
.mpeg on the web. Not supported anymore in HTML.
AVI .avi AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in video cameras
and TV hardware. Plays well on Windows computers, but not in web browsers.
WMV .wmv WMV (Windows Media Video). Developed by Microsoft. Commonly used in video
cameras and TV hardware. Plays well on Windows computers, but not in web browsers.
Note: Only MP4, WebM, and Ogg video are supported by the HTML standard.
Common Audio Formats
MP3 is the best format for compressed recorded music. The term MP3 has become synonymous with digital
music.
HTML Video
The HTML <video> element is used to show a video on a web page.
The controls attribute adds video controls, like play, pause, and volume.
It is a good idea to always include width and height attributes. If height and width are not set, the page might
flicker while the video loads.
The <source> element allows you to specify alternative video files which the browser may choose from. The
browser will use the first recognized format.
The text between the <video> and </video> tags will only be displayed in browsers that do not support
the <video> element.
HTML <video>Autoplay
To start a video automatically use the autoplay attribute:
From the above example value attribute is can be seen in server side not in client side.
Following is the list of attributes for <input> tag for creating Checkbox control
Attribute Description
Type Indicates the type of input control and for checkbox input control it will be set to checkbox.
Name Used to give a name to the control which is sent to the server to be recognized and get the value.
Value The value that will be used if the checkbox is selected.
checked Set to checked if you want to select it by default.
Select Box Control
The <select> tag is used to construct drop-down list boxes and scrolling list boxes.
Drop-down menus can serve the same purpose as radio buttons or check boxes depending on the options
specified.
The advantage of a drop- down menu, compared to radio buttons or check boxes, is that it takes up 1ess
space. But that is a1so a disadvantage, because people can’t see all options in the menu right away.
With the select attribute, the menu can be customized to show more than just one option at a time. Such lists
are typically encountered when the user is to select a city or a country.
The <option>...</option> element is used to specify each item displayed in the list.
The value of the option last selected is returned when the form data is transmitted.
Adding the select attribute in the <option> tag indicates which element is displayed initially when the page
loads.
If this is not provided, the first item is se1ected by default.
Example for select box control
<html><head><title>select box Control</title> </head>
<body>
<form >
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
</form></body></html>
Output
Following is the list of attributes used for creating Select Box control
Attribute Description
Name Used to give a name to the control which is sent to the server to be
recognized and get the value.
Size This can be used to present a scrolling list box.
Multiple If set to "multiple" then allows a user to select multiple items from the
menu.
Value The value that will be used if an option in the select box is selected.
Selected Specifies that this option should be the initially selected value when
the page loads.
Label An alternative way of labeling options
File Upload Box
The File field allows users to upload files.
The user can submit any information like picture, a spreadsheet, a scanned document or a word- processor
document after verifying that the server on which the form will be processed supports fi1e upload.
The browser displays a "BROWSE” button next to a text box that lets the user select a field from their
computer’s storage to use as the value of the file input element.
Typically, you would have encountered this option when attaching files to your email messages.
This is also created using the <input> element but type attribute is set to file.
Example for File upload control
<html><head><title>file upload box Control</title></head>
<body>
<form >
<input type="file" name="fileupload" accept="image/*" />
</form></body></html>
Output
Following is the list of attributes used for creating File upload control
Attribute Description
Name Used to give a name to the control which is sent to the server to be
recognized and get the value.
Accept Specifies the types of files that the server accepts.
Button Controls
There are various ways in HTML to create clickable buttons.
You can also create a clickable button using <input> tag by setting its “type” attribute to button.
The type=” submit” creates a submit button on the form and the type=”reset” creates a reset button.
The Submit button tells the web browser to gather up all the selections, values, and entered text in the form
elements and dispatch it off to the destination defined in the action part of the <FORM> tag.
The Reset button restores the form to its default state.
The submit or the reset button has a typical shape and size, which may not be in harmony with the rest of the
look and feel of the web page.
Hence you may prefer to use an image instead using the type=”image” attribute.
When a user clicks an image button the form is sent to the address specified in the action attribute of the
<form> tag.
Following is the list of attributes used for creating button control
Type Description
Submit This creates a button that automatically submits a form.
Reset This creates a button that automatically resets form controls to their initial
values.
Button This creates a button that is used to trigger a client-side script when the
user clicks that button.
Image This creates a clickable button but we can use an image as background of
the button.
Example for button controls
<html><head><title>Different button Controls</title></head>
<body><form >
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
<input type="image" name="imagebutton" src="/html/images/logo.png" />
</form></body></html>
Output
Module 3 - Frames
A frame divides the screen into separate windows with both vertical and horizontal scroll bars.
The windows so formed may appear to be sub-windows of the main window (the webpage).
This allows the user to access different pages of a website from one screen if designed to do so.
Frames are needed when you want to have menus on one side and the contents or the operations on the other
side.
When the user clicks on one of the menu items, the contents become visible on the other side.
A frame divides the webpage into different windows. It makes some structural changes to the main window.
Hence, it is not written inside the body element, but it forms its own element, outside the head section of
HTML document called the FRAMESET.
A FRAMESET element is the parent element that defines the characteristics of individual frame pages.
The basic syntax of FRAMESET element
<html><head> … </head>
<FRAMESET cols= “number%,number%”
<frame src = “address of HTML document”>
<frame src = “address of HTML document”>
</FRAMESET></html>
The attributes used with the FRAMESET element are given in the table below:
FRAMESET element works in conjunction with the FRAME tag whose attributes are discussed below
If we want to make a webpage that uses two frames divided in columns, we should follow these steps
HTML Page with FRAMESET element
<html><head><title>frameset program <title></head>
<FRAMESET cols=”120,*”>
<frame src=”menu.html” name=”menu”>
<frame src=”main.html” name=”main”>
</FRAMESET></html>
In the above code, the left side of the column is 120 pixels and the Star indicates the rest of the screen. A
star has been used because the screen size varies; it may be 640 pixels across, or 800 or 1024 pixels
across.
The ‘src’ attribute opens the menu.html document in left side frame and main.html gets opened in right
side frame. Both the frames are given a name through the ‘name’ attribute.
Create a number of HTML documents (containing the body tag) that you would like to load into the
frames. (At least as many as the frames that are there in the FRAMESET element from the above
example you need to have two documents; menu.html andmain.html)
When a FRAMESET page is loaded, the browser automatically loads the HTML documents designed.
If you want to divide the webpage in equal sizes horizontally, and want to display a.html in first and
b.html in second, you will use the following code.
<html><head>…</head>
<FRAMESET rows= “50%,50%”>
<frame src = “a.html”>
<frame src = “b.html”>
</FRAMESET></html>
The first FRAMESET divides the screen into two
rows. Now since the control has come to the first row of the new screen, the second FRAMESET can
divide it into two columns.
Open the two HTML documents, a.html and b.html, give them a name and then move the control to the
second row of the new screen. Since now the control is on the second screen, SRC can now open
secondrow.html as shown in below figure.
If we want to insert scrolls in the frames, when the contents of the frame are not visible, use the value
“auto” as shown below:
<html><head></head>
<FRAMESET cols=”120,*”
frameborder=0 framespacing=50>
<frame src=”a.html”
scrolling=auto>
<frame src=”formbutton.html”
scrolling=no>
</FRAMESET></html>
Multiple Choice Questions
1) Which HTML element is used to define a multi-line input field?
a) <multi-line> b) <textarea> c) <textfields> d) <textline>
2) In forms the _lank target attribute opens a linked document in …?
a) same window b) New tab c) New window d) Both A & B
3) Which character tells the end of a tag in HTML?
a) / b) \ c) >d) <
4) In HTML form the <input type=”text”> is used for …?
a) One line text b) Block of text c) one paragraph d) All of the these
5) Which tag is used for a submit button?
a) <button> b) <submit> c) <submit button> d) <input type=”submit”>
6) Which method is used when form data contains sensitive or personal information?
a) Get method b) Post method c) Both a &b d) Host method
7) The action attribute in HTML forms specifies ….?
a) Which HTTP method is used b) Which action is going on c) Where to submit the form
d) The auto completion of form
8) Which of the following is not the form type for adding text?
a) Text input b) Text area c) Password input d) Submit button
9) Which of the following creates push button?
a) Reset b)Check Box c)Input d) All of these
10) Define frameset to create 3 Horizontal frames?
a) <frameset rows=”20%,60%,20%”>-----</frameset> b)<frameset cols=”20%,60%,20%”>-----
</frameset> c) <frameset hrlines=”20%,60%,20%”>-----</frameset> d) None of these
Descriptive Questions
1) Explain about Forms in HTML
2) Explain about Frames in HTML
3) Explain about different fields in HTML Forms
4) Explain about forms and frames with example.
Unsolved Problems
1) Write HTML code to create basic form.
2) Write HTML code to create form.
3) Write HTML code to create your bio-data form.
Unit 4 - Introduction to CSS
Module 1 – Introduction to CSS and Font properties
CSS stands for cascading style sheets. CSS describe how HTML elements are to be displayed CSS saves a lot of
work. It can control the layout of multiple web pages all at once.
Why use CSS:
CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.
CSS Syntax:
A CSS rule – set of a selector and a declaration block:
1) Selector points to the HTML element you want to style.
2) The declaration block contains one or more declarations separated by semicolons.
3) Each declaration included a CSS property name and a value. Separated by a colon.
4) A CSS declaration always ends with a semicolon and declaration blocks are surrounded by curly braces.
The Limitations of CSS:
CSS is very limited in browser compatibility. When you design a web page and you want it to display exactly as
you like it. The problem with CSS is that it displays web pages very differently in the different browsers. Your
webpage looks perfect in Mozilla may look different in Internet Explorer. This is a big problem for your site’s
success.
Methods of applying CSS to an HTML document:
There are three ways you can apply CSS to an HTML document. The First method is “In-Line, Second method is
“Internal” and the Third method i.e. external which is most important.
Method 1: In-line (the attribute style):
Output:
Output:
Method 3: External (link to a style sheet):
The method to link html with style sheet is called external style sheet. An external style sheet is a text file with
the extension .css. Like other files, we can place the style sheet on your web server or hard disk. For example,
save the style sheet with the name style.css and place it in a folder named style.
To create a link from the HTML document (default.htm) to the style sheet (style.css). The following code will be
inserted in the header section of the HTML code i.e. between the <head> and </head> tags. HTML file. <link
rel=”stylesheet” type=”text/css” href=”style/style.css” />
In the other notepad rename as style.css we have to write the following code
This link will display the layout from the CSS file in the browser when displaying the HTML file.
Output:
One CSS file can be used to control the layout of many HTML documents. Using CSS, the change can be made
in a few seconds just by changing one code in the central style sheet.
Font Properties:
Following are the font properties.
1. Font – family
2. Font – style
3. Font – size
4. Font – variant
5. Font – weight
1. Font family:
The property font-family is used to apply prioritized list of fonts in a web page. If the first font of the list is not
installed on the computer then the next font of the list will be displayed until a suitable font is found. Font’s
family is divided into two categories
a. Generic Family: a group of font families with a similar look (like "Serif" or "Monospace")
b. Font Family: a specific font family (like "Times New Roman" or "Arial")
Font style:
The property font-style defines the chosen font either in normal, italic or oblique. In the example below, all
headlines marked with <h2> will be shown in italics.
h1 {font-family: arial, verdana, sans-serif; font-style: oblique;}
h2 {font-family: “Times New Roman”, serif; font-style: italic;}
Font variant:
This property is used to select normal or small-caps variants of a font. A small-caps font displays the smaller
sized capitalized letters (upper case) instead of lower case letters.
If font-variant is set to small-caps and no small-caps font is available the browser will most likely show the text
in uppercase instead.
h1 {font-variant: small-caps;}
h2 {font-variant: normal;}
Font weight:
This property describes how bold or “heavy” a font should be presented. A font can either be normal or bold.
Some browsers supports the use of numbers between 100 and 900(in hundreds) to describe the weight of a font.
p {font-family: arial, verdana, sans-serif; font-weight: normal;}
td {font-family: arial, verdana, sans-serif; font-weight: bold;}
The units ‘px’ and ‘pt’ make the font size absolute, while ‘%’ and ‘em’ allow the user to adjust the font size as
he/she see fit. Some users suffer from poor vision or a monitor of bad quality. To make your website readable for
everybody, you should use adjustable units such as ‘%’ or ‘em’
Combining [font] styles. All the different font properties can be combined in one single property. For example,
to apply different font-properties for <p> tag following code can be used.
p { font-style: italic;
font-weight: bold;
font-size: 30px;
font-family: arial, sans-serif; }
The order of values for font properties is:
`
Module 2 - Text Properties
The following are text properties applied to text on the web page
1) Text-indent 2) Text-align 3) Text-decoration 4) Letter-spacing 5) Text-transform
Text – indent:
The text-indent property allows you to add effects to text paragraphs by applying an indent to the first line of the
paragraph.
Example:
To apply 40px indentation to all text paragraphs marked with <p>, the following code will be used:
Text alignment:
The text-align property gives the same effect as attribute align gives in old versions of HTML. The text can
either be aligned to the left, to the right or center of the screen. CSS allows you to apply justified alignment on
text which is not available in HTML. The value justify will stretch each line so that both the right and left
margins are straight.
Example:
Display the text in table headings <th> aligned to the right while the table data <td> in the centre of the browser
window and normal text in paragraphs to be justified.
Text decoration:
The text-decoration property makes it is possible to add different “decorations” or “effects”to text. For example,
you can underline the text, have a line through or above the text,etc. In the following example, <h1> are
underlined headlines, <h2> are headlines with a line above the text and <h3> are headlines with a line though the
text.
Letter space:
This property is used to give the specified spacing between the text characters. The value of the property is
simply the desired width.
Example:
To give 3px spacing between the letters in a text paragraph <p> and 6px between letters in headlines <h1> the
following code will be used:
Text transformation:
The text-transform property controls the capitalization of a text. You can choose capitalize, use uppercase or
lowercase regardless of how the original text is looks in the HTML code. An example could be the
word“headline” which can be presented to the user as “HEADLINE” or “Headline”. There are four possible
values fortext-transform:
Capitalize: Capitalizes the first letter of each word. For example: “information technology” will be “Information
Technology”.
Uppercase: Converts all letters to uppercase. For example: “information technology” will be “INFORMATION
TECHNOLOGY”.
Lowercase: Converts all letters to lowercase. For example: “INFORMATION TECHNOLOGY” will be
“information technology”.
None: No transformations - the text is presented as it appears in the HTML code.
Background Properties:
1. FOREGROUND-COLOR
2. BACKGROUND-COLOR
3. BACKGROUND-IMAGE
4. BACKGROUND-REPEAT
Foreground color: the ‘color’ property:
The color property describes the foreground color of a text to be displayed in browser.
Example, display all headlines in a document to be in green color.
Background-color property:
The background-color property describes the background color of browser window. To change the background
color of an entire page, the background-color property should be applied to the <body> tag. You can also apply
background colors to other elements including headlines and text.
Example, apply different background colors to <body> and <h1> tags.
if( age> 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body></html>
Output: Qualifies for driving
Set the variable to different value and then try...
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a
more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else { Statement(s) to be executed if expression is false}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are
executed. If the expression is false, then the given statement(s) in the else block are executed.
Example: Try the following code to learn how to implement an if-else statement in JavaScript.
<html><body>
<script type = "text/javascript">
<!--
var age = 15;
if( age> 18 ) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body></html>
Output: Does not qualify for driving
Set the variable to different value and then try...
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out
of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of
the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the
conditions is true, then the else block is executed.
Example: Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html><body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body><html>
Output: Maths Book
Set the variable to different value and then try...
Module 3 - Introducing basic effects into web page
You can use JavaScript to create a complex animation having, but not limited to, the following elements −
Fireworks, Fade Effect, Roll-in or Roll-out, Page-in or Page-out and Object movements
You might be interested in existing JavaScript based animation library:
This module provides a basic understanding of how to use JavaScript to create an animation.
JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element)
around the page according to some sort of pattern determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in animation programs.
setTimeout( function, duration) − This function calls function after duration milliseconds from now.
setInterval(function, duration) − This function calls function after every duration milliseconds.
clearTimeout(setTimeout_variable) − This function calls clears any timer set by the setTimeout()
functions.
JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can
set top and left attribute of an object to position it anywhere on the screen. Here is its syntax.
// Set distance from left edge of the screen.
object.style.left = distance in pixels or points;
or
// Set distance from top edge of the screen.
object.style.top = distance in pixels or points;
Manual Animation
So let's implement one simple animation using DOM object properties and JavaScript functions as follows. The
following list contains different DOM methods.
We are using the JavaScript function getElementById() to get a DOM object and then assigning it to a
global variable imgObj.
We have defined an initialization function init() to initialize imgObj where we have set
its position and left attributes.
We are calling initialization function at the time of window load.
Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also
set it to a negative value to move it to the left side.
Example:
<html><head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
varimgObj = null;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload = init;
//-->
</script>
</head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick = "moveRight();" />
</form>
</body></html>
Output: Automated Animation
In the above example, we saw how an image moves to right with every click. We can automate this process by
using the JavaScript function setTimeout() as follows −
Here we have added more methods. So let's see what is new here −
The moveRight() function is calling setTimeout() function to set the position of imgObj.
We have added a new function stop() to clear the timer set by setTimeout() function and to set the
object at its initial position.
Example:
<html><head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
varimgObj = null;
varanimate ;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop() {
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload = init;
//-->
</script></head>
<body>
<form>
<img id = "myImage" src = "/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body></html>
Rollover with a Mouse Event
Here is a simple example showing image rollover with a mouse event.
Let's see what we are using in the following example −
At the time of loading this page, the ‘if’ statement checks for the existence of the image object. If the
image object is unavailable, this block will not be executed.
The Image() constructor creates and preloads a new image object called image1.
The src property is assigned the name of the external image file called /images/html.gif.
Similarly, we have created image2 object and assigned /images/http.gif in this object.
The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This
link is an image.
The onMouseOver event handler is triggered when the user's mouse moves onto the link, and
the onMouseOut event handler is triggered when the user's mouse moves away from the link (image).
When the mouse moves over the image, the HTTP image changes from the first image to the second one.
When the mouse is moved away from the image, the original image is displayed.
When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type = "text/javascript">
<!--
if(document.images) {
var image1 = new Image(); // Preload an image
image1.src = "/images/html.gif";
var image2 = new Image(); // Preload second image
image2.src = "/images/http.gif";
}
//-->
</script></head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href = "#" onMouseOver = "document.myImage.src = image2.src;"
onMouseOut = "document.myImage.src = image1.src;">
<img name = "myImage" src = "/images/html.gif" />
</a>
</body></html>
Multiple Choice Questions
1) Which type of JavaScript language is ___
a) Object-Oriented b)Object-Based c) Assembly-language b) High-level
2) Which of the following is the correct output for the following JavaScript code:
a) 1 b) Error c) 10 d) 5
3) In JavaScript, what is a block of statement?
a. Conditional block
b. block that combines a number of statements into a single compound statement
c. both conditional block and a single statement
d. block that contains a single statement
4) The "function" and " var" are known as:
a. Keywords b. Data types c. Declaration statements d. Prototypes
5) Which of the following is the correct output for the following JavaScript code
a. 3 b. 0 c. Error d.2
Descriptive Questions
1) What is client side java script and server side java script?
2) Write java script history and features of it?
3) What are the limitations of java script
4) write any simple java script in html
5) Write java script example for if, if..else and if..else if
6) write any 3 basic effects using java script
UNIT 6 -Basics of Algorithms and Flow charts
Module 1 – Introduction to problem Solving
Introduction:
Intelligence is one of the key characteristics which differentiate a human being from other living creatures on the
earth. Basic intelligence covers day to day problem solving and making strategies to handle different situations
which keep arising in day to day life. One person goes Bank to withdraw money. After knowing the balance in
his account, he/she decides to with draw the entire amount from his account but he/she has to leave minimum
balance in his account. Here deciding about how much amount he/she may with draw from the account is one of
the examples of the basic intelligence. During the process of solving any problem, one tries to find the necessary
steps to be taken in a sequence. In this Unit you will develop your understanding about problem solving and
approaches.
Problem Solving:
Can you think of a day in your life which goes without problem solving? Answer to this question is of course,
No. In our life we are bound to solve problems. In our day to day activity such as purchasing something from a
general store and making payments, depositing fee in school, or withdrawing money from bank account. All
these activities involve some kind of problem solving. It can be said that whatever activity a human being or
machine do for achieving a specified objective comes under problem solving. To make it clearer, let us see some
other examples.
Example1: If you are watching a news channel on your TV and you want to change it to a sports channel, you
need to do something i.e. move to that channel by pressing that channel number on your remote. This is a kind of
problem solving.
Example 2: One Monday morning, a student is ready to go to school but yet he/she has not picked up those
books and copies which are required as per timetable. So here picking up books and copies as per timetable is a
kind of problem solving.
Example 3: If someone asks to you, what is time now? Seeing time in your watch and telling is also a kind of
problem solving.
Example 4: Some students in a class plan to go on picnic and decide to share the expenses among them. So
calculating total expenses and the amount an individual have to give for picnic is also a kind of problem solving.
Now, we can say that problem is a kind of barrier to achieve something and problem solving is a process
to get that barrier removed by performing some sequence of activities.
Here it is necessary to mention that all the problems in the world cannot be solved. There are some
problems which have no solution and these problems are called Open Problems.
If you can solve a given problem, then you can also write an algorithm for it. In next section we will
learn what is an algorithm?
Module 2 –Algorithm
Introduction
Algorithm is a step-by-step process of solving a well-defined computational problem. In practice, in order to
solve any complex real-life problems, first we have to define the problem and then, design algorithm to solve it.
Writing and executing a simple program may be easy; however, for executing a bigger one, each part of the
program must be well organized. In short, algorithms are used to simplify the program implementation. The
study of algorithms is one of the key foundations of computer science. Algorithms are essential to the way
computers process information, because a computer program is essentially an algorithm that tells the computer
what specific steps to perform (in what specific order) in order to carry out a specified task, such as calculating
employees’ paychecks or printing students’ report cards. Thus, an algorithm can be considered to be any
sequence of operations that can be performed by a computing device such as a computer.
What is an Algorithm?
• Algorithm is a step by step procedure to solve a particular problem or “A sequence of activities to be
processed for getting desired output from a given input.
• It’s a easy way of analyzing a problem.
Structure of an algorithm:
START
– STEP 1
– SETP 2
– SETP 3
– SETP 4
– ……………………so on
STOP
Example 1: A simple algorithm to print „Good Morning‟.
Step 1: Start
Step 2: Print „Good Morning‟
Step 3: Stop
Example 2: Let us take one simple day-to-day example by writing algorithm for making “Maggi Noodles” as a
food.
Inputs to the algorithm: Maggie Noodles packet, Pan, Water, Gas
Expected output: Maggie Noodles
Algorithm:
Step 1: Start
Step 2: Take pan with water
Step 3: Put pan on the burner
Step 4: Switch on the gas/burner
Step 5: Put Maggie and masala
Step 6: Give two minutes to boil
Step 7: Take off the pan
Step 8: Take out the magi with the help of fork/spoon
Step 9: Put the Maggie on the plate and serve it
Step 10: Stop
Example3: Find the area of a Circle of radius r.
Inputs to the algorithm: Radius r of the Circle.
Expected output: Area of the Circle
Algorithm:
Step1: Start
Step2: Read\input Radios
Step3: Set 3.14 to PI
Step4: Set Area PI* Radios * Radios // calculation of area
Step5: Print Area
Step6: stop
Expressing Algorithms:
An algorithm is a set of steps designed to solve a problem or accomplish a task. Algorithms are usually written in
pseudo code, or a combination of your speaking language and one or more programming languages, in advance
of writing a program. An algorithm may be expressed in a number of ways, including:
Natural language: usually verbose and ambiguous.
Flow charts: avoid most (if not all) issues of ambiguity; difficult to modify w/o specialized tools;
largely standardized.
Programming language: Tend to require expressing low – level details that are not necessary for a high
– level understanding.
Qualities of a good algorithm
1) Inputs and outputs should be defined precisely.
2) A good algorithm should produce correct and accurate results for any set of legal or correct inputs.
3) Each step in algorithm should be clear and unambiguous.
4) Algorithm should be most effective among many different ways to solve a problem.
5) An algorithm shouldn’t have computer code. Instead, the algorithm should be written in such a way that
it can be used in similar programming languages Whenever we write an algorithm, we should make sure
that all of these parameters given for a good algorithm are incorporated.
Advantage of algorithm
1) It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
2) An algorithm uses a definite procedure.
3) It is not dependent on any programming language, so it is easy to understand for anyone even without
programming knowledge.
4) Every step in an algorithm has its own logical sequence so it is easy to debug.
5) By using algorithm, the problem is broken down into smaller pieces or steps hence, it is easier for
programmer to convert it into an actual program
Disadvantagesof algorithm
1) Writing algorithm takes a long time.
2) An Algorithm is not a computer program; it is rather a concept of how a program should be
3) Big tasks are difficult to put in Algorithms.
4) Difficult to show Branching and Looping in Algorithms.
Properties of algorithm:
1) Finiteness: An algorithm must always terminate after a finite number of steps. It means after every step
one reach closer to solution of the problem and after a finite number of steps algorithm reaches to an end
point.
2) Definiteness: Each step of an algorithm must be precisely defined. It is done by well thought actions to
be performed at each step of the algorithm. Also the actions are defined unambiguously for each activity
in the algorithm.
3) Input: An algorithm has zero or more inputs, taken from a specified set of objects.
4) Output: An algorithm has one or more outputs, which have a specified relation to the inputs.
5) Effectiveness: All operations to be performed must be sufficiently basic that they can be done exactly
and in finite length
Algorithm Efficiency
Algorithmic efficiency is a property of an algorithm which relates to the number of computational resources used
by the algorithm. An algorithm must be analyzed to determine its resource usage, and the efficiency of an
algorithm can be measured based on usage of different resources.
Speed - Method that takes the least time
Space - Method that uses the least memory
Code — Method that is shortest to describe
Speed is now the most important factor Example
A real world example: Travelling from Vempalli to Hyderabad in Vehicle
Case 1:
1. Take vehicle
2. Check vehicle condition if not get it repair
3. Drive from vempalli to Proddutur
4. Then Proddutur to Hyderabad
5. Travel is successfully completed.
Case 2:
1. Take vehicle
2. Check vehicle condition if not get it repair
3. Drive from Vempalli to kadapa
4. Then Kadapa tokurnool
5. Then Kurnool to Hyderabad
6. Travel is successfully completed
While comparing both cases Algorithm executed successfully with same output but in case 1 travelling time is
lesser than the case 2 travelling time.
Tracing an Algorithm
Tracing of an Algorithm means showing how the value of a variable changes during the execution of an
algorithm.
Steps in tracing:
1. Identify the variables in the algorithm that need to be traced.
2. Examine the value of the variables at each step in the execution of the algorithm.
3. Determine if the algorithm is giving the correct outputs for a set of legitimate/legal input. Values.
4. Analyze and determine what the purpose of the algorithm
In this module we will see examples of computational algorithms and the techniques used for tracing algorithms.
A computational algorithm is a set of precise instructions expected to be expressed as a computer program that
can execute on a computer.
Let us now get started with an example of adding two numbers.
Algorithm: Add two numbers
Step1: Start
Step2: Input x
Step3: Input y
Step4: Set z x+ y
Step5: Output z
Step6: Stop
If you notice the algorithm it takes two inputs, performs an addition operation and gives the output. Let us see
how the algorithm executes step by step.
Input x/* Takes input from the user by using input devices like keyboard. After entering input from the key
board, for ex: 5 the value is stored in a memory location. The name of this memory location is x in this particular
case. Any time this variable x can store only one value. For ex: if you set x value 6 you will find the new value is
referred by x is 6 but not 5 that means the old value which was stored in x values is lost. This is a very good
example that shows a variable can store only one value at a time. Input value :5*/ Input y /* Similar to previous
statement where new memory location is created for variable y and the user inputs to y is stored.Input value :2*/
Set z to x+ y /* in this statement actual operation that is performed on the input values which is to add the
numbers referred to by the variables x and y. In this example you will notice after the addition operation is
executed and the values 5 and 2 are added and set to new variable z. */
Output z //the result value i.e. z is displayed to an output device like monitor?
You will notice that algorithm also can be visualized as functions. A function performs a specific operation like
addition and multiplication or it could be more complex operations like finding square roots or sorting list of
numbers.
Variable:
Variables are used to handle the data by the algorithm.
Variables refer to a memory location where the actual value is stored.
Variable can store one value at a time.
Old values of the variable are lost when a new value is assigned.
Control structure:
Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be
clearer and more understood if they use self-contained modules called as logic or control structures. It basically
analyzes and chooses in which direction a program flows based on certain parameters or conditions.
Types of control structures:
There are three types of control structures
1) Sequence
2) Selection or Branching
3) Loop or Repetition
Sequence Control Structure: This refers to the line – by – line execution, in which statements are executed
sequentially, in the same order in which they appear in the script.They might, for example, carry out a series of
read or write operations, arithmetic operations, or assignments to variables.
Example problem:Write algorithm to find the greater number between two numbers
Step1: Start
Step2: Read\input the Number1
Step3: Read\input the Number2.
Step4: Set Average (Number1+ Number2)/2
Step5: Print Average
Step6: End
Selection or Decision Control Structure: The branch refers to a binary decision based on some condition.
Depending on whether a condition is true or false. If the condition is true, one of the two branches is explored; if
the condition is false, the other alternative is taken. This is usually represented by the ‘if-then’ construct in
pseudo-codes and programs. This structure is also known as the selection structure
Example problem:A person whose age is more than or equals to 18 years is eligible to vote. Now write an
algorithm to check whether he is eligible to vote?
Step 1: Start
Step2: Input/Read age //Taking age value from the user
Step 3: Check if age >= 18
a) Print “Eligible to vote” //If Condition is true
Step 4: Otherwise/else
a) Print “Not eligible to vote” //if Condition is false
Step 5: Stop
Repetition or Loop Control Structure: This is a control structure that allows the execution of a block of
statements multiple times until a specified condition is met. The loop allows a statement or a sequence of
statements to be repeatedly executed based on some loop condition. It is represented by the ‘while’ and ‘for’
constructs in most programming languages, for unbounded loops and bounded loops respectively. (Unbounded
loops refer to those whose number of iterations depends on the eventuality that the termination condition is
satisfied; bounded loops refer to those whose number of iterations is known before-hand.) In the flowcharts, a
back arrow hints the presence of a loop. A trip around the loop is known as iteration. You must ensure that the
condition for the termination of the looping must be satisfied after some finite number of iterations, otherwise it
ends up as an infinite loop, a common mistake made by inexperienced programmers. The loop is also known as
the repetition structure.
Example problem:Algorithm to print all-natural numbers upto “n” (Here you need to accept a number from the
user, and to print all the natural numbers till ‘n’ i.e. 1 to n)
Step 1: Start
Step2: Read/Input n
Step 3: Store 1 to “i” //initialization
Step 4: Do the following statements until i<=n//condition
a) print i
b) add 1 to i//increment
Step 5: Stop
Nested control structures: Combining the use of these control structures, for example, a loop within a loop
(nested loops), a branch within another branch (nested if), a branch within a loop, a loop within a branch, and so
forth, is not uncommon. Complex algorithms may have more complicated logic structure and deep level of
nesting, in which case it is best to demarcate parts of the algorithm as separate smaller modules. Beginners must
train themselves to be proficient in using and combining control structures appropriately, and go through the
trouble of tracing through the algorithm before they convert it into code.
Module 3 - Introduction to Flow chart
Flowchart
The diagrammatic representation of an algorithm is called “Flowchart”. Before you start coding a program it is
necessary to plan the step by step solution to the task your program will carry out. Such a plan can be
symbolically developed using a diagram. This diagram is then called a flowchart. Hence a flowchart is a
symbolic representation of a solution to a given task. A flowchart can be developed for practically any job.
Flowcharting is a tool that can help us to develop and represent graphically program logic sequence.
For example, suppose you are going for a picnic with your friends then you plan for the activities you will do
there. If you have a plan of activities, then you know clearly when you will do what activity. Similarly, when you
have a problem to solve using computer or in other word you need to write a computer program for a problem
then it will be good to draw a flowchart prior to writing a computer program. Flowchart is drawn according to
defined rules.
Features of flowchart:
The features of a flowchart are:
1. It is an easy method of communication.
2. It is independent of a programming language.
3. It is the key to correct programming.
4. It clearly indicates the task to be performed at each level.
Flowchart Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language Programs: Terminal, Process,
and input/output, Decision, Connector and Predefined Process. This is not a complete list of all the possible
flowcharting symbols; it is the ones used most often in the structure of Assembly language programming.
1) Process Symbol:
o A process symbol is used to represent arithmetic and data movement instructions in the flowchart. All
arithmetic processes of addition, subtraction, multiplication and division are indicated in the process
symbol.
o The logical process of data movement from one memory location to another is also represented in
the process box. If there are more than one process
2) Input/ Output Symbol:
o This symbol is used to denote any input/output function in the program. Thus, if there is any input to
the program via an input device, like a keyboard, tape, card reader etc. it will be indicated in the
flowchart with the help of the Input/output symbol.
o Similarly, all output instructions, for output to devices like printers, plotters, magnetic tapes, disk,
monitors etc. are indicated in the Input/ Output symbol.
3) Decision Symbol:
o The decision symbol is used in a flowchart to indicate the point where a decision is to be made and
branching done upon the result of the decision to one or more alternative paths. The criteria for
decision making are written in the decision box.
o All the possible paths should be accounted for. During execution, the appropriate path will be
followed depending upon the result of the decision.
4) Loops: Looping is a problem-solving technique through which a group of statements is executed
repeatedly, until certain specified condition is satisfied. Looping is also called a repetitive or an iterative
control statement
5) Connectors:
This symbol shows continuation of the flow chart from one page to another. When you reach the bottom
of the page or need to jump to another page, draw flow chart connector symbol and connect it to the last
item on the chart. Label the inside of the symbol with a letter, typically beginning with an “A”.
6) Predefined process (Function):
This symbol indicates a sequence of actions that perform a specific task embedded within a larger
process.
7) Terminal Symbol:
o Every flowchart has a unique starting point and an ending point.
o The flowchart begins at the start terminator and ends at the stop terminator.
o The Starting Point is indicated with the word START inside the terminator symbol. The Ending Point
is indicated with the word STOP inside the terminator symbol. There can be only one START and one
STOP terminator in your entire flowchart.
General Rules for flowcharting
1) All boxes of the flowchart are connected with Arrows. (Not lines)
2) Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit
point for all flowchart symbols is on the bottom except for the Decision symbol.
3) The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4) Generally, a flowchart will flow from top to bottom. However, an upward flow can be shown as long as
it does not exceed 3 symbols.
5) Connectors are used to connect breaks in the flowchart. Examples are:
a. From one page to another page.
b. From the bottom of the page to the top of the same page.
6) Subroutines (Functions) and Interrupt programs have their own and independent flowcharts.
7) All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines)
symbol.
8) All flowcharts end with a terminal or a contentious loop.
Flowcharting uses symbols that have been in use for a number of years to represent the type of operations and/or
processes being performed. The standardized format provides a common method for people to visualize
problems together in the same manner. The use of standardized symbols makes the flow charts easier to interpret,
however, standardizing symbols is not as important as the sequence of activities that make up the process.
Advantages of using flowchart
As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial representation of a
solution/system is having many advantages. These advantages are as follows:
Communication: A Flowchart can be used as a better way of communication of the logic of a system
and steps involve in the solution, to all concerned particularly to the client of system.
Effective analysis: A flowchart of a problem can be used for effective analysis of the problem.
Documentation of Program: Program flowcharts are a vital part of good program documentation.
Program document is used for various purposes like knowing the components in the program,
complexity of the program etc.
Efficient Program Maintenance: Once a program is developed and becomes operational it needs time
to time maintenance. With help of flowchart maintenance become easier.
Coding of the Program: Any design of solution of a problem is finally converted into computer
program. Writing code referring the flowchart of the solution become easy.
Disadvantagesof using flowchart:
Drawing flowchart is a time-consuming task.
Manual tracing is needed to check correctness of flowchart drawn on paper.
Simple modification in problem logic may lead to complete redraw of flowchart.
Showing many branches and looping in flowchart is difficult.
In case of complex program/algorithm, flowchart becomes very complex and clumpsy.
Some examples of Flowcharts
Now, we will discuss some examples on flowcharting. These examples will help in proper understanding of
flowcharting technique. This will help you in program development process in next unit of this block.
Problem1: Find the area of a circle of radius r
Problem 2: Convert temperature Fahrenheit to Celsius.
Problem3: Flowchart for an algorithm which gets two numbers and prints sum of their value.
2) Take input of two numbers from the user and do the division of two numbers?
Iterative (loop):
Its repeat the execution of a block of instruction.
In this structure the statements are executed more than one time. It is also known as iteration or loop
A loop structure is used to execute a certain set of actions for a predefined number of times or until a
particular condition is satisfied
Example: while loop, for loop do-while loops etc.
Example problem:Write an algorithm and flowchart to find Total Sum from 1 to 100 natural numbers
Step 1: Start
Step 2: Read value of n
Step 3: Set i←1
Step 4: Set Total_Sum 0
Iterative Structure
Step 5: Repeat the steps until i greater than n
a) Set Total_SumTotal_Sum+i
b) increment i // (i.e. i=i+1)
Step 6: Display “1 to 100 Natural Numbers Sum:” Total_Sum
Step 7: End
Pseudo code
A pseudo code is an informal way of writing a program. However, it is not a computer program. It only
represents the algorithm of the program in natural language and mathematical notations. Besides, there is no
particular programming language to write a pseudo code. Unlike in regular programming languages, there is no
syntax to follow when writing a pseudo code. Furthermore, it is possible to use pseudo codes using simple
English language statements.
Pseudo code is a kind of structured English for describing algorithm.
It has no syntax like any of the programming language and thus can’t be compiled or interpreted by the
computer.
No syntax for Pseudo code
Not executable program
Advantages of Pseudo code
Improves the readability of any approach. It’s one of the best approaches to start implementation of an
algorithm.
Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code is written
out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves
vital.
The main goal of a pseudo code is to explain what exactly each line of a program should do, hence
making the code construction phase easier for the programmer
How to write a Pseudo-code?
To begin the comment double forward slash are used “//“.
Matching braces “{and}” are used to present blocks where a compound statement (set of simple
statements) can be illustrated as a block and terminated by a semicolon”;“. The body of a procedure
constructs a block as well.
All the identifiers start with a letter and the data type of the variables are not declared explicitly.
An assignment statement is used for the assigning values to the variables.
To produce the Boolean values (i.e., true and false) the logical operators and, or and not and the
relational operators <, ≤, =, =, ≥ and > are provided.
Input and output are presented by read and write instructions.
Example:A pseudo code to find the total of two numbers is as follows.
Sum Of Two Numbers ()
begin
Set sum =0;
Read: number 1, number 2;
Set sum = number1 + number 2;
Print sum;
End
2. A pseudo code to find the area of a triangle is as follows.
AreaofTrinagle()
Begin
Read: base,height;
Set area =0.5*base*height;
Print area;
End
Differences between algorithm and Flowchart:
Algorithm Flow chart
Step by step instruction representing the process of any Block by block information diagram representing the
solution. data flow.
It is step wise analysis of the work to be done It is a pictorial representation of a process
Solution is shown in non-computer language like Solution is shown in graphical format.
English.
It is something difficult to understand. Easy to understand as compared to algorithm.
Difficult to show branching and looping. Easy to show branching and looping.
Algorithm can be written for any problem. Flow chart for big problem is impractical.
Easy to debug errors. Difficult to debug errors.
It is difficult to write algorithm as compared to It is easy to make flowchart.
flowchart.
Differences between algorithm and Pseudocode:
Basis for comparison Algorithm Pseudo code
Comprehensibility Quite hard to understand Easy to interpret
Uses Complicated programming language Combination of programming language and
natural language.
Debugging Moderate simpler
Ease of construction Complex Easier
Difference between flow chart and pseudo code:
Flow chart Pseudo code
A diagrammatic representation that illustrates a An informal high – level description of the operating
solution model to a given problem. principle of an algorithm.
Written using various symbols. Written in natural language and mathematical
notations help to write pseudo code.
Solved problems:
1) Write an algorithm to go for class picnic.
Algorithm:
Step 1: Start
Step 2: Decide the picnic venue, date and time
Step 3: Decide the picnic activities
Step 4: Hire a vehicle to reach to the venue and comeback
Step 5: Goto to the picnic venue on the decided date
Step 6: Do the activities planned for the picnic
Step 7: Come back to school in the hired vehicle
Step 8: Stop
2) To celebrate Teachers' Day
Algorithm:
Step 1: Start
Step 2: Decide the activities for teachers' day like dance performances, plays, etc.
Step 3: Form groups of students and assign the decided activities from step 2 to each group.
Step 4: Decide the practice timings for each group.
Step 5: Each group to practice as per the timings decided in step 4.
Step 6: Invite the teachers to Teachers' Day celebrations.
Step 7: Perform the activities planned in step 2 on Teachers' Day
Step 8: Stop
3) To celebrate New Year
Algorithm:
Step 1: Start
Step 2: Prepare a guest list for New Year party
Step 3: Decide the venue, food menu, games and fun activities for the party
Step 4: Invite the guests for the party
Step 5: On New Year eve, get ready and enjoy the party
Step 6: Stop
4) Convert temperature Fahrenheit to Celsius with flowchart
Inputs to the algorithm: Temperature in Fahrenheit
Expected output: Temperature in Celsius
Algorithm:
Step1: Start
Step2: Read Temperature in Fahrenheit F
Step3: Set C 5/9*(F-32)
Step4: Print “Temperature in Celsius: “+C
Step5: End
5) Write an algorithm to read two numbers and find their product?
Inputs to the algorithm: First num1. Second num2.
Expected output: Sum of the two numbers.
Algorithm:
Step1: Start
Step2: Read\input num1.
Step3: Read\input num2.
Step4: set product num1 * num2 // calculation of product
Step5: Print product.
Step6: End
6) An algorithm to display even numbers between 0 and 99 with
flowchart
Step 1: Start
Step2: input/read value of n
Step3: Set even0
Step4: Do the following until even < 100
a) Display even
b) Set even even+2
Step5: End
7) Design an algorithm which generates even numbers between 1000 and 2000 and then prints them in the
standard output. It should also print total sum:
Step 1: Start
Step2: input/read value of n
Step3: Set even 1000
Step4: Do the following until even < 2000
a) Display even
b) Set even even+2
Step5: End
8) Define the following symbol and use?
Answer: Process Box: A process box is used to represent all types of mathematical tasks like addition,
subtraction, multiplication, division, etc.
9) Algorithm to find area of a rectangle?
Algorithm:
Step 1: Start
Step 2: Take length and breadth and store them as L and B? // Input
Step 4: Multiply L and B and store it in area //Area of Rectangle = L*B
Step 5: Print area //Output
Step 6: Stop.
10) Write an algorithm to find the largest among three different numbers entered by user with flowchart
Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a greater than b
a) If a greater than c
i) Display a is the largest number.
b) else
i) Display c is the largest number.
Step 4: else
a) If b greater than c
i) Display b is the largest number.
b) else
i) Display c is the greatest number.
Step 5: Stop
Multiple Choice Questions:
1) An Algorithm is expressed by
a) Flowchart b) common language c) pseudo code d) all
2) A good algorithm having finite steps?
a) True b) False
3) Algorithm efficiency is measured by?
a) Speed b) space c) code d) all of the above
4) How many control structures are there in algorithm?
a) 3 b) 2 c) 1
5) Which control structure used weather a condition is true or false?
a) Selection b) iteration c) sequence d) none
6) Which control structure used to check a condition more than one time?
a) Iteration b) loop c) a & b d) None of the above
7) In computer science, algorithm refers to a pictorial representation of a flowchart.
a) True b) False
8) The process of drawing a flowchart for an algorithm is called __________
a) Performance b) Evaluation c) Algorithmic Representation d) Flowcharting
9) Actual instructions in flowcharting are represented in _________
a) Circles b) Boxes c) Arrows d) Lines
10) A box that can represent two different conditions.
a) Rectangle b) Diamond c) Circle d) Parallelogram
11) The following box denotes?