CP Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

Department of Information Technology

Lab Manual

GE6161- Computer Practice Laboratory

Velammal College of Engineering and Technology


Madurai

Prepared By

Verified By

Mr.P.Suresh Babu

Ms.J.Mahalakshmi

[HOD/IT]

Table of Contents

Sl. No

Description

Page No.

1
2
3
4
5
6
7
7a

Motivation for the course


Objectives of the course
Outcomes of the course
Pre-requisites for the course
Instructions to Students
Syllabus of the course
Requirements
Additional Reading: Some recommended productivity
software for students

3
4
5
6
7
8
9
10

7b

Additional Reading: Some useful technology news


websites for students to browse regularly

12

Ex.No.1 Search, Generate and manipulate data using MS


Office (Word)/OpenOffice

14

8a

31

Introduction to Open Source Office Suites


Ex.No.2 Presentation and Visualization Graphs, Charts,
2D, and 3D
Ex.No.3 Problem Formulation, Problem Solving and
Flowcharts
About Dennis Ritchie - Beyond Syllabus

11

Introduction to C programming

57

11

Working with C in Visual Studio 2010

58

12

Ex.No.4 C Programming using simple statements and


expressions
Ex.No.5 Scientific problem solving using decision
making and looping
Ex.No.6 Simple programming using 1D and 2D arrays

65

Ex.No.7 Solving problems using string functions


Ex.No.8 Programs with user defined functions includes
parameter passing
Ex.No.9
Program using recursive function and
conversion from given program to flow chart

83
87

Ex.No.10 Program using structures and unions


List of reference materials
Reference materials for Beyond the Syllabus Arduino
Programming and useful links

95
98
99

9
10

13
14
15
16
17
18
19
20

35
46
52

72
79

92

Motivation for the Course

The goal of Computer Practice Lab is to provide an introduction to computer application


software and programming, and it is mainly concerned with Word Processing and
Spreadsheet application software, and basics of C Programming. A thorough
understanding of the course will provide students with a solid foundation to later core IT
courses like object-oriented programming (languages like C++, Java, and C#), the .Net
environment, data base management, computer networks, web technologies, and so on.
The use of MS Word for technical communication, mathematical equations, collaborative
authoring, and basic drawings is explained, so that students can start writing technical and
research papers.
The use of MS Excel for data presentation, visualization, and analysis is presented, so that
students can present, analyze, and visualize their data from experiments, projects, and
research.
MS PowerPoint is used as a tool for oral technical communication.
The students are introduced to study of programming using C, as it is one of the most
versatile, powerful, and useful high-level programming languages. Students are given
extensive examples and exercises in applying logical thinking to program development.
Debugging is also taught in this course, as it will help the students to improve their
reasoning and logical thinking capabilities.
To make the learning of C interactive and fun, Beyond the Syllabus coverage of C
programming is presented with brief introduction to game programming, computer
graphics, and animation, as well as physical computing through the use of open source
microcontroller Arduino. Interested students are encouraged to pursue these topics in
greater depth on their own.
A brief introduction to free and open source software (FOSS) like Libre/Open Office,
Scilab, and other packages is given, with bonus marks for those who pursue these topics
in some depth on their own.

Objectives of the Course

To introduce Microsoft Word 2007 and its features. Students are trained in Microsoft
Word 2007 for document preparation, text manipulation, equation editing, table creation,
formatting, and conversion, drawing diagrams and flowcharts, mail merge, and letter
preparation.

To introduce Microsoft Excel 2007 and its features. Students will be taught to enter,
export and import data, use formulas, chart preparation and chart conversion in Microsoft
Excel 2007.

Basics of C language are taught to the students. Concepts such as data types,
expressions, decision making, looping, arrays, structures, unions, functions, pointers and
file handling are dealt in this course.

Outcomes of the Course

Students will be able to document their reports and assignments using Microsoft Word
2007.

Students will be able to input and plot data on a Microsoft Excel 2007 spreadsheet and
analyze the data through use of charts and formulas.

Students will be proficient in the basics of C language and its constructs.

Students will be familiar with the use of the Microsoft Visual Studio 2010 IDE for
executing and debugging their C programs.

Students will be equipped to model a software solution for real time problems.

Student will be able to demonstrate hardware interfacing with C using the open source
Arduino platform (Beyond the Syllabus material).

Prerequisites for the Course

Basic mathematical knowledge and computer usage skills.

INSTRUCTIONS TO STUDENTS:
Format of Experiments:
The lab instructions include the following:
Title Title of the experiment.
Objectives What does the student learn from the experiment.
Concepts Involved A brief introduction about the concept for the experiment.
Procedure Steps to perform the experiment.
Output Output of the experiment in screen shots.
Results & Discussions Answers to the questions in the Procedure section and results.
Student Lab Report
1. For each experiment, it is expected each student writes a report to:
Answer questions in the instruction sheet.
Explain her/his observations from the experiment.
Analyze the results collected from the experiment.
2. Your report should be presented in MS Words.

3.
4.
5.
6.

Not more than 10 pages.


Single spacing, font size-12, Times New Roman.
At least 1 inch margin on each side.
Each student is expected to analyze the issues and understand for her/his benefit.
Every student is instructed to bring laptops of their own to work during lab sessions.
The coding and output for every student should differ.
The lab report for every experiment needs to be submitted the very next week.
For late submissions the mark will be reduced as follows:

1 day- 1 mark
2 days- 3 mark
3 days- experiment will not be signed

7. Students are expected to do mini projects which will be allotted to them and they will
be awarded bonus marks for that.
8. Viva session will be there in every lab class for which you will be awarded 10 marks.
Mark allotment for experiment:
Total: 30 marks
Viva: 10
Performance: 10 (includes the output)
Record: 10
Note: If there is uniformity of code and output of the program the student will
be allowed to continue to do the lab.

not

Syllabus of the course


GE6161

COMPUTER PRACTICES LABORATORY

LTPC
0032

LIST OF EXPERIMENTS

1. Search, generate, and manipulate data using MS office/Open Office


2. Presentation and Visualization graphs, charts, 2D, 3D
3. Problem formulation, Problem Solving and Flowcharts
4. C Programming using Simple statements and expressions
5. Scientific problem solving using decision making and looping.
6. Simple programming for one dimensional and two dimensional arrays.
7. Solving problems using String functions
8. Programs with user defined functions Includes Parameter Passing
9. Program using Recursive Function and conversion from given program to Flow
Chart.
10. Program using structures and unions.
TOTAL: 45 PERIODS

Requirements
Microsoft Office/OpenOffice

Microsoft Word 2007

Microsoft Excel 2007

Microsoft PowerPoint 2007

Microsoft Visual Studio 2010

Some Recommended Productivity Software for Students


Students are encouraged to download and install the following software on their laptop
PCs to improve their computer skills.
1. PrintScreen software - Gadwin PrintScreen
Students will be required to include 'screenshots' of their programming exercises showing
the source code, results, or errors. Freeware version of Gadwin PrintScreen can be downloaded
from
http://www.gadwin.com/download/ - for making convenient screenshots.

2. Screen Recorder software - CamStudio


For oral presentations of projects/research papers as well for explaining results to the
faculty-in-charge, students are encouraged to download and install open source (meaning free;
see http://en.wikipedia.org/wiki/Open_source) CamStudio software, from http://camstudio.org/
Several videos posted on sites like YouTube and Khan Academy (www.khanacademy.org) are
made using CamStudio.
3. PDF file printer - PDFCreator
It is convenient for students to print out useful information like web pages for later
reference, in the form of PDF files which are not so easy to modify as MS Word. You can use
PDFCreator available at
http://sourceforge.net/projects/pdfcreator/

This program allows you to create PDF files from any Windows program, and is used as a (soft)
printer.
Note: Sourceforge.net is the Web's biggest repository of open source, free, and shareware
programs. You are encouraged to browse through some of its vast collections, and try out any
program that you might find interesting.
4. PDF file merge program - PDFMerge
Available from
http://www.pdfmerge.com/

This program can be used to merge multiple, PDF files for convenient access as a single file.
5. CD/DVD burning software - InfraRecorder
Available for download from
http://infrarecorder.org/
10

This open source software is useful for burning data/audio/video files to CD/DVD, as well as to
create 'image' of a CD/DVD as .iso file (which contains all the information contained on a
CD/DVD).
6. Audio editor and recorder software - Audacity
Available at http://audacity.sourceforge.net/
It is an open source software which can be used to record audio input and edit audio sounds/files,
on the PC.
7. Image Viewer - IrfanView
Available at
http://www.irfanview.com/

IrfanView is a free, fast, and compact program to view images in many popular files and to create
slideshows of multiple images. It can be also used for limited image modifications.
8. Multimedia viewers: Apple QuickTime, iTunes, Windows Media Player, RealPlayer, VLC
Media Player
9. Archiving and data compression software - 7-zip (free), WinRAR (shareware)
10. Typewriting tutor software - TypeFaster
If you are going to be typing for hours a day on your PC, and for years to come, it makes
sense to learn the basic keyboard layout so you type faster with less error, and reduce the pain on
your fingers and wrists! Available at
http://sourceforge.net/projects/typefaster/

CAUTION: While downloading and installing software from the Web, students are urged to
watch out for virus and malware that could slow down or even damage their PC, and watch out
for unintended installation of additional programs!

11

Some Useful Technology News Websites for Students to Browse Regularly


Students are encouraged to regularly browse the Internet for current news on technology
websites to keep themselves informed of the latest developments in their field. Some useful sites
are listed below and students are encouraged to find other similar websites that they find
interesting. If you find any articles that you feel will be of interest to your faculty or fellow
students, feel free to email the links to them using your class Google Group ID. You can
bookmark interesting articles for later access, or save them as PDF files (e.g., with PDFCreator).
A convenient way to browse these sites fast on a regular basis is to use browser
extensions, e.g., Daily Links in Google Chrome.

In Firefox, the browser add-on Morning Coffee can be used for this purpose:

1. New York Times Technology page: http://www.nytimes.com/pages/technology/index.html

12

The NY Times is the world's most well-known newspaper and contains articles on stateof-art R&D from the world's leading universities, research laboratories, and tech companies.
2. BBC News Technology: http://www.bbc.co.uk/news/technology/
Contains articles and videos on current technology developments.
3. Wired magazine: http://www.wired.com/
Contains latest news on computers, Internet, games, and gadgets.
4. Ars Technica: http://arstechnica.com/
Leading source of news on computers, software, IT, and has many forums and blogs for
programmers and developers.
5. Computer World magazine: http://www.computerworld.com/
Source of news on computer technologies, and has related websites like
www.infoworld.com, www.networkworld.com, www.javaworld.com, etc. Focuses mainly on
software, IT networking and administration, and programming including quizzes and interview
questions.
6. IEEE Spectrum Magazine online: http://spectrum.ieee.org/
The Institute of Electrical and Electronic Engineers (IEEE) is the world's largest
professional society of electrical, electronics, and computer engineers. The Spectrum is its
magazine devoted to covering technological developments at a level accessible for undergraduate
students.
7. Crossroads The ACM Magazine for Students: http://xrds.acm.org/
The Association for Computing Machinery (ACM) is the world's leading society of IT
professionals. Needs student membership of ACM for access!
8. Make Magazine online: http://makezine.com/
Make magazine is devoted to promoting a culture of do-it-yourself (DIY) making of
gadgets, robots, games, and other projects, by engineers, college and high school students, as well
as hobbyists. It promotes open source hardware and software technologies through these projects.
9. http://www.instructables.com/
This site is similar to Make magazine online, but covers more general areas, in terms of
projects.
10. TED (Technology, Entertainment, Design): http://www.ted.com/
Contains several video talks on technology and related areas by achievers ranging from
scientists and engineers to laypersons and high school students. Students can download them,
with subtitles, for later viewing.
13

14

Experiment 1
Search, Generate and Manipulate data using MS Office/ OpenOffice
Aim:
To learn and apply features of MS Word 2007 for the preparation of documents for
different purposes such as writing papers, resumes, and cover letters.
Concepts Involved:
To open MS Word 2007: Start All Programs Microsoft Office Microsoft Office Word 2007.
Searching for a keyword:

Word's Find and Replace function will search your documents for specific text (words, phrases,
etc), which will then be highlighted and can be replaced with different text.

To find any text, you must first access the Find and Replace dialog box. From
the Home command tab, in the Editing group, click FIND. Or as a shortcut, you can simply Press
[Ctrl] + [F].

From the Home command tab, in the Editing group, click REPLACE or Press [Ctrl] + [H] .
The Find and Replace dialog box appears, with the Replace tab displayed.

1. After highlighting the text, the Font tab can be used to change the font size/color/style
(bold text, italic text, underline, or their combinations).

15

2. After selecting a particular paragraph, text can be aligned to the left, right, center or
justify and use bullets, color the background behind the selected text.
Advice: Students should note that the preference in typesetting is for jagged right justify
([Ctrl]+L) rather than (full) justify ([Ctrl]+J[]). The latter is considered ugly due to uneven
spacing among words to justify the text on both left and right sides. See
http://www.chicagomanualofstyle.org/qanda/data/faq/topics/ManuscriptPreparation/faq00
41.html

3. To find a particular word from this document, editing option can be used. Here Find,
Replace and Select options available.
Insert menu:
Pages can be aligned through page break, blank page, and cover page.

Creating a Table:
Step 1: Click the word document where the user wants to insert the table and go to insert
menu. Select Table under Tables then click Insert Table.

Step 2: Enter the number of columns and rows for creating a table and then click OK.

16

Step 3: Enter the data into the table. You can right-click on the table or on the + at the top
left of the table to modify the properties of the table.

Use of Illustrations and Tables: Illustrations can be used for drawing pictures, clip art,
shapes, flowchart symbols, and charts.

Use of Links: Links can be used to indicate hyperlinks and bookmarks.


Step 1: If user wants a hyperlink for a word, a phrase, or a line then select it and then go
to hyperlink from Insert menu.

17

Step 2: After selecting hyperlink, user choose the document to which you want to link.

Step 3: Now, Press Ctrl key and click the hyperlink word and it appears in the document.

Use of Headers and Footers: The Header & Footer menu under Insert can be used to insert
Header/Footer/Page Number for the document at specified locations.
18

Use of Symbols, Subscripts, and Superscripts: Symbols can be used in text and inline
equations (the equation is in the same line as a text), e.g., " is used to indicate ...".
However, when subscripts and superscripts are used this way, the interline spacing may
not be uniform, and text fonts are used for equation, e.g., a2x2 + a1 x + a0 = .
We can use the Equation Editor (see below) for entering complex equations, with default
equations available for quadratic equation roots, area of circle, binomial theorem, and
Fourier series.

Beyond The Syllabus:


Equation Editor:
Ref:
http://office.microsoft.com/en-in/word-help/insert-an-equation-using-equation-editorHP005190247.aspx

It is a formula editor that allows the user to construct math and science equations.
Step 1: Click where user want to insert the equation. On the Insert menu, click Object.

19

Step 2: In the object type box, click Microsoft Equation 3.0 and then click OK.

Step 3: Build the equation by selecting symbols from the equation and by typing variables
and numbers. From the top row of the equation toolbar, user can choose from more than
150 mathematical symbols. From the bottom row, the user can choose from a variety of
templates or frameworks that contain symbols such as fractions, integrals and
summations.

20

Step 4: To return to Microsoft Word, click the word document.

Track Changes:
Ref: http://office.microsoft.com/en-us/word-help/track-changes-while-you-edit-HA001218690.aspx
Track changes is a very useful editing command that is commonly used when a user
creates an original document and makes changes and want to keep track of the changes
that are made to that original document to accept or delete later. It is also a useful tool for
collaborating on a document, as it allows multiple users to make revisions without losing
the context of the original document.
Step 1: Select Track Changes under Review which allows user to see what changes have
been made to a document. The changes made appear in RED, with underlining, and a
vertical tab on the left side of the page on the corresponding line appears showing where
changes occur.

Step 2: If a user wants to incorporate the changes which are made to the original
document then select Accept above Changes tab in the Review menu. Otherwise select

21

Reject" above "Changes. You can also accept All Changes in the Document, to
incorporate all the changes in one step.

There are four ways to view a document after the tracked changes.

Final Showing Markup: This shows the document with the changes displayed
Final: This shows the changed document, without the changes displayed
Original Showing Markup: The original document with the changes displayed
Original: The original document without any changes.

Adding and Deleting Comments:


Ref: http://office.microsoft.com/en-in/word-help/insert-or-delete-a-comment-HA001219010.aspx
The New Comment icon lets users add comments to the document. To add a new
comment, place the cursor where the comment is to be added and click on New
Comment. The new comment appears on the right side in an ellipse, in which the
comment text can be added. To delete the comment, right-click on the comment and
select "Delete Comment".

22

How to use Spell Check and Grammar Check?


Ref: http://office.microsoft.com/en-in/word-help/check-spelling-and-grammar-HP010117963.aspx
Step 1: On the Review tab, in the proofing group, click on Spelling and Grammar or press
F7.
Step 2: If the program finds spelling mistakes, a dialog box or task pane appears with the
first misspelled word found by the spelling checker.
Step 3: After you resolve each misspelled word, the program flags the next misspelled
word so that you can decide what you want to do.
Step 4: In Outlook or Word only, after the program finishes flagging the spelling
mistakes, it shows you the grammar mistakes. For each mistake, click an option in the
Spelling and Grammar dialog box.
IMPORTANT!!! How to turn on automatic spelling and grammar checking:
Step 1: Click Microsoft Office Button, select word options and then select
Proofing tab.
Step 2: Under Exceptions for, click name of currently open file.
Step 3: Select or clear the Hide spelling errors in this document only and Hide
grammar errors in this document only checkboxes.
Red and Green Underline in MS Word:
In Microsoft Word, wavy red underlines are used to indicate possible spelling
errors and wavy green underlines are used to indicate possible grammatical errors in a
document. If user wants to alter the default color such as red and green then refer the
following link: http://support.microsoft.com/kb/925597
For example, user can enter a name R.Dennis. It shows red underline. It will
overcome by leaving a space after dot and right click on it and select add to dictionary.
Web Page Creation in MS Word:

23

Webpage Creation Using MS Word

Follow the instructions in one of the two PDF files posted on


Lectures folder:
How to Make a Website With Word
Creating Web Pages in Word 2007
Save your web page in a default directory as file index.html
Add hyperlinks in the page to web pages of your choice
Open your web page file index.html and verify that the links
work
Practice adding images (photos, clip art, etc) and videos to
the page
You will need web access to a site to upload your web pages
for them to be seen over the WWW
1

Practice Problem

Create an 1-page Resume of yours as a web page.


You can add information on your work as links to the
page
See the sample handout from the earlier class, or the
sample CV (image) on the next slide for reference
You can make changes to the page in Word, save, and
refresh the page in the browser to see the changes
Explore the MS Word ribbon to experiment with
editing your page (e.g., background color, image,
borders, etc.)

24

Practice Problem (contd.)

Open the index.html file in a text editor (e.g.,


NotePad) to see the instructions/code in the
HyperText Markup Language (HTML).

This helps you understand why WYSIWYG


approach is so easy to use!
However, there are limits to using WYSIWYG
software

You can View the page in Print Layout format


to see how the page will print (i.e., without
background color or image)
5

Practice Problem (contd.)

For any additional editing issues, you can try using


online search, e.g., how to add background image to a web
page using MS Word

Alternatives to MS Word-based web page editing:


Mozilla SeaMonkey internet application suite (includes
Editor), Adobe Dreamweaver, etc
For more information on the technologies web pages
and their creation, see for example:
http://en.wikipedia.org/wiki/Web_page
http://en.wikipedia.org/wiki/HTML_editor

25

Practice Problem (contd.)

Courses are available (e.g., CMPS) on


advanced aspects of web authoring
Web site building and management tools are
available for end-users, e.g., open source on
SourceForge.net
Wikis allow online interactive collaboration and
authoring using a web browser or WYSIWYG
editor, e.g., parents of students in a class with
the teacher, students of a course, etc
7

Drawing in MS Word:
Step 1: Click in the document where user wants to create the drawing.
Step 2: On the Insert menu, select shapes or picture in the illustrations. Use the format
menu to add any shapes that user want.

MS Visio: It provides diagramming capabilities to prepare various business, engineering,


software and database, architecture and network diagrams. It also prepares Flowcharts
and UML (Unified Modeling Language) diagrams like Activity, use case and state
machine diagrams. It is easier to use than MS Word, as it has many libraries of ready-touse shapes and icons.
26

An open source alternative to MS Visio is Dia, available at


https://projects.gnome.org/dia/

Reference: See
http://www.ncsu.edu/labwrite/index_labwrite.htm - for descriptions of Pre-, In-, and Post-

lab activities, and how to write lab reports.

Pre Lab Exercises:


1. Open a new document in MS Word and perform the following tasks:
i. Write a Self-Introduction paragraph of text (about 100 words) and justify or left
align the text.
ii. Make some of the text as bold type, e.g., names.
iii. Correct any spelling mistakes, and add new words to the dictionary (e.g., your
name!).
iv. Use underline and/or italic style for some words.
v. Save the document with a suitable name (file name starts with upper case, avoid
all upper case file name!).
2. Create a table for four students with the following columns and display the results in
separate cells for the following: students name, address, phone number, and email ID.
Reference: Office 2013 All-In-One For Dummies by Peter Weverka
Free eBook available at http://it-ebooks.info/book/2120/
The book covers the latest, 2013, edition but many of the points apply to older versions.

In Lab Exercises:
1. Prepare a one-page resume which describes your career objective, qualifications, prizes,
extracurricular, co-curricular activities, and personal details. (Refer the following format
as a template, or find one online that you like!)

27

Web Resources:
a. http://akrion.net/short-1-page-resume-template/
b. http://career-advice.monster.com/resumes-cover-letters/resume-writing-tips/onepage-or-two-page-resume/article.aspx

28

2. Prepare a cover letter for an interview for an internship position (e.g., in BSNL during
your semester vacation for two weeks).

Web Resources:
a. http://owl.english.purdue.edu/owl/resource/723/03/
b. http://susanireland.com/using-a-resume-cover-letter-template/
c. http://www.career.vt.edu/jobsearchguide/coverlettersamples.html
3. Create a one-page document which describes your field, Information Technology.
4. Write the following equations in your document.
i. Ca (HCO3)2 CaCO3 + CO2 +H2O ("in-line" equation)
ii. (A+B) 2 = A2 + B2 + 2 AB (both as in-line equation and using Equation
Editor; see the difference in the two equations!)

iii.
iv.
4 9 4

v. Enter a 33 matrix, e.g., 3 3 1


7 8 3

29

Post Lab Exercises:


1. Write a 1/2-page essay about open source microcontroller Arduino, viz., what it is, what it
does, some of its advantages, and limitations. Use single space, 12-pt New Times Roman
font, with 1-inch margin on all sides.
IMPORTANT: Read the reference article Ctrl+C, Ctrl+V and ensure that you do not
simply copy from unsourced materials!
2. Fold an A4 sheet to form a box. Calculate (approximate) maximum volume possible for
such a box using differential calculus. Draw the box in MS Word and write the relevant
equations using Equation Editor. Look at your Physics or Math text book, to see how to

use descriptive English with your math!

Viva-Voce Questions:
1. What is WYSIWYG?
2. List out major open source alternatives to MS Office. What are advantages and
disadvantages? (Bonus marks will be 15% for installing the alternate software on your
laptop, and producing a sample document).
3. How will you read a document created with a new version of MS Word if you have an
older version of MS Word?
4. How will MS Word help you to compare two similar documents?
5. Can you keep different versions of a document in the same file? Explain your answer.
6. How will you count the number of words, characters, lines, and paragraphs in an MS
Word document?
7. What shortcut key will you use to jump to a specific page in MS Word?

Results and Discussion:


1. I pressed 'Enter' several times to start a new page. But my new page is not aligned
properly. What should I do?
2. How will you select a word in a document without using the mouse?
30

3. State how MS Word will be terminated and the document will be recovered if MS Word
hangs or the PC power goes out?
4. Explain how a single document can be created by combining a number of word
documents?

31

Introduction to Open Source Office Suites


Ref: http://www.digitaltrends.com/computing/best-microsoft-office-alternatives/
BEST FREE MICROSOFT OFFICE ALTERNATIVES:

Microsoft Office was once the go-to source and industry standard for office productivity
applications. As the office suite landscape continues to change and evolve, were seeing more and
more open source software springing up that lack little in the way of features and provide free
alternatives to the productivity king that dominated the market for years on end.
Whether youre at home or on the road with your mobile device, word processing, spreadsheets,
presentation software, and more are now all accessible anywhere you have an Internet
connection. Its been a long time coming, but the reign of Microsoft Office is drawing to a close.
While you could use Microsofts free Office Web Apps, weve rounded up six of our top picks
for some of the best Microsoft-free alternatives so you can carry out basic office tasks without
paying a cent. These resources will make it easy to continue hammering out those word docs,
spreadsheets, and presentations while keeping your wallet at bay.

Google Docs

Google Docs is at the forefront of open office software for many reasons just check out our
piece on why Gmail is awesome if you have any qualms regarding the software. It has all the
basic perks of Microsoft Office word processor, spreadsheets, and presentation capabilities
32

but its completely free and accessible online through Googles cloud-based storage service,
Google Drive. It provides a nice, central hub for all your documents, and the sheer potential for
collaboration makes the software a stand out among the rest. You can create, share, and edit
documents with anyone, regardless of whether they have a Google account. Also, the ability to
view document changes in real time even those made by several people at once in the same
document has its advantages.

From Microsoft Word documents to PDFs, Google Docs supports a wide array of file types, all of
which can be downloaded for offline use. Added perks include image editor Google Drawings,
and online form creator Google Forms. Plus, Google Docs works well with other Google services
like Google+, Gmail, and Google Calendar for greater integration capabilities and convenience.
Although the program is free, you can upgrade from the allotted 5GB of space for a mere $2.50 a
month. Be sure to download the Google Drive app for Android and Apple devices to access your
files on your mobile device.

OpenOffice

OpenOffice is one of the more renowned pieces of open source software on the market and has
been so for more than 10 years. The bundle contains tools for word processing, spreadsheets,
presentations, graphics, databases, and a slew of other capabilities. The software can be
downloaded and used completely free of any licensing fees and stores your data in an
international open standard format. It can also read and save Microsoft Word documents so you
dont have to sweat over any compatibility issues.

33

The current version of OpenOffice offers a treasure trove of developer extensions and supports
most common operating systems, including Microsoft Windows, Mac OS X, and GNU/Linux.
Its not as advanced for collaboration as Google Docs, but the package offers a solid line of
productivity tools that are frequently updated with new features.

LibreOffice

LibreOffice is essentially an open office suite that parted ways with Apache OpenOffice back in
2010. It uses the same underlying source code under the hood, features the same basic
productivity tools as OpenOffice, and even works in a similar manner. The major difference
between the two is the increased amount of development the Document Foundation has poured
into the LibreOffice software over the years. LibreOffice showcases a few more advanced
features, such as a Wiki publisher, and offers greater functionality given the available extensions
and customization options. Its fairly intuitive, simple to use, and dons a modern design that
comes up just short of Microsoft Office.

34

The current version of LibreOffice supports most common operating systems, including
Microsoft Windows, Mac OS X and GNU/Linux. The software can even be installed on a
portable drive or SD card so you can throw it in your pocket before you head out. A mobile app
for Android and Apple devices is also in the works.

35

Experiment 2
Presentation and Visualization Graphs, Charts, 2D & 3D
Aim:
To learn and apply basic features of MS-Excel for data visualization, and MS-PowerPoint
2007 to develop a presentation.

Concepts Involved:
What is MS Excel?
It is spreadsheet program, the computerized equivalent of a ledger. It is part of the MS
Office suite, and is used to analyze worksheets and workbooks. Its menus, toolbars, and dialog
boxes are similar to MS Word.
Applications of Excel:
Number crunching (analyze data)
Creating charts, diagrams, and graphics
Import data for processing (e.g., from MS Access)
Organizing lists (e.g., tables of data)
Automating complex tasks (using macros)

An MS Excel consists of a workbook, consisting of one or more worksheets. Each


worksheet consists of horizontal rows and vertical columns of cells. The first column is usually
used for independent variable, (e.g., time) and the columns to its right are used to enter dependent
variables. Enter the data for chart which user moving to plot and then select insert menu. The cell
in which data is currently being entered is called the active cell.
The three data types in Excel are labels, constants, and formulas. Formulas are used to
perform mathematical operations and arrive at a calculated result in the active cell. It begins with
an equal sign (=). The entry being made in the active cell appears in the formula bar to the right
of the name box, as shown below. The default name of the worksheet can be changed, and
As in the case of MS Word, MS Excel also has very useful Help option. So, if you need
to find out how to use a formula for a specific operation (e.g., find the average of a range of
numbers), you can simply use Help.

36

Steps for creating charts in MS Excel:


Step 1: Start All Programs Microsoft Office Microsoft Office Excel 2007.
Enter the data of interest in the chart, starting with the left-most column moving to the
right. For clarity, you can add labels for each column of data at the top. You can also format
the data in each column (e.g., change font type, color, size, fill, etc) without affecting its graph.

Step 2: Select the data range of interest (including labels), by click and drag from top left to
bottom right of the range of cells. Next, click on Insert on the menu bar, and select the type of
chart/graph (Column, Line, Pie, Bar, Scatter (x-y graph)) desired.

37

Step 3: The chart will appear, e.g., 2D or 3D column chart.

Step 4: Complete the chart by giving labels for x and y axes, change default a suitably, and
give a title above/below the graph, as shown below.

38

Beyond The Syllabus:


Formula Usage: Much of the power of Excel comes from its built-in formulas which can
be applied to user data. For example, the sum can be calculated as shown, similarly mean (or,
average) is calculated using the formula =AVERAGE(B3:B14) for B16.
.

Some of the commonly used functions are sum, average, max, min, count, sin, cos, tan, if,
and etc.
Syntax:
FUNCTION
=Sum (first value, second value, etc)
=Average (first value, second value, etc)
=Max (first value, second value)
=Min (first value, second value)
=Sin (value)
39

EXAMPLE
=SUM (A2:A4)
=Average (A2:A5)
=Max (A2, A4)
=Min (A2, A3)
=Sin (A2)

=Cos (value)
=Tan (value)
=IF (condition, value-if-true, value-if-false)

=Cos (A2)
=Tan (A2)
=IF (A2>50, Pass, Fail)

Use of Secondary Y-Axis:


If there are two dependent variables in a dataset (e.g., area of circle and volume of sphere
for a given radius), and the second dependent variable has a different type or order of
magnitude from the first, for clarity it can be plotted along the secondary Y axis (on the right).
To do this, select the corresponding data series, on the format menu click selected data series,
on the Axis tab, click Secondary Axis.

Comments:
1. Instead of entering radius values in sequence manually, I used a formula (A9=A8+1) to
increment them. Then, I dragged the "fill handle" (at bottom right of cell A9) all the way to A18
to fill in the remaining radius values automatically.
2. I wrapped the text in above comment manually by Enter, so all the content remains in the same
page; I can verify this by clicking Page Preview icon on the menu bar.
3. I have beautified the spreadsheet by using font selection, borders, etc!
4. I have done reducing the width of column A manually.
5. I have reduced the number of decimal places to 3 in Column B, by right clicking on column B,
select Number under Category, and choose 3 under Decimal places.
6. The little red triangle on the top right of cell F6 shows there is a Comment there. You can view
this comment simply by placing the cursor in that cell.
40

With both A and V plotted along the primary axis, the graph appears as above.
For the above graph/chart, I selected the cells in range A7 to D18, clicked insert under manu,
Scatter with Smooth Lines under Scatter under Charts. Due to the different scales of variation, I
cannot see Circumference data well. So, I need to move V to be shown on the Secondary Y axis.
To do this, I click on the graph for V and data points are highlighted. Next, I right click the mouse
on the graph, and in the pop-up menu (left) click on Format Data Series. In the Format Data
Series window that now appears, under Series Options on the left, I click on Secondary Axis on
the right, and select Close. Now, the V data curve is redrawn with Secondary Y-axis. If at any
stage you make a wrong selection, simply press ESC!

Questions: How did I remove the three decimal place zeros on y-axis? Add suitable x and y axis
labels, add a title to the figure (centered above and font- changed), and change the legend (e.g., C
Circumference, etc). Resize the figure suitably, and try adjusting or removing the grid lines.
41

Note: While submitting Excel homework, students are advised to submit both the data table (and
screenshot, if relevant) and the graph. As in the example above, show any formulas used and print
out the column and row headings so that the Instructor can see how the formulas are applied.
To print the column and row headings, click on Page Layout on the menu bar, and under
Sheet Options, click the box next to Print under Headings. The printout will appear as below:

Steps for creating PowerPoint Presentations:


Step 1: Open PowerPoint. StartAll ProgramsMicrosoft Office Microsoft Office
PowerPoint 2007.

Step 2: Create your first slide. Select Layout in the Home menu. From this, select the layout
which will satisfy the user to prepare the presentation.

42

Step 3: Add a new Slide. It can be done either by clicking the New Slide button in the top
toolbar, or by typing Ctrl+M, or by right click on the first slide and select net slide.

Step 4: Add Content on slides. Content can be added using Insert menu and choose the type
of the content that user want to add to that slide.

43

Step 5: Change slide themes or backgrounds. To choose a theme, Select themes from the
design menu.

To choose a background, Select Background Styles

Step 6: View slideshow. To view the final PowerPoint, Click Slide Show in the top toolbar or
press F5.

44

Reference: Refer to the file Technical Communication PPT for some basic information and
advice on how to prepare your written technical reports/papers using MS Word, and oral
presentations using MS PowerPoint.

Pre Lab Exercises:


1. Enter the following monthly projected sales data in a worksheet and plot column, bar, line,
pie, and scatter charts/graphs for the data. Also, calculate the total (annual) sales, minimum
and maximum sales, and average monthly sales using Excel formulas. Explain how to autogenerate months, i.e., Jan, Feb, etc.
Month

Projected Sales

Jan

50,000

Mar

75,000

May

98,000

July

125,000

Sep

200,500

Nov

250,900

In Lab Exercises:
1. On a long trip, you average 62.5 kmph, complete the following table and graph the
function as a line chart.
0
1
2
3
4
5
6
7
8
Hours
Travelled
Miles
Traveled
2.

62.5

Prepare a PPT presentation


about yourself (PPT must contain 5 slides). PPT describes about welcome slide with
proper animation, biography (place of birth and family), schooling, hobbies and goals.
45

Post Lab Exercises:


1. Prepare a 6-slide presentation about Arduino Programming.
2. Refer to the Post Lab exercise (4) of first experiment and plot a graph of box height
versus volume in MS Excel to find the maximum volume of a box. [Mention x-axis
label (box height, cm), y-axis label (volume, cm^3), series and units of each axis;
Hint: use formula to find max]
3. Present your solutions to Post-Lab Exercise (4) of Expt-1 and its Excel solution above
as six PPT slides.

Viva Questions:
1. How will you add animation to your MS PowerPoint for slides?
2. How will you add graphics, movie clips and audio files to a PowerPoint file?
3. Is there a way to make your own animation and play them in PowerPoint?

Results and Discussion:


1. Why don't sound/movie files play when I move my file to another computer?
2. Is it possible to generate the random number in MS Excel? Justify your answer.
3. Explain how to use fill handle to copy contents or formulas in a cell to contiguous cells.
As examples, automatically generate serial numbers, days of the week, and month names.
4. Explain how we can freeze the top row and left-most column in Excel file. This will come
in handy when the worksheet data is spread out beyond the opening screen.

46

Experiment 3
Problem Formulation, Problem Solving and Flow Charts
Aim:
To draw flow chart for problems using Microsoft Word 2007.

Concepts Involved:
Ref: http://en.wikipedia.org/wiki/Flowchart
Method of problem solving:

Recognize and understand the problem


Accumulate facts
Select appropriate theory
Make necessary assumptions
Solve the problem
Verify the results

The following five steps are used in a computer as a problem solving tool.
1.
2.
3.
4.
5.

Develop an algorithm and a flowchart


Write the program in a computer language
Enter the program into the computer
Test and debug the program
Run the program, enter input data, and get the results (output) from the computer.

Flowcharts:
It is a graphical representation of any program and it is helpful for understanding the
complicated process.
Guidelines for drawing flowcharts:

Flowcharts are usually drawn using some standard symbols. Some special symbols can
also be developed when required.
Some standard symbols are frequently required for flowcharting many computer C
programs.

Standard Symbols:

The major symbols are Decision (Selection) and Sequence (Process) symbols. Start and
Stop symbols are called Terminals. The Sub process symbol is a variation on the
sequence symbol. There are also connectors drawn between the symbols. For connectors,
we are using arrow i.e
47

START / STOP

SEQUENCE

DECISION

SUB SEQUENCE

Steps for drawing a Flow Chart Using MS Word:


Step 1: Start All Programs Microsoft Office Microsoft Office Word 2007. Select the
insert menu then click the shapes in the illustration. Select the required shapes.

Step 2: Plot the shapes into the document area.

48

Step 3: To add content into the shapes, right click on the shape and select Add Text.

Step 4: Use the connector (i.e. ) to show the sequence of steps to be executed by the programs.

49

Step 5: Decision box is used to check the condition. It has either yes or no option.

The same procedure is applied to draw a flow chart in MS Excel also.

Pre Lab Exercises:


1.
2.
3.
4.

Draw a flow chart to find the sum of the first 50 natural numbers.
Draw a flow chart to find the largest among three numbers.
Draw a flow chart to check whether a given number is odd or even.
Draw a flow chart for search prime number.
50

In Lab Exercises:
1.
2.
3.
4.
5.

Draw a flow chart to find a factorial of a number.


Draw a flow chart to find Fibonacci series for a given number.
Draw a flow chart to find exponent of a number.
Draw a flow chart to print Triangle of numbers.
Draw a flow chart to check whether the given number is perfect or not.

Post Lab Exercises:


1. Draw a flow chart to check whether a given number is Armstrong or Not.
2. Draw a flow chart to check whether the given two numbers are Amicable or not.
3. Refer the Post-lab exercise (4) of Expt-1 and draw a flow chart to find the maximum
volume of a box.

Viva Questions:
1.
2.
3.
4.
5.

Define Flow Chart.


Are there any limitations for flow charts?
List out the types of Flow Charts.
What are the guidelines for drawing a flow chart?
What is the purpose for using flow chart?

Results and Discussion:


1. Which step of the flow chart is redundant?
(A) Largest A
(B) C>Largest
(C) Largest B
(D) None.

2. What will be the output of the following flowchart?


START

INPUT A, B, C

LARGEST A

YES

B > LARGEST
NO
51

LARGEST B

YES

C > LARGEST
NO

OUTPUT LARGEST VALUE IS


LARGEST

STOP

52

LARGEST C

About Dennis Ritchie:


http://www.nytimes.com/2011/10/14/technology/dennis-ritchie-programming-trailblazer-dies-at70.html?_r=0
Dennis Ritchie, Trailblazer in Digital Era, Dies at 70
Dennis M. Ritchie, who helped shape the modern digital era by creating software tools that power
things as diverse as search engines like Google and smart phones, was found dead on Wednesday
at his home in Berkeley Heights, N.J. He was 70.

Victoria Will/Associated Press Images for Japan Prize Foundation

Dennis Ritchie received the 2011 Japan Prize in May.

Mr. Ritchie, who lived alone, was in frail health in recent years after treatment for prostate cancer
and heart disease, said his brother Bill.
In the late 1960s and early 70s, working at Bell Labs, Mr. Ritchie made a pair of lasting
contributions to computer science. He was the principal designer of the C programming language
and co-developer of the UNIX operating system, working closely with Ken Thompson, his
longtime Bell Labs collaborator.
The C programming language, a shorthand of words, numbers and punctuation, is still widely
used today, and successors like C++ and Java build on the ideas, rules and grammar that Mr.
Ritchie designed. The UNIX operating system has similarly had a rich and enduring impact. Its
free, open-source variant, Linux, powers many of the worlds data centers, like those at Google
and Amazon, and its technology serves as the foundation of operating systems, like Apples iOS,
in consumer computing devices.
53

The tools that Dennis built and their direct descendants run pretty much everything
today, said Brian Kernighan, a computer scientist at Princeton University who worked with Mr.
Ritchie at Bell Labs.
Those tools were more than inventive bundles of computer code. The C language and UNIX
reflected a point of view, a different philosophy of computing than what had come before. In the
late 60s and early 70s, minicomputers were moving into companies and universities smaller
and at a fraction of the price of hulking mainframes.
Minicomputers represented a step in the democratization of computing, and UNIX and C were
designed to open up computing to more people and collaborative working styles. Mr. Ritchie, Mr.
Thompson and their Bell Labs colleagues were making not merely software but, as Mr. Ritchie
once put it, a system around which fellowship can form.
C was designed for systems programmers who wanted to get the fastest performance from
operating systems, compilers and other programs. C is not a big language its clean, simple,
elegant, Mr. Kernighan said. It lets you get close to the machine, without getting tied up in the
machine.
Such higher-level languages had earlier been intended mainly to let people without a lot of
programming skill write programs that could run on mainframes. Fortran was for scientists and
engineers, while Cobol was for business managers.
C, like UNIX, was designed mainly to let the growing ranks of professional programmers work
more productively. And it steadily gained popularity. With Mr. Kernighan, Mr. Ritchie wrote a
classic text, The C Programming Language, also known as K. & R. after the authors initials,
whose two editions, in 1978 and 1988, have sold millions of copies and been translated into 25
languages.
Dennis MacAlistair Ritchie was born on Sept. 9, 1941, in Bronxville, N.Y. His father, Alistair,
was an engineer at Bell Labs, and his mother, Jean McGee Ritchie, was a homemaker. When he
was a child, the family moved to Summit, N.J., where Mr. Ritchie grew up and attended high
school. He then went to Harvard, where he majored in applied mathematics.
While a graduate student at Harvard, Mr. Ritchie worked at the computer center at the
Massachusetts Institute of Technology, and became more interested in computing than math. He
was recruited by the Sandia National Laboratories, which conducted weapons research and
testing. But it was nearly 1968, Mr. Ritchie recalled in an interview in 2001, and somehow
making A-bombs for the government didnt seem in tune with the times.

54

Mr. Ritchie joined Bell Labs in 1967, and soon began his fruitful collaboration with Mr.
Thompson on both UNIX and the C programming language. The pair represented the two
different strands of the nascent discipline of computer science. Mr. Ritchie came to computing
from math, while Mr. Thompson came from electrical engineering.
We were very complementary, said Mr. Thompson, who is now an engineer at Google.
Sometimes personalities clash, and sometimes they meld. It was just good with Dennis.
Besides his brother Bill, of Alexandria, Va., Mr. Ritchie is survived by another brother, John, of
Newton, Mass., and a sister, Lynn Ritchie of Hexham, England.
Mr. Ritchie traveled widely and read voraciously, but friends and family members say his main
passion was his work. He remained at Bell Labs, working on various research projects, until he
retired in 2007.
Colleagues who worked with Mr. Ritchie were struck by his code meticulous, clean and
concise. His writing, according to Mr. Kernighan, was similar. There was a remarkable precision
to his writing, Mr. Kernighan said, no extra words, elegant and spare, much like his code.
A version of this article appeared in print on October 14, 2011, on page A22 of the New York
edition with the headline: Dennis Ritchie, 70, Dies; Trailblazer in Digital Era.

55

http://articles.washingtonpost.com/2011-10-13/local/35277916_1_dennis-ritchie-charles-petzoldunix
Dennis Ritchie, founder of UNIX and C, dies at 70

Dennis Ritchie worked at Bell Laboratories for four decades, from his time (/ALCATEL-LUCENT)

Dennis Ritchie, 70, a computer scientist who changed modern technology by writing an elegantly
simple computer programming language, was found dead at his home in Murray Hill, N.J., his
former colleague Rob Pike said.
Pike received word Oct. 12 that Dr. Ritchies body had been discovered last weekend. A cause of
death was not immediately available.
As the news of his death spread throughout the computer science world, historians and computer
enthusiasts compared the bearded, introverted Dr. Ritchie to media-savvy Apple co-founder Steve
Jobs, who died Oct. 5.
Its sort of apples and oranges, said Paul Ceruzzi, a Smithsonian historian and expert on the
history of computers. Ritchie was under the radar. His name was not a household name at all,
but... if you had a microscope and could look in a computer; youd see his work everywhere
inside.
Dr. Ritchie worked at Bell Laboratories for four decades, from his time as a Harvard doctoral
student until his retirement in 2007. He was the inventor of the programming language known as
C and co-inventor of the operating system UNIX, another innovation that came from Bell Labs in
the late 1960s and early 70s.
When Dr. Ritchie went to Bell, computer programming language was arcane and impenetrable
for many computer gurus of the era. As a young scientist, Dr. Ritchie went to work on a language
that was sophisticated yet simple. Something of a night owl, he often went to the office about
noon and worked into the night from his home.
He named his creation C because programming language that came before it was called B.
C is a terse, elegant, deceptively simple language that allows programmers almost unlimited
flexibility, technology writer Charles Petzold wrote in the New York Times in 1996. It appeals
to the macho instincts of young and wild PC hackers, as well to the puzzle-solving impulses of
more mature programmers because of its power and the variety of ways to solve problems.
C was not without flaws it was vulnerable to viruses, Petzold wrote but it soon became the
most popular programming language. It allowed programmers to do in a few months jobs that
with other languages would have taken a year or more.
56

C language was the foundation for UNIX, the operating system Dr. Ritchie helped develop with
Bell colleague Kenneth Thompson. Microsoft Windows-based personal computers and many
Apple products run on its descendents. It is the ancestor of most of the infrastructure of our
wired society, Ceruzzi said.
Dr. Ritchie and Thompson received the Turing Award from the Association for Computing
Machinery in 1983 an early recognition of what would be an enduring contribution to
technology, said Tim Bergin, a computer language historian and professor emeritus at American
University.
More honors followed. In 1998, President Bill Clinton awarded the two men
of Technology and Innovation for their invention of UNIX operating
programming language, which together have led to enormous growth of
thereby enhancing American leadership in the Information Age. Early this
the prestigious Japan Prize for science and technology.

the National Medal


system and the C
an entire industry,
year, they received

Dennis MacAlistair Ritchie was born Sept. 9, 1941, in Bronxville, N.Y., to a scientific family.
His father, Alistair Ritchie, worked at Bell and co-wrote a book on switching circuits. The
younger Ritchie attended Harvard, where he earned a bachelors degree in physics in 1963 and a
doctorate in applied mathematics in 1968.
My undergraduate experience convinced me that I was not smart enough to be a physicist, and
that computers were quite neat, he wrote in a biography for Bell Labs. My graduate school
experience convinced me that I was not smart enough to be an expert in the theory of algorithms
and also that I liked procedural languages better than functional ones.Survivors include two
brothers, William Ritchie of Alexandria and John Ritchie of Newton, Mass., and one sister, Lynn
Ritchie of Hexham, England.
Dr. Ritchie co-wrote the book The C Programming Language, a volume on the order of a
technological Oxford English Dictionary.
He had a lighter side, too. With Pike, he lined up the magician duo Penn and Teller for a practical
joke on his boss, Nobel Prize-winning physicist Arno Penzias. In the stunt, videotaped in 1989
and available on YouTube, the two scientists convinced Penzias that they had invented fancy
voice-recognition technology. It took him days to recover, the voice-over says.

57

C PROGRAMMING
I/O Statements in C
printf - used to print the character, string, float, integer, octal, and hexadecimal values onto the console
Reference: http://en.wikipedia.org/wiki/C_language

Syntax:
int printf(const char *format, ...);
Format Explanation

Example

%d

Display an integer

10

%f

Displays a floating-point number in fixed decimal format

10.500000

%.1f

Displays a floating-point number with 1 digit after the decimal

10.5

%e

Display a floating-point number in exponential (scientific notation)

1.050000e+01

%g

Display a floating-point number in either fixed decimal or exponential format 10.5


depending on the size of the number (will not display trailing zeros)

Returns
The printf function returns the number of characters that was written. If an error occurs, it will return a
negative value.

Required Header
The required header for the printf function is:
#include <stdio.h>

scanf
int scanf ( const char * format, ... );

Specifier Description

Characters extracted

i, u

Any

Integer

number

of

digits,

optionally

preceded

by

sign

(+ or -).

Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits

58

(0-7), and 0x hexadecimal digits (0-f).

Decimal
integer

Any number of decimal digits (0-9), optionally preceded by a sign (+ or -).

Octal integer

Any number of octal digits (0-7), optionally preceded by a sign (+ or -).

Hexadecimal
integer

Any

f, e, g
Floating
number

point

Character

String
characters

number

of hexadecimal

digits (0-9, a-f, A-F),

optionally

A series of decimal digits, optionally containing a decimal point, optionally


preceded by a sign (+ or -) and optionally followed by the e or E character and
a decimal integer (or some of the other sequences supported by strtod).
Implementations complying with C99 also support hexadecimal floating-point
format when preceded by 0x or 0X.
The next character. If a width other than 1 is specified, the function reads
exactlywidth characters and stores them in the successive locations of the
array passed as argument. No null character is appended at the end.

of

Any number of non-whitespace characters, stopping at the first whitespace


character found. A terminating null character is automatically added at the end
of the stored sequence.

Return Value
If successful, the total number of characters written is returned, otherwise a negative number is returned.

Beyond Syllabus: File Processing on C programs:

preceded

by 0x or 0X, and all optionally preceded by a sign (+ or -).

fscanf( ) - reading a content from a file


fprintf( ) - writing a content into a file
fopen( ) open a file in either read mode or write mode
fclose( ) close a file

Working with C in Visual Studio 2010


Goto Start -> Micrsoft Visual Studio 2010 -> Click on it
A window as shown below appears. Goto File Menu -> New -> Project

59

A window as shown below appears. See that Visual C++ as shown in Figure is chosen. Goto
Win32 Console Application
Enter name, choose location and give ok

A window as shown below appears. Click next

60

A window as shown below appears

Uncheck Precompiled header and check the option Empty Project


The window changes to as shown below. Then click Finish.

61

The project opens.


In the solution explorer, goto source files -> Right click on it and choose Add -> New Item option
as shown in Figure.

A window as shown below appears. Make sure Visual C++ template is chosen and then click
C++ File option
Give file name with extension .c Eg. One.c (Please note that .cpp is the file extension for c++
programs, which you will study in the OOPS course).
62

A window as shown below appears. There is space to type code.


Type as shown below.

Compile the code by going to build menu -> Compile option

63

If there are compilation errors then they appear in the output window.
Click on the error to locate it and correct. If you are unable to figure out the error, you can cut and
paste the error message in Google in your web browser, go online, and find a possible solution to
try out!

If there is no error then go to Debug Menu and choose the option Start without Debugging.

64

The console opens for input and output.

65

Experiment 4
C Programming using Simple Statements and Expressions
Aim:
To write a C program to demonstrate the use of data types, simple statements, and
expressions.

Concepts Involved:
Data types: Data types are used to declare a variable before its use. Built-in data types are int,
float, char and double.

int is used to define integer numbers.(2 bytes)


float is used to define floating point numbers.(4 bytes)
double is used to define BIG floating point numbers. It reserves memory twice as
that of float.(8 bytes)
char is used to represent the character.(1 byte)

Declaration :
[Data type name] [Variable name];
E.g. int g;
char c;
Variables: A variable is the name given to a storage area that the programs can manipulate.
Operators:

These are symbols that operate on value or a variable.


For example: + is a operator to perform addition.
C language offers many types of operators. They are,
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators
66

Arithmetic Operators:
Operator

Operation

Explanation

Addition

Add two numbers

Subtraction

Subtract two numbers

Multiplication

Multiply two numbers

Division

Find quotient of division

Modulus

Find remainder of division

Assignment operators:
Simple operator

Compound
Operator

sum = 10

Value 10 is
variable sum

+=

sum+=10

This is same as sum = sum+10

-=

sum =
10

This is same as sum = sum


10

*=

sum*=10

This is same as sum = sum*10

/+

sum/=10

This is same as sum = sum/10

%=

sum%=10

This is same as sum =


sum%10

&=

sum&=10

This is same as sum =


sum&10

^=

sum^=10

This is same as sum = sum^10

Relational operators:
Operator

Example

>

x>y

<

x<y

>=

x >= y

<=

x <= y
67

assigned

to

==

x == y

!=

x != y

Logical operators:
Operator

Example

&&

x && y

||

x || y

x (x || y), !(x && y)

Conditional operators:
Syntax :
(Condition? true_value: false_value);
Example:
(A > 100? 0: 1);
If A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional
statements.

Bit wise operators:


These operators are used to perform bit operations on given two variables.

68

Truth table for bitwise operation:

Bitwise operators:

x/y

x&y

x^y

Operator

Explanation

&

Bitwise AND

Bitwise OR

Bitwise NOT

XOR

<<

Left Shift

>>

Right Shift

Increment and decrement operators:


Syntax:

Example:

++var_name;
(or)
var_name++;
(or)
- var_name;
(or)
var_name- -;
++i, i++, - -i, i- -

Special Operators:
S.no

Operators

Description

&

This is used to get the address of the variable.


Example:
&a will give address of a.

This is used as pointer to a variable.


Example: * a where, * is pointer to the variable a.

Size of ()

This gives the size of the variable.


Example: size of (char) will give us 1.
69

ternary

This is ternary operator and act exactly as if else


statement.

Type cast

Type cast is the concept of modifying variable from


one data type to other.

Precedence Table:
Operators

Associativity

Arithmetic Operators

Left to Right

Increment and Decrement Left to Right


Operators
Assignment Operators
Right to Left
Relational Operators

Left to Right

Logical Operators

Left to Right

Conditional Operators

Right to Left

Bitwise Operators

Left to Right

Expressions: It is a combination of operands and operators. It is used to compute new values


from old ones. Example a + b, x = y, t = u + v, x <= y , ++j

ASCII Table: http://en.wikipedia.org/wiki/ASCII_table

Pre Lab Exercises (test your programs with sample inputs, with descriptive
"Enter ..." statements!):
1.
2.
3.
4.

Write a C program to convert degree Celsius into Fahrenheit and vice versa.
Write a C program to find the area and circumference of a circle and a rectangle.
Write a C program to add three numbers (use file input/output!).
Write a C program that prints the next character for the given character (in English
alphabet).

70

In Lab Exercises: (test your programs with sample inputs, with descriptive
"Enter ..." statements!):
1. Write a C program to evaluate the algebraic expression (if X = 1, print out an error
message):

2. Write a C program to find maximum of two numbers using ternary operator.


3. Write a C program to find simple interest and compound interest accrued on a given
deposit amount after five years. Assume that annual compounding is followed. If the
average inflation is 6% over the same period, calculate the real value of the
principal+interest at the end of five years.
4. Look up the ASCII table, and write a C program to convert a word with lowercase letters
into a word with uppercase letters.

Post Lab Exercises:


1. Write a C program to find the size of the data types.
2. Write a C program to mask the most significant digit of the entered number. ( Use AND
operator)
3. Write a C program to enter a number and carry out modular division operation by 2, 3,
and 4 and to display the sum of the remainders.
4. Write a C program to perform swapping of two float values in variables a and b without
using temporary variable.
5. (Bonus: 15%) Repeat Post-Lab Ex (4) of Expt-1 with a C program and file I/O, i.e., enter
0 to (max_width)/2 equally spaced as twenty height values of box in input file, and print
out the ten corresponding outputs (volume of box) in output file. As you have not yet
studied how to compared the volumes to determine the maximum volume, simply export
the output file to MS Excel and plot the graph! You can also create the input values
automatically in Excel and save it as text input file.
Viva Questions:
1. Why C language is called middle level language?
2. What is meant by compilation?
3. List out the types of linkages.
4. How will you declare a variable in C?
5. List out some built-in functions
6. Differentiate static from public.
7. What do you mean by type conversion? Why is it necessary?
8. What is Dynamic initialization?
9. What are the operator precedence and how it will be used in the expression
evaluation?
10. List out all the control strings used in C.
71

11. How will you execute a dos command through C?

Results and Discussion:


Find error in following c program?
1. #include <stdio.h>
#include <conio.h>
int x;
int x=0;
int x;
int main(){
printf("%d",x);
getch();
return 0;
}
2. #include <stdio.h>
#include <conio.h>
int x;
int x=0;
int x;
int x=1;
int main(){
printf("%d",x);
getch();
return 0;
}
3. What will be the output for this program?
#include<stdio.h>
int main()
{
int i=3, j=2, k=0, m;
m= ++i && ++j && ++k;
printf(%d, %d, %d, %d\n, i, j, k, m);
return 0;
}

Beyond Syllabus: Arduino Programming


1. Bonus Problem on Arduino Programming (20%): Purchase an Arduino Uno board, install
the IDE software on your laptop, and light up three different colors (Red, Green, and
Blue).
References:
(1) Maik Schmidt - Arduino: a Quick-Start Guide, available as free eBook on www.itebooks.info
(2) Arduino Tutorial on blink program - The blink is the Arduino equivalent of the Hello,
World program!
72

2.

Experiment 5
Scientific Problem Solving using Decision Making and Looping
Aim:
To write a C program to demonstrate the use of decision making statements, looping
statements, and expressions.

Concepts Involved:
Decision Making
Programs should be able to make logical (true/false) decisions based on the condition
they are in;
An if statement consists of a Boolean expression followed by one or more statements.
Syntax: if(Boolean Expression) {
Statements;
}
Eg: if (x>10)
printf(Greater than 10);
The if....else statement is an extension of the simple if statement.
Syntax: if(Boolean Expression) {
Statements; }
else{
Statements;
}
Eg: if (x>10)
printf(Greater than 10);
else
printf(Not Greater than 10);
Syntax for Nesting of if else statements
if(Boolean Expression 1)
{
if(Boolean Expression 2){
statements; }
else {
statements; }
}
73

else{
statements;}
Eg: Find Maximum of three numbers a, b and c
if(a>b)
{
if(a>c)
printf(A is greater);
else
printf(C is greater);
}
else
{
if(b>c)
printf(B is Greater);
else
printf(C is Greater);
}

Syntax for else if ladder


if(Boolean Expression 1)
statement 1;
else if(Boolean Expression 2)
statement 2;
else if(Boolean Expression 3)
statement 3;
else
default statement;
Eg: Compare two numbers and determine the relationship between them
if(a>b)
printf(A is greater);
elseif(a=b)
printf(A is equal to B);
else
printf(B is greater);
Syntax for Switch Case:
switch(expression)
{
case constant_expression1:
statements;
break;
case constant_expression2:
74

statements;
break;
.
.
.
default: statements;
break;
}
Eg: Print day for number
switch(n)
{
case 0:
printf(Sunday);
break;
case 1:
printf(Monday);
break;
case 2:
printf(Tuesday);
break;
case 3:
printf(Wednesday);
break;
case 4:
printf(Thursday);
break;
case 5:
printf(Friday);
break;
case 6:
printf(Saturday);
break;
default:
printf(Not a valid number);
break;
}

Looping

Loops are used to execute a set of statements repeatedly until a particular condition is
satisfied.
There are three types of loops. while, do-while and for loop

while loop: The while loop allows for the repeated execution of a group of statements as long as
a condition is true. The condition is checked each time before the code is executed.
Syntax: while (condition) {
75

Statements; }
Eg: To print Hello 10 times
while (i < 10)
{
printf(Hello\n);
i++;
}
do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax: do {
statements;
} while(condition);
Eg: To print Hello 10 times this prints atleast once even if condition is not satisfied
do {
printf(Hello\n);
i++;
} while (i < 10);

for loops from one number to another number and increases by a specified value each time.
Syntax: for(initialization ; conditional ; increment/decrement)
{
statements; }

Pre Lab Exercises:


1. Write a C program to check whether a given number is palindrome or not.
2. Write a C program to check whether a given number is even or odd using if-else
statement.
3. Write a C program to convert binary number to decimal number and vice versa.
4. Write a C program to find prime numbers between two intervals.
5. Write a C program to check whether a given number is an Armstrong or Not.

In Lab Exercises:
1. Write a C program to simulate a calculator using switch statement.
2. Write a C program to convert a given decimal number to hexadecimal?
3. Write a C program to check whether a blood donor is eligible or not for donating blood.
The conditions laid down are as under. Use if statement.
(a). Age should be above 18 years but not more than 55 years.
(b). Weight should be more than 45 kg.

76

4. Write a C program to calculate bill for Internet Browsing. The conditions are given
below.
(a). 1 Hour 20 Rs.
(b). Hour 10 Rs.
(c). 12 Hours 90 Rs.
5. Write a C program to calculate the sum of remainders of numbers 1 to 9 when divided by
2.
6. Write a C program to calculate sum of the first and last numbers from 1 to 10 (e.g. 1+10,
2+9, 3+8 sums should be always 11)

Post Lab Exercises:


1. Write a C program to calculate the energy bill. Read the starting and ending meter
readings. The charges are as follows:
No. of units consumed
Rates in (Rs.)
200 500
3.5
100 200
2.50
Less than 100
1.50
2. Write a C program to convert years (assume non-leap years are given) into a. Minutes b.
Hours c. Days d. Months and e. Seconds and using switch statements.
3. Write a C program to print the reverse of the given text using do-while loop
4. Write a C program to print a 5 10 pattern of 0s using nested for loop.
5. Write a C program to check the entered input data for the following. Whenever input is
non-zero or positive, display numbers from 1 to that number, otherwise display message
Negative or zero. The program is to be performed for 10 numbers.
6. (Bonus program: 10%) Using while/for statement, solve the folding box maximum
volume calculation problem.

Viva Questions:
1.
2.
3.
4.
5.
6.
7.
8.

How will you use if statement for Switch- Case in C program?


How to decide even and odd values without decision making loops?
Is it possible to use multiple default statements in switch statement?
List out the difference between while and do-while statements.
Is it possible to use else statement in place of default or vice versa?
What will happen if you create a loop that never ends?
What are the values of NULL and !NULL?
Why loop is necessary in the program?

Results and Discussion:


1. What will be the output for the following programs?
for(i=1 ; i<5 ; i++)
{
if(i==4)
break;
77

printf(%d, i);
}
2. How many times IndiaBIX is get printed?
#include<stdio.h>
int main()
{
int x;
for(x=1; x<=10; x++)
{
if(x<5)
continue;
else
break;
printf(IndiaBix);
}
return 0;
}
3. Point out the error in the following program.
#include<stdio.h>
int main()
{
int i=1;
while()
{
printf(%d\n, i++);
if(i>10)
break;
}
return 0;
}
4. Point out the error
#include<stdio.h>
int main()
{
int i=1;
switch(i)
{
case 1: printf(Case 1);
break;
case 1*2+4: printf(Case2);
break;
}
return 0;
}
78

Beyond Syllabus: Arduino Programming


1. (Bonus Arduino Program, 15%):
In this section, we will use it to control Arduinos status LED using our computers
keyboard. TheLED should be turned on when you press 1, and it should be turned off
when you press 2. Heres all the code we need:
Download welcome/LedSwitch/LedSwitch.pde
const unsigned int LED_PIN = 13;
const unsigned int BAUD_RATE = 9600;
void setup()
{
pinMode(LED_PIN, OUTPUT);
Serial.begin(BAUD_RATE);
}
void loop()
{
if (Serial.available() > 0)
{
int command = Serial.read();
if (command == '1')
{
digitalWrite(LED_PIN, HIGH);
Serial.println("LED on");
}
else if (command == '2')
{
digitalWrite(LED_PIN, LOW);
Serial.println("LED off");
}
else
{
Serial.print("Unknown command: ");
Serial.println(command);
}
}
}

79

Experiment 6
Simple Programming for 1D and 2D Arrays
Aim:
To write a C program to demonstrate the use of arrays, types of array and its declaration.

Concepts Involved:
C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.

Array might be belonging to any of the data types

Array size must be a constant value.

Always, Contiguous(adjacent) memory locations are used to store array elements in


memory.

It is a best practice to initialize an array to zero or null while declaring, if we


dont assign any values to array.
Types of Arrays:
There are three types of arrays in C:
1. Single Dimensional Array.
2. Two dimensional Array &
3. Multi Dimensional Array.
Single dimensional array: <type of array> <name of array> <[size]>;
S.no

Array declaration

Array initialization

Accessing array

Syntax:
data_type
array_name
[array_size];

data_type
array_name
[array_size]=
(value 1, value 2,
value 3, .);

array_name[index];

is

int age[5] = {0, 1, 2,


3, 4, 5};

age[0]; //
accessed
age[1]; //
accessed
age[2]; //
accessed

is

is

char

name[0];

//S

is

int age [5];

char name [10];

name[10]
80

{S, u, r,
n};
(or)
name [0] =
name [1] =
name [2] =
name [3] =
name [4] = n;

e,

accessed
name[1];
accessed

//u

is

S;
u;
r;
e;

Two dimensional array:


S.n
o

Array declaration

Array initialization

Accessing
array

Syntax:
data_type
array_name[num_of_rows][num
_of_column];

data_type
array_name
[num_of_rows][num_of_columns]={
{1,2},{3,4}}}

array_name[i
ndex];

arr [0] [0] =


1;
arr [0] ]1] =
2;
2

Example:
int arr[2][2];

int arr[2][2] = {{1,2}, {3, 4}};

arr [1][0]
3;

arr [1] [1] =


4;

Accessing Array elements: An individual element of the array can be accessed by using the array
name followed by the element which is enclosed in square brackets. matrix[3][5];

Pre Lab Exercises:


1. Write a C program to read n numbers and find the maximum and minimum number.
2. Write a C program to enter the integer elements and arrange them in ascending order
using bubble sort.
3. Write a C program to find the transpose of the given matrix.

In Lab Exercises:
1. Write a C program for searching a number from the given list using 1D Array.
81

2. Write a C program to insert a given element in a sorted array.


3. Write a C program to read a number containing five digits, store each digit of it in an
array and print the square of them. For example, for the number 45252, Output should be
16254254
4. Write a C program to perform matrix addition, subtraction and multiplication.
5. Write a C program to merge the elements of 2 sorted array.

Post Lab Exercises:


1. Write a C program to generate the Pascal Triangle using 1D Array.
2. Given a binary array, write a C program to segregate 0s on left side and 1s on the right
side of the array.
3. (Bonus: 10%) Refer the post lab exercise (4) of first experiment and to find out the
maximum volume of a box using 1D Arrays and if statements for volume comparison.

Viva Questions:
1.
2.
3.
4.
5.
6.
7.

Define array and how to declare an array?


What are actual and formal arguments?
What does it mean if there is no return statement in the function?
Why is return statement not necessary when function is called by reference?
Is it possible to call library functions recursively?
How does an ordinary variable differ from an array definition?
Differentiate int *p from int* p.
8. How do you pass array as an argument to the function?

Results and Discussion:


1. What will happen if in a C program you assign a value to an array element whose
subscript exceeds the size of array?
2. What will be the output for the following program?
#include<stdio.h>
int main()
{
int a[5]={5,1,15,20,25}
int i, j, m;
i=++a[1];
j=a[1]++;
m=a[i++];
printf(%d, %d, %d,i , j, m);
return 0;
}
3. Is there any difference in the following declarations?
int fun (int arr[]);
int fun (int arr[2]);
4. If an array is passed as an argument to a function, what actually gets passed?
82

Beyond the Syllabus: Arduino Programming


1. Write an Arduino program to control RGB LED.
2. (Bonus: 15%) Write an Arduino program to create a traffic light system using four sets of
RGB LEDs.

83

Experiment 7
Solving problems using String functions
Aim:
To write a C program to demonstrate the string manipulations.

Concepts Involved:
String is an array of character and it is terminated by null character /0.
Example for C string:
char string[20] = { f , r , e , s , h , 2 , r , e , f , r , e , s , h , \0}; (or)
char string[20] = fresh2refresh; (or)
char string []

= fresh2refresh;

Difference between above syntax is, in the declaration, char as string[20], 20 bytes of
memory space is allocated by the programmer for holding the string value. Whereas in string[],
any number of required space will be allocated during execution of the program.
String handling functions are
strlen(arg1) - This function takes arg1 as argument, counts and returns the number of
characters in it. Length always does not include a null character.
n=strlen(string); where n is an integer value.
strcpy(destn, source) It is used to copy source string to destination string
strcat() This function used to concatenate (join) the two strings. Consider
strcat(string1, string2) here, string1 & string2 are the character arrays. When the
function strcat is executed string2 is appended to the string1. The string at string2
always remains unchanged.
strcmp(s1, s2) It is used to compare two strings.
o If the first string is greater than the second string (lexicographically) then
a number greater than zero is returned.
o If the first string is less than the second string (lexicographically) then a
number less than zero is returned.
o If the first and the second string are equal then zero is returned.
strlwr(str) It will convert the string str to lowercase and returns lowercase letters.
strupr(str) It will convert the string to uppercase and returns uppercase letters.
String handling functions are defined under string.h header file. i.e you have to include
the code below to run string handling functions. #include<string.h>

Pre Lab Exercises:


84

1. Write a C program to simulate string handling functions.


2. Write a C program to delete all the occurrences of vowels in the given sentence.
3. Write a C program to enter the string and get its duplicate.

In Lab Exercises:
1. Write a C program to enter some text through the keyboard. Insert dot (.) after every three
words in the text. The first character after every dot should be changed to capital.
2. Write a C program to encrypt the text in the following way. If input is INDIA, output
should be KPFKC.
3. Write a C program to sort a given set of names.
4. Write a C program that will analyze a line of text and will print the number of words, the
number of consonants and the number of vowels in the text.

Post Lab Exercises:


1. Write a C program to find whether a string is palindrome or not without using built-in
string functions.
2. Write a C program to remove the white spaces (blank spaces) from a string.
3. Write a C program to that takes the names of a person as input and prints the name in an
abbreviated fashion, e.g., Manas Ghosh as MG.
4. Write a C program that accepts a word from the user and prints it in the following way.
For example, if the word is COMPUTER, the program will print it as
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER

Viva Questions:
1.
2.
3.
4.
5.
6.
7.
8.

How will you print \n on the screen?


Why NULL character is important in strings?
Is it possible to initialize NULL character in the string?
What is the difference between the functions strcmp() and stricmp()?
What is strdup()?
List out the string library functions
How do you concatenate the strings?
What is the difference between getch() and getche() ?

Results and Discussion:


1. Will the program compile successfully?
#include<stdio.h>
85

#include<string.h>
int main()
{
char a[]=India;
char *p=BIX;
a=BIX;
p=India;
printf(%s %s\n,a,p);
return 0;
}
2. What will be the output of the program?
a. #include<stdio.h>
int main()
{
char p[]=%d\n;
p[1]=c;
printf(p,65);
return 0;
}
b. #include<stdio.h>
int main()
{
char str[] = Nagpur;
str[0] = K;
printf(%s, str);
str = Kanpur;
printf(%s,str+1);
return 0;
}
c. #include<stdio.h>
int main()
{
int i;
char a[ ]= \0;
if(printf(%s, a))
printf(the string is not empty\n);
else
printf(the string is empty\n);
return 0;
}

86

Beyond the Syllabus: Arduino Programming


1. Write an Arduino program to make a LED glow when controller detects a
button pressed.
2. (Bonus Arduino Program: 20%) Implement the Morse Code Generator example
of Section 4.2 from the eBook.

87

Experiment 8
Programs with user defined functions includes Parameter Passing
Aim:
To Write a C program to demonstrate the user defined function concepts, parameter
passing methods i.e., call by value and call by reference.

Concepts Involved:
The function is a self contained block of statements which performs a coherent task of a
same kind.
The functions which are created by user for program are known as 'User defined
functions'.
C Functions can be invoked from anywhere within a C program.
main() function is the function from where every C program is started to execute.
Name of the function is unique in a C program.
Syntax for defining user defined function:
//Function Prototype
<return type><function name> ([<argument list>]);
void main()
{
//Function Call
<function name>([<argument list>]);
}
//Function Definition
<return type><function name>([<argument list>])
{
<function body>;
}

Example:
int add (int a , int b)
{
int sum;
88

sum = a+b;
return sum;
}
Where,

Before calling and defining a


function, we have to declare function
prototype in order to inform the compiler
about the function name, function
parameters and return value type.

Only one value can be returned. If you want to return more than one values, pointers can be used.

Parameter Passing Methods:

Call by value
Call by reference

Call By Value:
Call by value means passing the copy of the value to a function. The called function is
copied in a local variable; any changes to it do not affect the source variable.
Call By Reference:
Call by reference means passing the address of a variable where the actual value is stored.
The called function uses the value stored in the passed address; any changes to it do affect the
source variable.

Main function
add( a,b)
Function
add(x,y)
For examples: Call By Value: a and b value passed to x and y. If any changes made in x and y
means it will not affect the value of a and b.

Main function
add( &a,&b)
Function
add(*x,*y)

89

For example: Call by Reference: a and b pass its address to the x and y variable. If any changes
made in x and y means it will affect the value of a and b also.
Note: In the all the exercises below, be sure to use functions!

Pre Lab Exercises:


1. Create a user-defined function message () to display Hello 10 times. Invoke the
function in main().
2. Write a function to calculate the average temperature of five days.
3. Write a C program to perform the following tasks using user defined functions:
a. Finding the square of a number
b. Finding the area of a rectangle
c. Conversion of decimal number to binary number
d. Reversing the number
4. Write a C program to find the sum of the digits of a number using functions

In Lab Exercises:
1. Write a function to calculate average of n numbers stored in an array. Get the numbers
and it to the functions.
2. Write a C program for adding two arrays of elements and display it in new array using
user defined function.
3. Write a C program for swapping of two values using call by value and call by reference.
4. Write a C program to interchange array elements of two arrays using a function.
5. Write a C program to add return values of three functions add(), multiply() and subtract().

Post Lab Exercises:


1. Write a C program to find prime factors of a number, which when multiplied, give the
number itself. For example, prime factors of 32 are 2.
2. Write a C program to find the highest and lowest common factors of two given numbers.
( Highest and lowest common factors for 50 and 100 are 5 and 2 respectively)
3. Write a C program to sort the numbers stored in a matrix (Do it row-major).
4. (Bonus: 10%) Repeat Post-Lab Ex 4 of Expt-1 by using a function to calculate the box
volume for a given height of the box.

Viva Questions:
1.
2.
3.
4.
5.

Differentiate call by value and call by reference.


What does it mean if there is no return statement in the function?
Why is return statement not necessary when function is called by reference?
List out user defined functions.
Give the example of call by reference.
6. Can you define a user defined function with the same library function name?
90

Results and Discussion:


1. Point out the error in the program.
a. #include<stdio.h>
int main()
{
int a=10;
void f();
a=f();
printf(%d\n,a);
return 0;
}
void f()
{
printf(Hi);
}
b. #include<stdio.h>
int f (int a)
{
a > 20 ? return(10) : return(20);
}
int main ( )
{
int f (int);
int b;
b = f(20);
printf(%d\n, b);
return 0;
2. Will the following functions work?
int f1(int a, int b)
{
return(f2(20));
}
int f2(int a)
{
return(a*a);
}

91

Beyond the Syllabus: Arduino Programming


1. (Bonus Arduino program: 15%): Write an Arduino 3-LED light chaser program using
functions, fast(), slow(), clockwise(), and counterclockwise().
2. Write an Arduino program to read the temperature and display the same in serial
monitor.

92

Experiment 9
Program using Recursive function
Aim:
To Write a C program to demonstrate the use of recursive functions.

Concepts Involved:
A function that calls itself is known as recursive function
For example:
find sum of first n natural numbers using recursion
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n)
{
if(n==0)
return n;
else return n+sum(n-1); /*self call to function sum() */
}

Tracing
sum(5) =5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
93

=5+4+6
=5+10
=15

Pre Lab Exercises:


1. Write a C program to reverse the sentence entered by user using recursion.
2. Write a C program to find the power of a number using recursion.
3. Write a C program to find whether the number is prime or not using recursion.

In Lab Exercises:
1. Write a C program for finding Factorial of a given number using recursion.
2. Write a C program to generate Fibonacci Series upto the given number using recursion.
3. Write a C program to determine GCD of a number using recursive function.
4. Write a C program to find the LCM of a number using recursion.

Post Lab Exercises:


1. Write a C program to remove all characters in a given string except Alphabet.
2. Write a C program to calculate the result of X = 1 + 3 + 5 + 7 +. . . + n with recursive
calls of function
3. Write a C program to find the first capital letter in the string using recursion.
4. Write a C program to solve the Tower-of-Hanoi problem using recursion.
5. (Bonus Problem: 10%) Refer the post lab exercise (4) of first experiment; Write a C
program to find the maximum volume of a box using recursion.

Viva Questions:
1.
2.
3.
4.
5.
6.

Is it possible to call the main function recursively?


How to define and declare a recursive function?
List out the types of function
Is it true that too many recursive calls may result into stack overflow?
Define recursion.
Is it true that too many recursive calls may result into stack overflow?

Results and Discussion:


1. What will be the output of the program?
#include<stdio.h>
int reverse(int);
int main()
{
int no=5;
94

reverse(no);
return 0;
}
int reverse(int no)
{
if(no==0)
return 0;
else
printf(%d,no);
reverse(no--);
}
2. The five items : A, B, C, D and E are pushed in a stack, one after the other starting from
A. The stack is popped four times and each element is inserted in a queue. Then two
elements are deleted from the queue and pushed back on the stack. Now one item is
popped from the stack. The popped item is ?

Beyond the Syllabus: Arduino Programming


1. (Bonus problem: 15%) Ref: Arduino Arrays and Recursion Tutorial
http://filear.com/?p=204
The students don't need to write original code, but just copy, paste, and execute this
code.

95

Experiment 10
Programs using Structures and Unions
Aim:
To write a C program to demonstrate the use of structure concepts and unions.

Concepts Involved:
Structure is user defined data type which is used to store heterogeneous data under
unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
All the members of a structure can be accessed at anytime.
Syntax for defining the structure:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
}struct_var;

Structure members can be accessed using member operator '.' . It is also called as 'dot
operator' or 'period operator'.
structure_var.member;

Union is user defined data type used to store a set of heterogeneous/ homogeneous data
under unique variable name at single memory location. Keyword union is used to
declare union.

Only one member of a union can be accessed at anytime.

Syntax for defining the union


union union_name
{
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
}union_variable;

The members of union can be accessed in similar manner as that structure. Suppose if
you are using pointer variable as a member then you can access the variable using
member operator i.e union_var member;
96

Typedef is a keyword that is used to give a new symbolic name for the existing name
in a C program.
In structure typedef means you no longer have to write struct all over the place.
For example:
typedef struct student
{
int mark [2];
char name [10];
float average;
}status;
structure variable declaration:
status record1;
//record 1 is structure variable
status record2;
//record 2 is structure variable

Pre Lab Exercises:


1. Write a C program to read and display car number, starting time and reaching time using
structure.
2. Write a C program to get either name or id of a list of users. Assume that names are
strings and ids are integers. Give only a single detail for a user. Use memory efficiently.

In Lab Exercises:
1. Write a C program to represent the details of student such as name, roll number, average
marks and their grade using structure.
2. Write a C program to display the different parameters of ten men in a table. The
parameters to be entered are height, weight, age, and chest in cm, Find the number of men
who satisfy the following condition:
(a). Age should be greater than 18 and less than 25.
(b). Height should be between 5.2 to 5.6 inches.
(c). Weight should be in between 45 to 60 kg.
(d). Chest should be greater than 45cm.
3. There are two employees in an industry namely regular and daily wages. Salary for regular
employees will be calculated using the formulae basic_pay + % of da * basic_pay+hra. Salary for
daily wages is calculated as no_of_hrs_worked * wages_per_hour. Create a structure to store
details of employees such as name, age, type of employment and salary details.

Post Lab Exercises:


1. Write a C program to get details of a student to print the mark sheet of n students. Mark
sheet must contain details such as name of the student, register number and marks of five
subjects.
2. Write a C program to develop the simple database program that will store a persons
details such as age, date of birth, and address.
3. (Bonus problem: 20%) Redo the box volume calc problem using (a) pointer, (b)
structure(?)
97

Viva Questions:
1.
2.
3.
4.
5.

Define structure and union


Differentiate structure from union.
How is a structure different from an array?
Is it possible to pass structure variable to function?
How can you invoke structure and union variable?

Results and Discussion:


1. Will the following declaration work?
typedef struct s
{
int a;
float b;
}s;
2. Point out the error and debug it for the following program.
struct emp
{
int ecode;
struct emp e;
}
3. What will be the output of the program?
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf(%d, %d, %d\n, u.ch[0], u.ch[1], u.i);
return 0;
}
Beyond the Syllabus: Arduino Programming
1. Write an Arduino code to flashes LED to music.
2. (Bonus problem: 20%) Arduino code using pointers and structures
http://arduino.cc/en/Tutorial/HomePage

98

LIST OF REFERENCE MATERIALS


1. http://www.cprogramming.com/
2. http://www.cprogrammingexpert.com/C/
3. http://www.learn-programming.za.net/learn_c_programming.html
4. http://pothi.com/pothi/faq/128
5. http://cwithabhas.blogspot.com/2012/05/c-interview-debugging-questions-find.html
6. http://www.thegeekstuff.com/2012/08/c-interview-questions/
7. http://www.avatto.com/computer/exam/mcqs/questions-answers/c/20/1.html
8. http://www.indiabix.com/c-programming/arrays/044001
9. http://www.cquestions.com/2010/06/array-questions-with-explanation-in-c.html
10. http://www.w3professors.com/Pages/Courses/C/C.html
11. http://os.camden.rutgers.edu/c_resources/c_programming/
12. https://www.classle.net/book/simple-c-programming-1-dimensional-array#
13. http://www.technoexam.com/c-language-lecture-study-notes-tutorials-material/functionsin-c.asp
14. http://www.le.ac.uk/users/rjm1/cotter/page_93.htm
15. http://www.indiastudycenter.com/studyguides/cs/objtest/default.asp
16. http://www.programiz.com/c-programming/examples/reverse-sentence-recursion
17. http://fresh2refresh.com/c/c-operators-expressions/
18. http://cprogrammingcodes.blogspot.in/2012/01/amicable-numbers.html
19. http://en.wikipedia.org/wiki/C_(programming_language)#K.26R_C
20. http://learning.acm.org/
21. http://www.codeproject.com/Articles/447332/Game-Programming-in-C-For-Beginners
22. http://en.wikipedia.org/wiki/The_C_Programming_Language_(book)

99

Reference Materials for Beyond the Syllabus:


1. http://www.slideshare.net/IT-BA-Certification/microsoft-visio-an-overview - MS VISIO
2. http://www.techonthenet.com/excel/formulas/vlookup.php - VLOOKUP
3. http://www.wikihow.com/Add-a-Second-Y-Axis-to-a-Graph-in- Microsoft-Excel Secondary axis
4. http://www.baycongroup.com/excel2007/03_excel.htm
5. http://office.microsoft.com/en-in/publisher-help/getting-started-HA010100492.aspx - MS
Publisher
6. http://inpics.net/publisher07.html - MS - Publisher
7. http://ist.uwaterloo.ca/ec/equations/equation.html
8. http://office.microsoft.com/en-in/word-help/insert-an-equation-using-equation-editorHP005190247.aspx
9. http://office.microsoft.com/en-in/word-help/track-changes-HA102840151.aspx
10. http://www.addintools.com/documents/word/where-track-change.html
11. http://www.youtube.com/watch?v=jqzn4mtVoic

Reference Materials for Beyond the Syllabus (Arduino Programming):


1. Maik Schmidt - Arduino: a Quick-Start Guide, available as free eBook on www.itebooks.info
2. Ref: Arduino Arrays and Recursion Tutorial http://filear.com/?p=204
3. Arduino code using pointers and structures
http://arduino.cc/en/Tutorial/HomePage

Useful Links:
1. C Puzzles - http://www.gowrikumar.com/c/index.html
2. Programming Interview Questions http://www.gowrikumar.com/programming/index.html
3. The Best Answers to Tough Interview Questions http://www.gowrikumar.com/interview/index.html
http://cboard.cprogramming.com/c-programming/30984-cool-programs.html
http://www.cprogramming.com/tutorial/thinking.html
4. 8 Common Programming Mistakes http://www.cprogramming.com/tutorial/common.html
5. 5 Ways You can Learn Programming Faster http://www.cprogramming.com/how_to_learn_to_program.html
http://nms.csail.mit.edu/papers/sigcomm13.pdf
http://www.cs.virginia.edu/~asb/teaching/cs101-fall05/index.html
http://www.cs.virginia.edu/~asb/teaching/cs101-fall05/labs/labs.html
http://cseweb.ucsd.edu/~ricko/CSE5A/HW5.pdf
http://www.ugrad.cs.ubc.ca/~cs101/current/project/course-project-2012W2.html
100

https://www.coursera.org/course/cs101
http://cseweb.ucsd.edu/~ricko/CSE5A/quizzes.html

101

You might also like