Vous êtes sur la page 1sur 97

SINHGAD COLLEGE OF ENGINEERING

VADGAON (Bk.), OFF SINHGAD ROAD PUNE 411041


Year 2013-14 CERTIFICATE

This is to certify that the project report entitled


AN ANALYSIS OF CRIME AND CRIMINAL INFORMATION USING DATA
MINING
Submitted by

is a bonafide work carried out by him under the guidance of Prof. S. A. Joshi and it is
approved for the partial fulfillment of the requirement of University of Pune, for the
award of the degree of Master of Engineering Computer (Computer Networks) during
the year 2013-14.
Place : Pune
Date :
Prof. S. A. Joshi
Prof. P. R. Futane Dr. S. D. Lokhande Guide, Head,
Principal, Department of Computer Engineering Department of Computer
Engineering Sinhgad College of Engineering Pune 41

Contents
1 Assignment 1

2 Assignment 2

12

3 Assignment 3

21

4 Assignment 4

33

5 Assignment 5

37

6 Assignment 6

40

7 Assignment 7

45

8 Assignment 8

50

9 Assignment 9

53

10 Assignment 10

57

11 Assignment 11

60

12 Assignment 12

63

13 Assignment 13

65

14 Assignment 14

69

15 Assignment 15

71

16 Assignment 16

75

17 Assignment 17

82

ii

18 Assignment 18

86

19 Assignment 19

88

20 Assignment 20

93

iii

Chapter 1
Assignment 1
Title
Use and Study of Linux GUI and Commands.

Objective
To learn and understand Linux GUI and basic commands.

Theory:
1.LINUX
Linux is a computer operating system assembled under the model of free and open source
software development and distribution. The defining component of Linux is the Linux
kernel, an operating system kernel first released on 5 October 1991, by Linus Torvalds.
Since the C compiler that builds Linux and the main supporting user space system tools
and libraries originated in the GNU Project, initiated in 1983 by Richard Stallman, the
Free Software Foundation prefers the name GNU/Linux when these tools and libraries
are used.
Linux was originally developed as a free operating system for Intel x86-based personal
computers. It has since been ported to more computer hardware platforms than any
other operating system. It is a leading operating system on servers and other big iron
systems such as mainframe computers and supercomputers: more than 90% of todays
500 fastest supercomputers run some variant of Linux, including the 10 fastest. Linux
also runs on embedded systems (devices where the operating system is typically built into
the firmware and highly tailored to the system) such as mobile phones, tablet computers,
network routers, building automation controls, televisions and video game consoles; the
Android system in wide use on mobile devices is built on the Linux kernel.
The development of Linux is one of the most prominent examples of free and open
source software collaboration: the underlying source code may be used, modified, and
distributed commercially or non- commercially by anyone under licenses such as the
GNU General Public License. Typically Linux is packaged in a format known as a Linux

Fundamental Programming Language Lab Manual

distribution for desktop and server use. Some popular mainstream Linux distributions
include Debian (and its derivatives such as Ubuntu and Linux Mint), Fedora (and its
derivatives such as the commercial Red Hat Enterprise Linux and its open equivalent
CentOS), Mandriva/Mageia, openSUSE (and its commercial derivative SUSE Linux
Enterprise Server), and Arch Linux. Linux distributions include the Linux kernel, supporting utilities and libraries and usually a large amount of application software to fulfil
the distributions intended use.
A distribution oriented toward desktop use will typically include the X Window System
and an accompanying desktop environment such as GNOME or KDE Plasma. Some
such distributions may include a less resource intensive desktop such as LXDE or Xfce
for use on older or less powerful computers. A distribution intended to run as a server
may omit all graphical environments from the standard install and instead include other
software such as the Apache HTTP Server and an SSH server such as OpenSSH. Because
Linux is freely re distributable, anyone may create a distribution for any intended use.
Applications commonly used with desktop Linux systems include the Mozilla Firefox
web browser, the LibreOffice office application suite, and the GIMP image editor.
Today, Linux systems are used in every domain, from embedded systems to supercomputers, and have secured a place in server installations often using the popular LAMP
application stack. Use of Linux
distributions in home and enterprise desktops has been growing. They have also gained
popularity with various local and national governments. The federal government of
Brazil is well known for its support for Linux. News of the Russian military creating
its own Linux distribution has also surfaced, and has come to fruition as the G.H.ost
Project. The Indian state of Kerala has gone to the extent of mandating that all state
high schools run Linux on their computers. China uses Linux exclusively as the operating system for its Loongson processor family to achieve technology independence. In
Spain some regions have developed their own Linux distributions, which are widely used
in education and official institutions, like gnuLinEx in Extremadura and Guadalinex in
Andalusia. Portugal is also using its own Linux distribution Caixa Mgica, used in the
Magalhes netbook and the e-escola government program. France and Germany have
also taken steps toward the adoption of Linux.
Linux distributions have also become popular in the netbook market, with many devices
such as the ASUS Eee PC and Acer Aspire One shipping with customized Linux distributions installed.
2. DESIGN
A Linux-based system is a modular Unix-like operating system. It derives much of its

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

basic design from principles established in Unix during the 1970s and 1980s. Such a
system uses a monolithic kernel, the Linux kernel, which handles process control, networking, and peripheral and file system access. Device drivers are either integrated
directly with the kernel or added as modules loaded while the system is running.
Separate projects that interface with the kernel provide much of the systems higher-level
functionality. The GNU userland is an important part of most Linux-based systems, providing the most common implementation of the C library, a popular shell, and many
of the common Unix tools which carry out many basic operating system tasks. The
graphical user interface (or GUI) used by most Linux systems is built on top of an implementation of the X Window System. Some components of an installed Linux system
are:
1. A bootloader - for example GRUB or LILO. This is a program which is executed by
the computer when it is first turned on, and loads the Linux kernel into memory.
2.An init program. This is the first process launched by the Linux kernel, and is at the
root of the process tree: in other terms, all processes are launched through init. It starts
processes such as system services and login prompts (whether graphical or in terminal
mode)
3.Software libraries which contain code which can be used by running processes. On
Linux systems using ELF-format executable files, the dynamic linker which manages
use of dynamic libraries is ld-linux.so. The most commonly used software library on
Linux systems is the GNU C Library. If the system is set up for the user to compile software themselves, header files will also be included to describe the interface of installed
libraries.
4.User interface programs such as command shells or windowing environments
2.1 USER INTERFACE
The user interface, also known as the shell, is either a command-line interface (CLI),
a graphical user interface (GUI), or through controls attached to the associated hardware, which is common for embedded systems. For desktop systems, the default mode
is usually a graphical user interface, although the CLI is available through terminal
emulator windows or on a separate virtual console. Most low-level Linux components,
including the GNU userland, use the CLI exclusively. The CLI is particularly suited
for automation of repetitive or delayed tasks, and provides very simple inter-process
communication.
On desktop systems, the most popular user interfaces are the extensive desktop environments KDE Plasma Desktop, GNOME, Cinnamon, Unity and Xfce, though a variety of
additional user interfaces exist. Most popular user interfaces are based on the X Window System, often simply called X. It provides network transparency and permits a

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

graphical application running on one system to be displayed on another where a user


may interact with the application.
Other GUIs may be classified as simple X window managers, such as FVWM, Enlightenment, and Window Maker, which provide a minimalist functionality with respect to the
desktop environments. A window manager provides a means to control the placement
and appearance of individual application windows, and interacts with the X Window
System. The desktop environments include window managers as part of their standard
installations (Mutter for GNOME, KWin for KDE, Xfwm for Xfce as of January 2012)
although users may choose to use a different window manager if preferred.
3.DEVELOPMENT
The primary difference between Linux and many other popular contemporary operating systems is that the Linux kernel and other components are free and open source
software. Linux is not the only such operating system, although it is by far the most
widely used. Some free and open source software licenses are based on the principle of
copyleft, a kind of reciprocity: any work derived from a copyleft piece of software must
also be copyleft itself. The most common free software license, the GNU General Public
License (GPL), is a form of copyleft, and is used for the Linux kernel and many of the
components from the GNU Project.
Linux based distributions are intended by developers for interoperability with other operating systems and established computing standards. Linux systems adhere to POSIX,[61]
SUS,[62] LSB, ISO, and ANSI standards where possible, although to date only one Linux
distribution has been POSIX.1 certified, Linux-FT.[63][64].
Free software projects, although developed in a collaborative fashion, are often produced
independently of each other. The fact that the software licenses explicitly permit redistribution, however, provides a basis for larger scale projects that collect the software
produced by stand-alone projects and make it available all at once in the form of a Linux
distribution.
Many Linux distributions, or distros, manage a remote collection of system software
and application software packages available for download and installation through a network connection. This allows users to adapt the operating system to their specific needs.
Distributions are maintained by individuals, loose-knit teams, volunteer organizations,
and commercial entities. A distribution is responsible for the default configuration of
the installed Linux kernel, general system security, and more generally integration of the
different software packages into a coherent whole. Distributions typically use a package
manager such as dpkg, Synaptic, YAST, yum, or Portage to install, remove and update
all of a systems software from one central location.
UBUNTU GRAPHICAL USER INTERFACE

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

http://www.ubuntu.com/tour/en/
BASIC LINUX COMMANDS
1.LS :
Lists the contents of a directory / list files and directories in bare format where we wont
be able to view details.
OPTION:
1.ls -a : Shows you all files, even files that are hidden (these files begin with a dot.)
2.ls -i : For each file, print the i-node number in the first column of the report.
3.ls -l : Shows - permissions, owners, size, and when last modified.)
4.ls -r : Reverses the order of how the files are displayed.
5.ls -R : Includes the contents of subdirectories.
6.ls -s : Give size in blocks, including indirect blocks, for each entry.
7.ls -x : Displays files in columns.
2.chmod:
Changes the permission of a file.file or directory permissions.
1. Add single permission to a file/directory
Changing permission to a single set. + symbol means adding permission. For example,
do the following to give execute permission for the user irrespective of anything else:
2. Add multiple permission to a file/directory
Use comma to separate the multiple permission sets as shown below.
$ chmod u+r,g+x filename
3. Remove permission from a file/directory
Following example removes read and write permission for the user.
$ chmod u-rx filename
4. Change permission for all roles on a file/directory
Following example assigns execute privilege to user, group and others (basically anybody
can execute this file).
$ chmod a+x filename
5. Make permission for a file same as another file (using reference)
If you want to change a file permission same as another file, use the reference option
as shown below. In this example, file2s permission will be set exactly same as file1s
permission.
$ chmod reference=file1 file2
3.password
Both Linux and UNIX use the passwd command to change user password. The passwd

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

is used to update a users authentication token (password) stored in shadow file.


A normal user may only change the password for his/her own account, the super user
(or root) may change the password for any account. The administrator of a group may
change the password for the group. passwd also changes account information, such as
the full name of the user, users login shell, or password expiry date and interval.
Set or Change User Password
Type passwd command as follows to change your own password:
$ passwd
Output:
Changing password for sayali
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
4.su
Become super user or another user.
The su (short for substitute user) command makes it possible to change a login sessions
owner (i.e., the user who originally created that session by logging on to the system)
without the owner having to first log out of that session.
The operating system assumes that, in the absence of a username, the user wants to
change to a root session, and thus the user is prompted for the root password as soon
as the ENTER key is pressed. This produces the same result as typing:
su root
su alice
Likewise, to transfer the ownership of a session to any other user, the name of that user
is typed after su and a space. For example, to change the owner of the current login
session to a user named alice, type the following:
The name of the current user can also be confirmed by using the whoami command, i.e.,
whoami
su hope
Login as the user hope as if the user hope actually logged in (process all login scripts
5.tty
The Linux tty command display the name of the connected terminal or Print filename
of terminal on stdin. A tty command in Linux and other Unix-like operating systems
is a shell command that can be entered interactively or as part of a script to determine

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

whether the output for the script is a terminal (that is, to an interactive user) or to
some other destination such as another program or a printer.
6.who
As a Linux user, sometimes it is required to know some basic information like :
a.Time of last system boot
b.List of users logged-in
c.Current run level etc
Though this type of information can be obtained from various files in the Linux system
but there is a command line utility who that does exactly the same for you. In this
article, we will discuss the capabilities and features provided by the who command.
who - Get the information on currently logged in users
syntax
who [OPTION]... [ FILE ARG1 ARG2 ]
-b, boot time of last system boot
-m only hostname and user associated with stdin
-q, count all login names and number of users logged on
-u, users list users logged in message
7. make
make - GNU make utility to maintain groups of programs
The purpose of the make utility is to determine automatically which pieces of a large
program need to be recompiled, and issue the commands to recompile them. The manual
describes the GNU implementation of make, which was written by Richard Stallman and
Roland McGrath. Our examples show C programs, since they are most common, but
you can use make with any programming language whose compiler can be run with a
shell command. In fact, make is not limited to programs. You can use it to describe any
task where some files must be updated automatically from others whenever the others
change.
To prepare to use make, you must write a file called the makefile that describes the
relationships among files in your program, and the states the commands for updating
each file. In a program, typically the executable file is updated from object files, which
are in turn made by compiling source files.
Once a suitable makefile exists, each time you change some source files, this simple shell
command:
make
suffices to perform all necessary recompilations. The make program uses the makefile

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

data base and the last-modification times of the files to decide which of the files need to
be updated. For each of those files, it issues the commands recorded in the data base.
make executes commands in the makefile to update one or more target names, where
name is typically a program. If no -f option is present, make will look for the makefiles
GNUmakefile, makefile, and Makefile, in that order.
Create the Makefile for a Simple Compilation
Let us assume that you have the sample C program file called helloworld.c. Using cc
command, typically you would compile it as shown below.
$ cc -o helloworld helloworld.c
While you dont need to use make for compiling single a program, the following example
will give you an idea on how to use make. Create a makefile as shown below.
$ vim makefile
helloworld : helloworld.c
cc -o helloworld helloworld.c
Execute make to create the helloworld executable as shown below.
$ make helloworld
(or)
$ make
8.rpm
RPM command is used for installing, uninstalling, upgrading, querying, listing, and
checking RPM packages on your Linux system.
RPM stands for Red Hat Package Manager.
There are five basic modes for RPM command
1.Install : It is used to install any RPM package.
2.Remove : It is used to erase, remove or un-install any RPM package.
3.Upgrade : It is used to update the existing RPM package.
4.Verify : It is used to query about different RPM packages.
5.Query : It is used for the verification of any RPM package.
With root privilege, you can use the rpm command with appropriate options to manage the RPM software packages.
In this article, let us review 15 practical examples of rpm command.
Let us take an rpm of Mysql Client and run through all our examples.
Syntax

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

rpm - RPM Package Manager


9.yum
yum - Yellowdog Updater Modified
yum is an interactive, automated update program which can be used for maintaining
systems using rpm
Syntax
yum [options] [command] [package ...]
The following are the ways which you can invoke yum in list mode. Note that all list
commands include information on the version of the package.
yum list [all regexp1] [regexp2] [...]
List all available and installed packages.
yum list available [regexp1] [...]
List all packages in the yum repositories available to be installed.
yum list updates [regexp1] [...]
List all packages with updates available in the yum repositories.
yum list recent
List packages recently added into the repositories.
Specifying package names
All the list options mentioned above take file-glob-syntax wild-cards or package names
as arguments, for example yum list avail-able foo* will list all available packages that
match foo*.
10.sudo
sudo - execute a command as another user. Allows a user with proper permissions to
execute a command as the superuser or other user.
sudo allows a permitted user to execute a command as the superuser or another user,
as specified in the sudoers file. The real and effective uid and gid are set to match those

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

of the target user as specified in the passwd file (the group vector is also initialized when
the target user is not root). By default, sudo requires that users authenticate themselves
with a password (NOTE: by default this is the users password, not the root password).
Once a user has been authenticated, a timestamp is updated and the user may then
use sudo without a password for a short period of time (5 minutes unless overridden in
sudoers).
The sudo command stands for superuser do. It prompts you for your personal password and confirms your request to execute a command by checking a file, called sudoers,
which the system administrator configures. Using the sudoers file, system administrators can give certain users or groups access to some or all commands without those users
having to know the root password. It also logs all commands and arguments so there is
a record of who used it for what, and when.
To use the sudo command, at the command prompt, enter:
sudo command
Replace command with the command for which you want to use sudo.
The sudo command also makes it easier to practice the principle of least privilege (PoLP),
which is a computer security concept that helps control system access and potential system exploits and compromises. For more information about the sudo command,
Examples
su -u hope ls hope
List the contents of the hope directory as the hope user.
11.shutdown command
shutdown - bring the system down or Turn off the computer immediately or at a specified time.
shutdown brings the system down in a secure way. All logged-in users are notified
that the system is going down, and login(1) is blocked. It is possible to shut the system down immediately or after a specified delay. All processes are first notified that
the system is going down by the signal SIGTERM. This gives programs like vi(1) the
time to save the file being edited, mail and news processing programs a chance to exit
cleanly, etc. shutdown does its job by signalling the init process, asking it to change the
runlevel. Runlevel 0 is used to halt the system, runlevel 6 is used to reboot the system,
and runlevel 1 is used to put to system into a state where administrative tasks can be
performed; this is the default if neither the -h or -r flag is given to shutdown. To see
which actions are taken on halt or reboot see the appropriate entries for these runlevels

10

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

in the file /etc/inittab.


Syntax
shutdown [-a][-t sec][-krhnfFc][time][warning-message]
-a Use /etc/shutdown.allow.
-t sec Tell init to wait sec seconds between sending processes the warning and the kill
signal, before changing to another runlevel.
-k Dont really shutdown; only send the warning messages to everybody.
-r Reboot after shutdown.
-h Halt after shutdown.
-n Dont call init to do the shutdown but do it ourselves. The use of this option is
discouraged, and its results are not always what youd expect.
-f Skip fsck on reboot.
-F Force fsck on reboot.
-c Cancel an already running shutdown. With this option it is of course not possible
to give the time argument, but you can enter an explanatory message on the command
line that will be sent to all users.
time When to shutdown.
warning-message Message to send to all users.
Examples
shutdown 8:00
Shutdown the computer at 8-oclock

11

Dhole-Patil College of Engineering,pune

Chapter 2
Assignment 2
Title
Handling and use of Eclipse Editor for creating project in C, Python, Java.

Objective
To learn and understand Eclipse Editor.

Theory:
1.Eclipse:
In computer programming, Eclipse is an integrated development environment (IDE). It
contains a base workspace and an extensible plug-in system for customizing the environment. Written mostly in Java, Eclipse can be used to develop applications. By means
of various plug-ins, Eclipse may also be used to develop applications in other programming languages: Ada, ABAP, C, C++, COBOL, Fortran, Haskell, JavaScript, Lasso,
Natural, Perl, PHP, Prolog, Python, R, Ruby (including Ruby on Rails framework),
Scala, Clojure, Groovy, Scheme, and Erlang. It can also be used to develop packages
for the software Mathematica. Development environments include the Eclipse Java development tools (JDT) for Java and Scala, Eclipse CDT for C/C++ and Eclipse PDT
for PHP, among others.
The initial codebase originated from IBM VisualAge.The Eclipse software development
kit (SDK), which includes the Java development tools, is meant for Java developers.
Users can extend its abilities by installing plug-ins written for the Eclipse Platform,
such as development toolkits for other programming languages, and can write and contribute their own plug-in modules.
1.1 Prerequisites for Running Eclipse
Eclipse is written in Java and will thus need an installed JRE or JDK in which to execute
-JDK recommende.
1.2 Eclipse on GL
This years coordinated release (known as Ganymede) of the Eclipse IDE for Java Devel-

12

Fundamental Programming Language Lab Manual

opers has been installed on GL.From any of the Linux machines in the labs simply run
the command eclipse.
1.3 Obtaining Eclipse:
Eclipse can be downloaded from:
http://www.eclipse.org/downloads/packages/
Be sure to grab Eclipse IDE for Java Developers.Eclipse comes bundled as a zip file(Windows)
or a tarball (all other operating systems).Some versions of Linux (i.e. Fedora, Ubuntu)
offer Eclipse in their respective repositories and can be downloaded using the appropriate tool (i.e. yum, apt-get).
1.4 Installing Eclipse
Simply unwrap the zip file to some directory where you want to store the executables.On
windows:
1.I typically unwrap the zip file to C:\eclipse
2.I then typically create a shortcut on my
3.desktop to the eclipse executable 4.C:\eclipse\eclipse.exe
Under Linux 1.I typically unwrap to /opt/eclipse/
1.5 Launching Eclipse Once you have the environment setup, go ahead and launch
eclipse.You should see the following splash screen

1.6 Selecting a Workspace In Eclipse, all of your code will live under a workspace.A
workspace is nothing more than a location where we will store our source code and where
Eclipse will write out our preferences.Eclipse allows you to have multiple workspaces
each tailored in its own way.Choose a location where you want to store your files,then
click OK

13

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

1.7 Welcome to Eclipse The first time you launch Eclipse, you will be presented
with a welcome screen. From here you can access an overview to the platform, tutorials,
sample code, etc.Click on the workbench to get actual IDE

14

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

1.8 Creating a New Project


All code in Eclipse needs to live under a project.To create a project: File New Java
Project

Enter a name for the project, then click Finish

15

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

16

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

This brings up the new class wizard. From here you can specify the following...
1.Package
2.Class name
3.Superclass
4.Whether or not to include a main etc
Fill in necessary information then click Finish to continue.

17

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

1.9 Compiling Source Code:


One huge feature of Eclipse is that it automatically compiles your code in the background.You no longer need to go to the command prompt and compile code directly
This means that errors can be corrected when made. We all know that iterative development is the best approach to developing code, but going to shell to do a compile can
interrupt the normal course of development. This prevents going to compile and being
surprised with 100+ errors.

18

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

1.10 Running Code:

19

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Conclusion: Thus we had studied how to create project in Eclipse for Java.

20

Dhole-Patil College of Engineering,pune

Chapter 3
Assignment 3
Title
Using Eclipse to write/test Hello!Worldprogram in C,Python.

Objective
To learn and understand Eclipse Editor programming.

Theory:
1. Creating Hello World program in C using Eclipse:
To create a simple Hello World application using CDT, perform the following general
steps:
1. Creating a project
2. Reviewing the code and building the project
3. Running the application
Step 1: Creating a project:
1. Select File New Project.

2.Select the type of project to create. select C Project and click Next.

21

Fundamental Programming Language Lab Manual

3.The C Project wizard opens.

In the Project name field, type a name for the project, such as HelloWorld.
a. From the Project type list, expand Executable and select Hello World C Project.
This project type provides a simple Hello World application in C.
b. Select a required toolchain from the Toolchain list.
A toolchain is a set of tools (such as a compiler, linker, and assembler) intended to build
your project. Additional tools, such as a debugger, can be associated with a toolchain.

22

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

There can be several toolchains available, depending on the compilers installed on your
system.
c. Click Next.
4. Specify the Basic Properties for the new project, such as your author, copyright, and
source information, then click Next.

5.The Select Configurations page displays a list of configurations based on the project
type and toolchain(s) selected earlier.

23

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

OPTIONAL: If you want to change the default project settings, click Advanced Setting to open the Project Properties dialog for your new project allowing you change any
of the project specific settings, such as includes paths, compiler options, and libraries.
6. Click Finish.
NOTE If the C++ perspective is not currently set as the default, you are prompted to
determined if you would like to this project to be associated with the C/C++ perspective. Click Yes.
A project is created with the default settings and a full set of configurations based on
the project type and toolchain you selected. You should now see the new project in
Project Explorer view.

Step 2: Reviewing the code and building the project:


1. From the Project Explorer view, double-click the .cpp file created for your project,
for example, HelloWorld.cpp. Youll find it within the project src folder.
This file opens in a default editor. It contains C++ template code for the Hello World
example project you selected earlier. In addition, the Outline view has also been populated with objects created from your code.

24

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

NOTE: You can specify a different editor, and add or modify existing code templates
in Window Preferences. OPTIONAL: You can type additional code in this file, and
then save the changes by clicking File Save, or pressing CTRL+S. Next, you will need
to build your project before you can run it.
2. Build your project by pressing CTRL+B, or select the project in the Project Explorer view and select File Build Project. NOTE: If a build generates any errors or
warnings, you can see those in the Problems view. If you encounter difficulty, see the
topics Building C/C++ projects and Before you begin .
3. Read through the build messages in the Console view. The project should build
successfully.
You will also see the Outline view has also been populated with objects created from
your code. If you select an item from the Outline view, the corresponding text in the
editor is highlighted.
Step 3: Running the application To run your application:
1. Within the C/C++ Perspective, click Run Run Configurations....
2. Select C/C++ Application.
3. Click New.
A new Run Configuration is created. Its name and path to the executable are provided
by the project (Hello World in our case).
4. Click Run.
Now, you should see the Hello World application running in the Console view. The
Console also shows which application is running in a title bar.
5. You can click the other views to see the information that they contain.

25

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

2.Using Eclipse PyDev Plugin


Pyton is a interpreted high-level programming language developed by Guido van Rossum.
Python is free to use, even for commercial products, because of its OSI-approved open
source license. Python runs on Windows, Linux/Unix, Mac OS X, and has been ported
to the Java and .NET virtual machines. The language is very easy to learn because
its source code resembles pseudo code. Python is an object-oriented programming language. In Python, everything is an object, and can be handled as such. However, unlike
Java, Python does not impose object-oriented programming as the main programming
paradigm. It is perfectly viable for a Python project to not be object-oriented, i.e. to
use no or very few class definitions, class inheritance, or any other mechanisms that are
specific to object-oriented programming. In Python there is no curly braces to indentify
a block of code. For example in case of an if statement all the code that is indented
after the if statement belong to the if statement block. This tutorial will go thru how
to Install Python and the PyDev plugins for Eclipse. After that we will create a small
Hello world program to demonstrate its usage.
Step 1: Download Python
You can download Python from http://www.python.org/download/. For Windows you
can use the native installer python-3.2.msi for Python and follow the instructions.

26

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

27

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Step 2: Eclipse Python Plugin


PyDev is a Python IDE for Eclipse, which may be used in Python, Jython and IronPython development supporting code refactoring, graphical debugging, code analysis
and many other features. You can install PyDev via the Eclipse update manager using
the following update site - http://pydev.org/updates

Select Checkbox for PyDev and follow thru on the installation

28

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Step 3: Configure Eclipse


We have to tell eclipse about the Python location. Please open Window - Preferences.
Select Interpreter Python inside the PyDev option and click on New Configuration and
add Python executable path.

Step 4: Python Hello World Program


Create a Python Project named PythonBeginner. File New Project PyDev
Project.

29

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Right click on the src folder and Select New PyDev Module.

30

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Name your new module HelloWorld and click Finish. Now copy the following source
into the HelloWorld Python Module and save it.

Now right click on your HelloWorld module and select Run As Python Run

31

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

In the console input your name and press ENTER. All Done...

Conclusion:
Thus we had studied how to create Hello World project in C, python project using
Eclipse

32

Dhole-Patil College of Engineering,pune

Chapter 4
Assignment 4
Title

Write a C program to accept five number from console and then to display
them back in console in ascending order

Objective
To learn and understand basic of arrays.

Theory:
Array in C:
C programming language provides a data structure called the array, which can store a
fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed
by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Declaring Arrays:

33

Fundamental Programming Language Lab Manual

To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a
10-element array called balance of type double, use this statement:
double balance[10];
Now balance is a variable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays:
You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = 1000.0, 2.0, 3.4, 7.0, 50.0;
The number of values between braces can not be larger than the number of elements
that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write:
double balance[] = 1000.0, 2.0, 3.4, 7.0, 50.0;
You will create exactly the same array as you did in the previous example. Following is
an example to assign a single element of the array:
balance[4] = 50.0;
The above statement assigns element number 5th in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called base index and
last index of an array will be total size of the array minus 1. Following is the pictorial
representation of the same array we discussed above:

Accessing Array Elements:


An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable.

34

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Algorithm:
step 1: Start
Step 2: Initialize required variables .
step 3: Accept total number to be sorted.
Step 4: Accept the numbers.
step 5: compare each number with other and if first number is greater than second
number then swap.
Step 6: stop. Flowchart:

program:
] include h stdio.h i
] include h conio.h i
void main()
{
int n,i,j,num[20],temp;
clrscr();
printf(\n Enter how many numbers to be sorted:\n);
scanf(%d,&n);
printf(\n Enter the %d numbers :,n);
for(i=0;i i= n;i++)
{
scanf(%d,&num[i]);
}
//the following code is for sorting

35

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

for(i=0;i i= n;i++)
{
for(j=i+1;j i= n;j++)
{
//following code is for swapping the elements to maintain the order.
if(num[i] i num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
printf(\ n Elements in sorted order are : \n);
for(i=0;ih n;i++)
{
printf(%d,num[i]);
}
getch();
}
Output: Enter how many number to be sorted: 5
Enter 5 number:
54321
Elements in sorted order are:
12345
Conclusion: Hence we had studied how to sort a numbers using arrays.

36

Dhole-Patil College of Engineering,pune

Chapter 5
Assignment 5
Title
Write a C program to calculate sum of all numbers from 0 to 100 (both inclusive) that
are divisible by 4.

Objective
To learn and understand basic of programming.

Prior Concepts:
1.Variables / constants / keywords.
2.Data types, Operations and Expressions.
3.Input / Output statements.
4.C program structure.

Theory:
1.for statement:
This involves repeating some portion of the program either a specified number of times
or until a particular condition is being satisfied. This repetitive through a loop control
instruction.For is one of the method from which we can repeat a part of a program.The
for allows us to specify three things about a loop in a single line:
a. Setting a loop counter to an initial value.
b. Testing a loop counter to determine whether its value has reached the numbers of
repetitions desired.
c. Increasing the value of loop counter each time the program segment within the loop
has been executed.
The general form of for statement is as follows :
for (initialise counter; test counter; increment counter )
{
do this;
and this;

37

Fundamental Programming Language Lab Manual

}
2. if statement :
C uses the keyword if to implement the decision control instruction. The general form
of if statement looks like this:
if ( this condition is true )
execute this statement ;
The keyword if tells the compiler that what follows is a decision control instruction. The
condition following the keyword if is always enclosed within a pair of parentheses. If the
condition, whatever
it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. But how do we express the
condition itself in C? And how do we evaluate its truth or falsity? As a general rule,
we express a condition using Cs relational operators. The relational operators allow us
to compare two values to see whether they are equal to each other, unequal, or whether
one is greater than the other. Heres how they look and how they are evaluated in C.
this expression is true if
x==y
x is equal to y
x!=y
x is not equal to y
The relational operators should be faxhy
x is less than y
xiy
x is greater than y
xh=y
x is less than or equal to y
xi=y
x is greater than or equal to y
miliar to you except for the equality operator == and the inequality operator !=. Note
that = is used for assignment, whereas, == is used for comparison of two quantities.
Algorithm:
step 1: Start
Step 2: Initialized necessary variables, for storing addition take sum and initialized it
with 0.
step 3: start from 0 to 100 check every number is divisible by 4 or not.
Step 4: if number is divisible by 4 then add that number with sum
step 5: continue till 100 then show result which is in sum variable.
Flowchart:

38

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

program:
] include h stdio.h i
] include h conio.h i
void main()
{
int i,sum=0;
clrscr();
for(i=0;ih=100;i++)
{
if(i % 4 ==0) //to check if number is divisible by 4
sum=sum+i;
}
printf( The addition of numbers from 0 to 100 that are divisible by 4 is %d,sum);
getch();
}
Output:
The addition of numbers from 0 to 100 that are divisible by 4 is : 1300.
Conclusion:
Hence we had studied use of if statement and for loop.

39

Dhole-Patil College of Engineering,pune

Chapter 6
Assignment 6
Title
Write a C program to accept length of three sides of a triangle from console and to test
and print the types of triangle-equilateral, right angle, isosceles, none of these.

Objective
To learn and understand nested if else statement.

Prior Concepts:
1.Variables / constants / keywords.
2.Data types, Operations and Expressions.
3.Input / Output statements.
4.C program structure.
5.Control Structure.

Theory:
The if-else Statement
The if statement by itself will execute a single statement, or a group of statements,
when the expression following if evaluates to true. It does nothing when the expression
evaluates to false. Can we execute one group of statements if the expression evaluates
to true and another group of statements if the expression evaluates to false? Of course!
This is what is the purpose of the else statement.
It is perfectly all right if we write an entire if-else construct within either the body of
the if statement or the body of an else statement. This is called nestingof ifs, which is
shown below :
if ( condition )
{
if ( condition )
do this ;
else

40

Fundamental Programming Language Lab Manual

{
do this ;
and this ;
}
}
else
do this ;
if the condition is true then another if else is executed and if condition is false then
directly else will be executed.
Algorithm:
Step 1: Start
Step 2: Read the value of three sides. i.e., a, b & c.
Step 3: if a+bhc or b+cha or a+chb,
then display Sides cant Triangle (Triangle Rule: Sum of two sides should be than
the third side.)
Step 4: if all sides are equal, i.e., a=b=c then display Equilateral Triangle.
Step 5: if two sides are equal, i.e., a=b or b=c or c=a then display Isosceles Triangle.
Step 6: if sides follow Pythagoras Theorem: Sum of Squares of two sides is equal to the
Square of the Hypotenuse. i.e., a*a = b*b + c*c OR c*c = a*a + b*b OR b*b= a*a
+ c*c, display Right Triangle.
Step 7: Display Scalene... i.e., Each side is different.
Step 8: Stop
Flowchart:

41

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

program:
] include h stdio.h i
] include h conio.h i
] include h process.h i
void main()
{
int a, b, c;
clrscr();
printf(Program to Identify the Type of Triangle based on its sides\n\n );
printf(Enter the length of three sides of the triangle:\n );
scanf(%d%d%d , &a, &b, &c);
if ( ((a+b)h=c) k ((b+c)h=a) k ((a+c)h=b) )
{
printf(The Given sides cant form a TRIANGLE!!! );
getch();
exit(0);
}
else
{
if (a==b && b==c)

42

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

{
printf(The given triangle is EQUILATERAL... );
getch();
exit(0);
}
if ((a==b)k(b==c)k(a==c))
{
printf(The given triangle is ISOSCELES... );
getch();
exit(0);
}
if (((a*a)==(b*b)+(c*c))k( (b*b)==(a*a)+ (c*c))k((c*c)==(a*a)+(b*b)))
{
printf(The given triangle is RIGHT ANGLED... );
getch();
exit(0);
}
else
printf(The given triangle is SCALENE... );
}
}
getch();
}
Output:
CASE 1:
Program to Identify the Type of Triangle based on its sides
Enter the length of three sides of the triangle:
333
The given triangle is EQUILATERAL...
CASE 2:
Program to Identify the Type of Triangle based on its sides
Enter the length of three sides of the triangle:
433
The given triangle is ISOSCELES...
CASE 3:
Program to Identify the Type of Triangle based on its sides
Enter the length of three sides of the triangle:

43

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

345
The given triangle is RIGHT ANGLED...
CASE 4:
Program to Identify the Type of Triangle based on its sides
Enter the length of three sides of the triangle:
473
The given triangle is SCALENE...
CASE 5:
Program to Identify the Type of Triangle based on its sides
Enter the length of three sides of the triangle:
123
The Given sides cant form a TRIANGLE!!!
Conclusion:
Hence we had studied use of nested if else statement.

44

Dhole-Patil College of Engineering,pune

Chapter 7
Assignment 7
Title
Write a C program to accept a string from console and to display the following on console:
1.Total numbers of character in the string.
2.Total number of vowels in the string.
3.Total number of occurrence of a character a in the string.
4.Total number od occurrence of the string the in the string.

Objective
To learn and understand basic of String and String Operation.

Prior Concepts:
1.Variables / constants / keywords.
2.Data types, Operations and Expressions.
3.Input / Output statements.
4.C program structure.

Theory:
String:
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character \0. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word Hello.
To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word Hello.
char greeting[6] = H, e, l, l, o, \0;
If you follow the rule of array initialization then you can write the above statement as
follows:
char greeting[] = Hello;

45

Fundamental Programming Language Lab Manual

Following is the memory presentation of above defined string in C:


Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the \0 at the end of the string when it initializes the
array. Let us try to print above mentioned string:
] include h stdio.h i
int main ()
{
char greeting[6] = H, e, l, l, o, \0;
printf(Greeting message: %s\n, greeting );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings:
A variety of operations can be performed on Strings. Therefore different modules are
created(with and without pointers) to perform the following different functions:
1.Count: This function tells total numbers of character in the String.
Eg: The original string is:Codearea
The Total number of character in The String are:8
2. Substring:This function tells whether user entered string is a part of the original
String.
Eg: The original string is:Codearea
The user entered string is:Code
Then above function will display the result as String is a substring
Algorithm:
Step 1: Start.
Step 2: Accept String in str.
Step 3: Initialize i=0.
Step 4: while str[i]!=\0.
Step 5: increment count.
Step 6: print count in which total number of characters are stored.
Step 7: Stop.
Flowchart:

46

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Program:
] include h stdio.h i
] include h conio.h i
] include h string.h i
int count=0, i=0;
char str[24];
clrscr();
printf(Program to Study String Functions...\n );
printf(\n\tEnter a string: );
scanf(%s, str);
while (str[i] != \0)
{
count++;/* this count total number of character in string*/
}
printf(\n\t 1. There are %d characters in the string.\n , count);
count=0;
while (str[i] != \0)
{
if(str[i]==akstr[i]==ekstr[i]==ikstr[i]==okstr[i]==u
kstr[i]==Akstr[i]==Ekstr[i]==Ikstr[i]==Okstr[i]==U)

47

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

{
count++;
}
i++;
}
printf(\t 2. Theres %d vowel(s).\n , count);
i=0;
count=0;
while (str[i] != \0)
{
if (str[i]==a)
{
count++;
}
i++;
}
printf(\t 3. Character a appears %d time(s).\n , count);
i=0;
count=0;
while (str[i] != \0)
{
if ((str[i]==tkstr[i]==T) &&
(str[i+1]==hk str[i+1]==H)&&
(str[i+2]==ekstr[i+2]==E)) {
count++;
}
i++;
}
printf(\t4. The phase the appears %d time(s). , count);
getch();
}
Output:
Program to Study String Functions...
Enter a string: qweEtYIOuThEiTHeatheU
1. There are 21 characters in the string.
2. Theres 11 vowel(s).
3. Character a appears 1 time(s).

48

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

4. The phase the appears 3 time(s).


Conclusion:
Hence we had studied use of String in c.

49

Dhole-Patil College of Engineering,pune

Chapter 8
Assignment 8
Title
Write a C program to convert character String to lower class to upper class and numeric
digits to reverse order.

Objective
To learn and understand basic of String and String Operation.

Prior Concepts:
1.Variables / constants / keywords.
2.Data types, Operations and Expressions.
3.Input / Output statements.
4.C program structure.
5.String.

Theory:
Logic for Reversing a number :This program reverse the number entered by the user and then prints the reversed
number on the screen. For example if user enter 123 as input then 321 is printed as
output. In our program we use modulus(%) operator to obtain the digits of a number.
To invert number look at it and write it from opposite direction or the output of code
is a number obtained by writing original number from right to left. To reverse or invert
large numbers use long data type or long long data type if your compiler supports it, if
you still have large numbers then use strings or other data structure
Logic of converting upplercase to lowercase and vice versa:ASCII value of A is 65 while a is 97. Difference between them is 97 65 = 32
So if we will add 32 in the ASCII value of A then it will be a and if will we subtract
32 in ASCII value of a it will be A. It is true for all alphabets.
In general rule:
Upper case character = Lower case character 32

50

Fundamental Programming Language Lab Manual

Lower case character = Upper case character + 32


Algorithm:
Step 1: Start.
STEP 2: Take input N.
STEP 3: Initialize S = 0.
STEP 4: Check if N i 0 then go to step 4 else go to the STEP 5.
STEP 5: Compute S = S*10+N%10 and N = N/10 and go to STEP 3.
STEP 6: Print S.
STEP 7: Stop.
Flowchart:

program:
] include h stdio.h i
] include h conio.h i
] include h string.h i
] include h ctype.h i
void main()
{
int num,i,rev=0,dig,ch,str[20];
clrscr();
printf(Menu\n 1.Case Change \n 2.Reverse Digit);
printf(Enter Ur Choice);
scanf(%d,&ch);
switch(ch)

51

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

{
case 1: printf(Enter String:);
scanf(%s,str);
printf(original String: %s,str);
i=0;
while(str[i]!=\0) {
if(str[i]i=65 && str[i]h=90)
str[i]=str[i]+32;
else
str[i]=str[i]-32;
}
printf(converted String is: %s,str);
break;
case 2:
//accept the number to be reversed

printf(Enter number:);
scanf(%d,&num);
while(num i 0)
{
dig=num%10; //extract the digits from unit place
rev=(rev*10)+dig; //concatenate
num=num/10; //units digit gets eliminated
}
printf(Reversal of number:=%d ,rev);
break;
}
getch();
}
Output: Menu:
1.Case Change
2.Reverse Digit
Enter Ur choice:2
Enter Number:321
123
Conclusion: Hence we had studied use of if statement and for loop.

52

Dhole-Patil College of Engineering,pune

Chapter 9
Assignment 9
Title Write a C program to read an integer and display each of digit of the integer
in English.

Objective To learn and understand basic of String and String Operation..


Theory:
1. Switch Case:
The switch statement causes a particular group of statements to be chosen from several
available groups. The selection is based upon the current value of an expression which
is included within the switch statement.
Syntax:
switch (expression)
{
case expression 1:
statement 1;
:
:
break;
case expression 2:
statement 2;
:
:
break;
case expression n:
statement 1;
:
:
break;

53

Fundamental Programming Language Lab Manual

default :
statement ;
}
Where expression is an integer or character value.
Expression following the keyword switch is evaluated. Value of expression is matched
with value that follows case statement. When match is found the statement within that
is executed. To avoid the execution of statements keyword break is used if the control
out of the switch statement.

Algorithm:
Step 1: start
step 2: Initialize necessary variables.
Step 3: Accept integer number.
Step 4: Reverse number.
Step 5: Divide reverse by 10 to get first number.
step 6: print that number using switch case.
step 7: Stop.
Flowchart:

54

Dhole-Patil College of Engineering,pune

START

READ
Number
NO
While
number >0
YES
u=number%10
rev=rev*10+u
number=number/10

While
rev>0
YES
r=rev%10
Rev=rev/10

Switch (r)
Rev=rev/10
If r==0

If r==1

If r==2

If r==3

If r==4

r=rev%10

r=rev%10

r=rev%10

r=rev%10

r=rev%10

Rev=rev/10

Rev=rev/10

Rev=rev/10

Rev=rev/10

Rev=rev/10

STOP

Fundamental Programming Language Lab Manual

program:
] include h stdio.h i
] include h conio.h i
void main(){
int number,rev=0, r,u;
clrscr();
printf(Enter a number: );
scanf(%i, &number);
while(numberi0) {
u=number%10;
rev=rev*10+u;
number=number/10;
}
while(revi0)
{
r=rev%10;
rev=rev/10;
switch (r)
{
case 0 : printf(Zero ); break;
case 1 : printf(One ); break;
case 2 : printf(Two ); break;
case 3 : printf(Three ); break;
case 4 : printf(Four ); break;
case 5 : printf(Five ); break;
case 6 : printf(Six ); break;
case 7 : printf(Seven ); break;
case 8 : printf(Eight ); break;
case 9 : printf(Nine ); break;
default : printf(Unknown Interger ); break;
}
}
getch();}
Output: Enter a number:11043
One one zero four three
Conclusion
Hence we had studied use of Switch Case

56

Dhole-Patil College of Engineering,pune

Chapter 10
Assignment 10
Title
Write a C program to generate first 20 Fibonacci numbers.

Objective
To learn and understand basic of Fibonacci series.

Theory:
1. Fibonacci Series:
The Fibonacci sequence is a set of numbers that starts with a one or a zero, followed by
a one, and proceeds based on the rule that each number (called a Fibonacci number) is
equal to the sum of the preceding two numbers. If the Fibonacci sequence is denoted F
( n ), where n is the first term in the sequence, the following equation obtains for n =
0, where the first two terms are defined as 0 and 1 by convention:
F (0) = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
In some texts, it is customary to use n = 1. In that case the first two terms are defined
as 1 and 1 by default, and therefore:
F (1) = 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
The Fibonacci sequence is named for Leonardo Pisano (also known as Leonardo Pisano
or Fibonacci ), an Italian mathematician who lived from 1170 - 1250. Fibonacci used
the arithmetic series to illustrate a problem based on a pair of breeding rabbits:
How many pairs of rabbits will be produced in a year, beginning with a single pair, if
in every month each pair bears a new pair which becomes productive from the second
month on? The result can be expressed numerically as: 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Fibonacci numbers are of interest to biologists and physicists because they are frequently
observed in various natural objects and phenomena. The branching patterns in trees and
leaves, for example, and the distribution of seeds in a raspberry are based on Fibonacci
numbers.
A Sanskrit grammarian, Pingala, is credited with the first mention of the sequence of

57

Fundamental Programming Language Lab Manual

numbers, sometime between the fifth century B.C. and the second or third century A.D.
Since Fibonacci introduced the series to Western civilization, it has had a high profile
from time to time. Recently, in The Da Vinci Code , for example, the Fibonacci sequence
is part of an important clue. Another application, the Fibonacci poem , is a verse in
which the progression of syllable numbers per line follows Fibonaccis pattern.
textbfAlgorithm:
step 1: Assign required variables i.e. sum=0, a=0, b=1, i=1, num.
step 2: Get the no. of terms up to which u want to generate the Fibonacci no, i.e., num.
step 3: Add a and b to get the next Fibonacci number.
step 4: Assign the value of b to a i.e. a==b.
step 5: Assign the value of sum to b i.e. b=sum.
step 6: Write the value of sum to get next Fibonacci number in the series..
step 7: Increment i with 1 i.e. i=i+1 and repeat step 3,4,5,6 with the last value of i=n(n
is the no. of terms which u want to generate Fibonacci no. series.)
step 8: Stop.
Flowchart:

program:
] include h stdio.h i
] include h conio.h i
void main()
{
int a,b,sum,num,i;

58

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

a=0,b=1,sum=0;
clrscr();
printf(\n Enter the number till which u want the series::);
scanf(%d,&num);
for(i=0;ihnum;i++)
{
sum=a+b;
a=b;
b=sum;

printf(%d,sum);
}
getch();
}
Output:
1 2 3 5 8 13......
Conclusion:
Hence we had studied use of Fibonacci series.

59

Dhole-Patil College of Engineering,pune

Chapter 11
Assignment 11
Title
Write a C program to generate prime numbers between 1 to n.

Objective
To learn and understand basic of Prime Numbers.

Theory:
1.Prime Number and its uses:
A prime number (or a prime) is a natural number greater than 1 that has no positive
divisors other than 1 and itself. A natural number greater than 1 that is not a prime
number is called a composite number. For example, 5 is prime because 1 and 5 are its
only positive integer factors, whereas 6 is composite because it has the divisors 2 and 3
in addition to 1 and 6.
Primes are used in several routines in information technology, such as public-key cryptography, which makes use of properties such as the difficulty of factoring large numbers
into their prime factors. Prime numbers give rise to various generalizations in other
mathematical domains, mainly algebra, such as prime elements and prime ideals.//
Prime number logic:
A number is prime if it is divisible only by one and itself. Remember two is the only
even and also the smallest prime number. First few prime numbers are 2, 3, 5, 7, 11, 13,
17....etc. Prime numbers have many applications in computer science and mathematics.
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Initialize i=1,c=0,count
Step 4: if i h =n goto step 5
if not goto step 10
Step 5: Initialize count=2

60

Fundamental Programming Language Lab Manual

Step 6: if jh=i do the following. If no goto step 7


i)if i% j==0 increment c
ii) increment j
iii) goto Step 6
Step 7: if c== 2 print i
Step 8: Increment i
Step 9: goto step 4
Step 10: Stop
Flowchart:

program:
] include h stdio.h i
] include h conio.h i
int main()
{
int n, i = 3, count, c;
printf(Enter the number of prime numbers required);
scanf(%d,&n);
if ( n i= 1 )
{
printf(First %d prime numbers are :,n);
printf(2);
}

61

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

for ( count = 2 ; count = n ; )


{
for ( c = 2 ; c = i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(%d\n,i);
count++;
}
i++;
}
return 0;
}
Output:
Enter range for prime numbers:5
The prime numbers between 1 to 5:2 3 5
Conclusion:
Hence we had studied prime numbers.

62

Dhole-Patil College of Engineering,pune

Chapter 12
Assignment 12
Title
Write a program in C to compute the GCD of the given two integer.

Objective
To learn and understand basic of GCD..

Theory:
Greatest Common Divisor (GCD):-GCD of Two Numbers is a Largest Positive
Numbers which can divide both numbers without any remainder.for example : GCD of
4 and 8 is 2 since 2 is the largest positive number which can dived 4 as well as 8 without
a remainder.
Logic of HCF or GCD of any two numbers: In HCF we try to find any largest
number which can divide both the number.For example: HCF or GCD of 20 and 30
Both number 20 and 30 are divisible by 1, 2,5,10.
HCF=max (1, 2, 3, 4, 10) =10
Logic for writing program:In mathematics, the Euclidean algorithm[a], or Euclids
algorithm, is a method for computing the greatest common divisor (GCD) of two (usually
positive) integers, also known as the greatest common factor (GCF) or highest common
factor (HCF).
This notion can be extended to polynomials, see Polynomial greatest common divisor,
or to rational numbers (with integer quotients).
Algorithm:
The Greatest Common Divisor, GCD for short, of two positive integers can be computed
with Euclids division algorithm. Let the given numbers be a and b, a = b. Euclids
division algorithm has the following steps:
step 1: Start
Step 2: Compute the remainder c of dividing a by b.
Step 3: If the remainder c is zero, b is the greatest common divisor.

63

Fundamental Programming Language Lab Manual

Step 4: If c is not zero, replace a with b and b with the remainder c. Go back to step
(1).
Step 5: Stop
Flowchart:

program:
] include h stdio.h i
] include h conio.h i
int main() {
int num1, num2, min,i;
printf(Enter two integers: );
scanf(%d %d, &num1, &num2);
min=(num1inum2)?num2:num1; /* minimum value is stored in variable min */
for(i=min;i i =1;i) {
if(num1%i==0 && num2%i==0) {
printf(HCF of %d and %d is %d, num1, num2,i);
break; }
}
return 0;}
Output:Enter two integers: 14 35
HCF of 14 and 35 is 7
Conclusion:Hence we had studied how to find GCD using C programming.

64

Dhole-Patil College of Engineering,pune

Chapter 13
Assignment 13
Title
Write a program in C to compute the factorial of the given positive integer using recursive function.

Objective
To learn and understand basic of Factorial.

Theory:
1. Basic of Factorial:
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product
of all positive integers less than or equal to n. For example,
5! = 5 4 3 2 1 = 120.
The value of 0! is 1, according to the convention for an empty product.
Applications:
Although the factorial function has its roots in combinatorics, formulas involving factorials occur in many areas of mathematics.
1.There are n! different ways of arranging n distinct objects into a sequence, the permutations of those objects.
2.Often factorials appear in the denominator of a formula to account for the fact that
ordering is to be ignored. A classical example is counting k-combinations (subsets of k
elements) from a set with n elements.
2. Recursion:
Recursion is a programming technique that allows the programmer to express operations
in terms of themselves. In C, this takes the form of a function that calls itself. A useful
way to think of recursive functions is to imagine them as a process being performed where
one of the instructions is to repeat the process. This makes it sound very similar to a
loop because it repeats the same code, and in some ways it is similar to looping. On the
other hand, recursion makes it easier to express ideas in which the result of the recursive

65

Fundamental Programming Language Lab Manual

call is necessary to complete the task. Of course, it must be possible for the process
to sometimes be completed without the recursive call. One simple example is the idea
of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will
first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this
is like saying the build wall function takes a height and if that height is greater than
one, first calls itself to build a lower wall, and then adds one a foot of bricks.
3. Factorial with Recursion analysis :

Algorithm:
Step 1: Start
Step 2: Read num
Step 3: Call sub program
Step 4: f=fact(num)
Step 5: Print f value
Step 6: Stop
Sub program:
Step 1: Initialize the f
Step 2: if n= = 0 or n == 1 return 1 to main program if not goto step 3
Step 3: return n*fact(n-1)
step 4: Stop
.
Flowchart:

66

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

program:
] include h stdio.h i
] include h conio.h i
int rec(int num); //prototype void main()
{
double num, fact;
clrscr();
printf( nEnter any number: );

67

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

scanf (% d, & num);


fact=rec (num); //calling
printf(
nFactorial Value = % d, fact);
getch();
}
int rec (int num) //defination
{
int f;
if (num==1)
return (1);
else
f=num*rec(num-1);
return (f);
}
Output:
Enter any Number:5
Factorial Value: 120
Conclusion:
Hence we had studied factorial and recursion function.

68

Dhole-Patil College of Engineering,pune

Chapter 14
Assignment 14
Title
Write a program in C to compute the roots of a quadratic equation.

Objective
To learn and understand basic of roots of a quadratic equation.

Theory:
Algorithm:
step 1 :Read the values of Coefficients and Constant of a Quadratic Equation. i.e., a, b
and c.
Step 2: D= b*b - 4*a*c. (Value of Discriminant)
Step 3: if D0 then display Imaginary Roots
Step 4:if D=0 then display Equal Roots and root is r= -b/2a.
Step 5:if D0 then display Real and Distinct Roots and the roots are
Step 6:r1=(-b + root(D))/2a and r2=(-b - root(D))/2a
Step 7: Stop
program:
] include h stdio.h i
] include h conio.h i
void main(){
int a, b, c, d;
float r1,r2;
printf(Program to find out the roots of a quadratic equation. );
printf(Enter the coefficient of x 2: );
scanf(%d,&a);
printf(Enter the coefficient of x: );
scanf(%d, &b);
printf(Enter the value of the constant: );

69

Fundamental Programming Language Lab Manual

scanf(%d, &c);
printf(The given Quadratic equation is:
n
t (%d)x 2 + (%d)x + (%d) = 0
n
n , a, b, c);
d=(b*b)-(4*a*c);
if (d0)
printf(This equation has Imaginary roots );
else
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
if (d==0)
{
printf(Roots are Real and Equal.
n );
printf(Roots are %f & %f , r1, r1);
}
if (d0)
{
printf(Roots are Real and Distinct. );
printf(Roots are %f & %f , r1, r2);
}
}}
Output: CASE 1: Program to find out the roots of a quadratic equation.
Enter the coefficient of xCASE 1:
Enter the coefficient of x 2: 1
Enter the coefficient of x: -5
Enter the value of the constant: 6
The given Quadratic equation is:(1) x 2 + (-5)x + (6) = 0
Roots are Real and Distinct.
Roots are 3.000000 & 2.000000
Conclusion: Hence we had studied how to compute the roots of quadratic equation.

70

Dhole-Patil College of Engineering,pune

Chapter 15
Assignment 15
Title
Write a program in C to sort n integer using Bubble sort

Objective
To learn and understand basic of Sorting.

Prior Concept:
Array structure

Theory:
Bubble Sort:
Among various other sorting algorithm, bubble sort algorithm is one of the popular and
frequently used algorithm to sort elements either in ascending or descending order.
Bubble sort algorithm starts by comparing the first two elements of an array and swapping if necessary, i.e., if you want to sort the elements of array in ascending order and if
the first element is greater than second then, you need to swap the elements but, if the
first element is smaller than second, you mustnt swap the element. Then, again second
and third elements are compared and swapped if it is necessary and this process go on
until last and second last element is compared and swapped. This completes the first
step of bubble sort.
If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required result. But, for better performance, in second step, last
and second last elements are not compared becuase, the proper element is automatically
placed at last after first step. Similarly, in third step, last and second last and second
last and third last elements are not compared and so on.
A figure is worth a thousand words so, acknowledge this figure for better understanding
of bubble sort.

71

Fundamental Programming Language Lab Manual

Algorithm:
Step 1: Start
Step 2: Read n
Step 3: Initialize i=0
Step 4: if in go to step 5, otherwise go to step 6
Step 5: Read a[i], go to step 4
Step 6: Initialize i=0
Step 7: if in go to step 8, otherwise go to step 13
Step 8: Initialize j=0
Step 9: if j h n go to step 10, otherwise go to step 12
Step 10: if a[i] i a[j], otherwise go to step 11 i) temp=a[i];
ii) a[i]=a[j];
iii) a[j]=temp; go to step 11
Step 11: increment j, go to step 9
Step 12: increment i, go to step 7
Step 13: initialize i=0
Step 14: if in go to step 15, otherwise go to step 16
Step 15: Print a[i], go to step 14
Step 16: Stop.
Flowchart:

72

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Program:
] include h stdio.h i
] include h conio.h i
int main()
{
int array[100], n, c, d, swap;
printf(Enter number of elements\n);
scanf(%d, &n); printf(Enter %d integers\n, n);
for (c = 0; c n; c++)
scanf(%d, &array[c]);
for (c = 0 ; c ( n - 1 ); c++)
{
for (d = 0 ; d n - c - 1; d++)
{
if (array[d] array[d+1]) /* For decreasing order use */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}

73

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

}
}
printf(Sorted list in ascending order:\n);
for ( c = 0 ; c n ; c++ )
printf(%d, array[c]);
return 0;
}
Output:
Enter number of element: 5
Enter 5 integer:5 4 3 2 1
Sorted list in ascending order:1 2 3 4 5
Conclusion:Hence we had studied Bubble sort.

74

Dhole-Patil College of Engineering,pune

Chapter 16
Assignment 16
Title
Write a program in C to compute addition/subtraction/multiplication of two matrices.
use functions to read, display, and addition/subtraction/multiplication of two matrices.

Objective
To learn and understand basic Matrix operation.

Prior Concepts:
One Dimensional Array. Theory:
1.Matrix: In mathematics, a matrix (plural matrices) is a rectangular array[1] of numbers, symbols, or expressions, arranged in rows and columns.[2][3] The individual items
in a matrix are called its elements or entries. An example of a matrix with 2 rows and
3 columns is
"

#
1 9 13
.
20 5 6

Matrices of the same size can be added or subtracted element by element. But the rule
for matrix multiplication is that two matrices can be multiplied only when the number
of columns in the first equals the number of rows in the second. A major application of
matrices is to represent linear transformations, that is, generalizations of linear functions
such as f(x) = 4x.
Applications of matrices are found in most scientific fields. In every branch of physics,
including classical mechanics, optics, electromagnetism, quantum mechanics, and quantum electrodynamics, they are used to study physical phenomena, such as the motion
of rigid bodies. In computer graphics, they are used to project a 3-dimensional image
onto a 2-dimensional screen. In probability theory and statistics, stochastic matrices are
used to describe sets of probabilities; for instance, they are used within the PageRank
algorithm that ranks the pages in a Google search. Matrix calculus generalizes classical
75

Fundamental Programming Language Lab Manual

analytical notions such as derivatives and exponentials to higher dimensions. Compatible matrices.
Two matrices are said to be compatible when they have the same size, that is, the same
number of rows and the same number of columns. When two matrices are compatible
they can be added (or subtracted). Here are four matrices.

"
A=
"
c=

4
0

3 0
0 2

5 2
3

B= 1 3
1
1
0

#
2 2
3

. D= 0 3
1
4 1
#

First consider the size of each of these matrices:


A is 2 X 2 matrix,B is 3 X 2 matrix,C is 2 X 3 matrix,D is 3 X 2 matrix
From these four matrices only B and D are compatible. This means we can calculate B
+ D, B D,D B , but we cannot add or subtract any other pair of these matrices.
Adding and subtracting matrices
When two matrices are compatible we add (or subtract) them by adding (or subtracting)
the elements in corresponding positions
We have seen that B and D have the same size; they are both 3 2 matrices. This means
we can add them by adding elements in the corresponding (that is, th e same) positions:

Note that the answer we get is another matrix of the same size as the ones we started
with.
Similarly, we can find BD by subtracting elements in the corresponding positions.

76

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Since any matrix is the same size as itself we can always add a matrix to itself. If
we do this for matrix A we find:

Matrix Multiplication The Dot Product is where you multiply matching members,
then sum up:
(1, 2, 3) (7, 9, 11) = 17 + 29 + 311 = 58
We match the 1st members (1 and 7), multiply them, likewise for the 2nd members (2
and 9) and the 3rd members (3 and 11), and finally sum them up.
Multidimensional array:
Multidimensional array are defined in much the same manner as one dimensional arrays,
except that separate pair of square brackets is required for each array. Thus a two dimensional array will require two pairs of square brackets, a three dimensional array will
require three pairs of square brackets and so on. It is used to store values having two
dimensions. i.e. Matrix.
Two dimensional array : The declaration of a two dimensional array is as follows.
int m [10] [10]
Here m is declared as a matrix having 10 rows and 10 columns.
The first element in the matrix is m [0][0] and that the last element in the matrix is m
[9][9].
Two dimensional array initialization: Initialization of Two dimensional array during declaration is done as:
int arr [3][3] = 1,2,3,4,5,6,7,8,9;
The result of this initial assignment are as follows:
arr [0] [0] =1
arr [0] [1] =2
arr [0] [2] =3
arr [1] [0] =4
arr [1] [1] =5
arr [1] [2] =6
arr [2] [0] =7
arr [2] [1] =8
arr [2] [2] =9

77

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

The natural order in which the initial values are assigned can be altered by forming
group of initial values enclosed within braces ( i.e. , . ).
int arr [3] [3] = {
{1,2,3};
{4,5,6};
{7,8,9}
;
};
This definition result in the same initial assignment as above.
Accessing two-dimensional array elements:
The elements of a two dimensional array can be accessed by following expression.
arr [i][j]
where i refers to the row number and
j refers to the column number.
The C code will be:
for ( i=0;i3;i++)
{
for ( j=0;j3;j++)
{
printf( \n %d , arr [i][j] );
}
}
program:
] include h stdio.h i
] include h conio.h i
/* MATRIX ADDITION, SUBTRACTION AND MULTIPLICATION */
void main()
{
int i,j,c,r,k;
int a[20][20],b[20][20],ma[20][20],ms[20][20];
int mm[20][20];
clrscr();
printf(INPUT:);
printf();
printf( Enter the value for row and column: );
scanf(%d%d,&c,&r);
printf( Enter the value for matrix A);

78

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
scanf(%d,&a[i][j]);
}
printf( \n);
}
printf( Enter the value for matrix B
n);
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
scanf(%d,&b[i][j]);
}
printf(\n);
}
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
ma[i][j]=a[i][j]+b[i][j];
ms[i][j]=a[i][j]-b[i][j];
}
}
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
mm[i][j]=0;
for(k=0;kh=c;k++)
{
mm[i][j] +=a[i][k]*b[k][j];
}
}
}

79

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

printf( OUTPUT:);
printf(-);
printf( The addition matrix is:
n);
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
printf(%d,ma[i][j]);
}
printf(\n);
}
printf( The subtraction matrix is:
n);
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
printf(%d,ms[i][j]);
}
printf(\n);
}
printf( The multiplication matrix is:
n);
for(i=0;ih=c;i++)
{
for(j=0;jh=r;j++)
{
printf(%d,mm[i][j]);
}
printf(\n);
}
getch();
}
Output:
INPUT:
Enter the value for row and column: 2 2

80

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Enter the value for matrix A


4 3
6 2
Enter the value for matrix B
8 1
0 5
OUTPUT:
- The addition matrix is:
12 4
6 7
The subtraction matrix is:
-4 2
6 -3
The multiplication matrix is:
32 19
48 16
Conclusion: Hence we had studied matrix operation.

81

Dhole-Patil College of Engineering,pune

Chapter 17
Assignment 17
Title
Write a program in C to carry out following operation on string using library functions:
1.To Concatenate a string S2 to string S1
2.To find the length of given string
3.To Compare a two strings S1,S2
4. TO Copy a string S2 to another string S1.

Objective
To learn and understand basic of String and String Operation..

Prior Concept:
1.Variable declaration.
2.Expressions, operators, decision and loop control structure.
3.Array structure

Theory:
1.Function:
A function is a self contained program that carries out a large number of some specific
tasks. There are some built in functions such as strlen( ),strcpy( ) etc. as well there can
be a user defined functions.
String Functions:
String are collection of characters.The functions which are used to carry out different
operations on These characters are called String Functions.String functions are used
to carry out the string manipulations such as joining strings together, comparing the
strings, copying the strings, etc. The most commonly used string functions are
1. strlen ( )
2. strcat ( )
3. strcmp ( )
4. strcpy ( )

82

Fundamental Programming Language Lab Manual

1.strlen ( ) : This function counts and returns the number of characters in a string.
Syntax:
length = strlen ( string );
where length is an integer variable which receives the value of the length of the string.
String is any character string or a constant string. The counting ends at the first null
character.
2.strcat ( ) : This function is used to join two strings together.
Syntax:
strcat (string1, string2 );
where string1 and string2 are separate character arrays. When function strcat ( ) is
executed string2 gets appended to string1 and the null character at the end of string1
is removed.
3.strcmp ( ):
This function compares two strings and returns value 0 if they are equal. If they are not ,
it returns the numeric difference between the first nonmatching characters in the string.
i.e. numeric difference between the ASCII values. Syntax: strcmp (string1,string2);
where string1 and string2 are character arrays.
4.strcpy ( ) : This function copies the content of one string to other string. Syntax:
strcpy ( string1,string2 );
where string1 and string2 are character arrays. The contents of string2 get copied to
string1. The length of string1 should be enough large to receive the contents of string2.

Algorithm:
Step 1: Start.
Step 2: Include all required header files.
Step 3: Input three strings.

83

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Step 4: Compare the entered strings, if they are not equal join them together.
Step 5: Copy the contents of string1 to string3.
Step 6: Display the contents of all there string with their length.
Step 7: Concatenate string1 and String2.
Step 8: Stop.
Flowchart:

program:
] include h stdio.h i
] include h conio.h i
] include h String.h i
void main ( )
{
char str1[10], str2[10], str3[10];
int length1,length2,length3,compare;
clrscr ( );
printf ( \n Enter two strings: \n);
scanf(%s%s,str1,str2);
compare =strcmp(str1,str2);
if ( compare != 0)

84

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

{
printf ( Strings are not equal \n);
strcat (str1,str2);
}
else
{
printf( \n Strings are equal \n);
}
strcpy ( str3,str1);
length1=strlen ( str1);
length2=strlen ( str2);
length3=strlen ( str3);
printf( The string1 is %s\t and length is %d\n, str1,length1);
printf( The string2 is %s\t and length is %d\n, str2,length2);
printf( The string3 is %s\t and length is %d\n, str3,length3);
getch( );
}
Output:
Enter two strings:
C programming
Strings are not equal
The string1 is C and length is 1
The string2 is Rao and length is 11
The string3 is Cprogramming and length is 12
Conclusion:
Hence we had studied String Operation using library function.

85

Dhole-Patil College of Engineering,pune

Chapter 18
Assignment 18
Title:
Find sub-string from string using LISP.
Theory:
Lisp is a functional language well-suited to symbolic AI, based on the -calculus and with
list structures as a very flexible basic data type; programs are themselves list structures,
and thus can be created and manipulated just like other dataL.
Lisp (historically, LISP) is a family of computer programming languages with a long
history and a distinctive, fully parenthesized Polish prefix notation.Originally specified
in 1958, Lisp is the second-oldest high-level programming language in widespread use
today; only Fortran is older (by one year). Like Fortran, Lisp has changed a great deal
since its early days, and a number of dialects have existed over its history. Today, the
most widely known general-purpose Lisp dialects are Common Lisp and Scheme.
Lisp was originally created as a practical mathematical notation for computer programs,
influenced by the notation of Alonzo Churchs lambda calculus. It quickly became the
favored programming language for artificial intelligence (AI) research. As one of the
earliest programming languages, Lisp pioneered many ideas in computer science, including tree data structures, automatic storage management, dynamic typing, conditionals,
higher-order functions, recursion, and the self-hosting compiler.
The name LISP derives from LISt Processing. Linked lists are one of Lisp languages
major data structures, and Lisp source code is itself made up of lists. As a result, Lisp
programs can manipulate source code as a data structure, giving rise to the macro systems that allow programmers to create new syntax or new domain-specific languages
embedded in Lisp.The interchangeability of code and data also gives Lisp its instantly
recognizable syntax. All program code is written as s-expressions, or parenthesized lists.
A function call or syntactic form is written as a list with the function or operators name
first, and the arguments following; for instance, a function f that takes three arguments

86

Fundamental Programming Language Lab Manual

might be called using (f arg1 arg2 arg3).


String functions
Common Lisp has relatively few functions that work exclusively on strings. There is
no function, for example, to extract a substring from a string. However, strings are
defined as specialized vectors of character objects. Since vectors are sequences, all the
sequence-related functions also apply to strings. To extract a substring from a string,
use subseq.Accessor SUBSEQ
Syntax:subseq sequence start &optional end = subsequence
(setf (subseq sequence start &optional end) new-subsequence)
Arguments and Values:sequencea proper sequence.
start, endbounding index designators of sequence. The default for end is nil.
subsequencea proper sequence.
new-subsequencea proper sequence.
Description:subseq creates a sequence that is a copy of the subsequence of sequence
bounded by start and end.Start specifies an offset into the original sequence and marks
the beginning position of the subsequence. end marks the position following the last
element of the subsequence.subseq always allocates a new sequence for a result; it never
shares storage with an old sequence. The result subsequence is always of the same type
as sequence.If sequence is a vector, the result is a fresh simple array of rank one that has
the same actual array element type as sequence. If sequence is a list, the result is a fresh
list.setf may be used with subseq to destructively replace elements of a subsequence with
elements taken from a sequence of new values. If the subsequence and the new sequence
are not of equal length, the shorter length determines the number of elements that are
replaced. The remaining elements at the end of the longer sequence are not modified in
the operation.Examples:
(setq str 012345) 012345
(subseq str 2) 2345
(subseq str 3 5) 34
(setf (subseq str 4) abc) abc
str 0123ab
(setf (subseq str 0 2) A) A
str A123ab
Should be prepared to signal an error of type type-error if sequence is not a proper
sequence. Should be prepared to signal an error of type type-error if new-subsequence
is not a proper sequence.
Conclusion:
Hence we had studied how to find sub-string from string using LISP.

87

Dhole-Patil College of Engineering,pune

Chapter 19
Assignment 19
Title:
Write a program in MATLAB/OCTAVE to compute addition/subtraction/multiplication
of two matrices. use functions to read, display, and addition/subtraction/multiplication
of two matrices.
Objective To learn and understand basic of String and String Operation. Theory:
What is a MATLAB function?
A MATLAB function is a MATLAB program that performs a sequence of operations
specified in a text file (called an m-file because it must be saved with a file extension
of *.m). A function accepts one or more MATLAB variables as inputs, operates on
them in some way, and then returns one or more MATLAB variables as outputs and
may also generate plots, etc. (sometimes a function doesnt return any output variables
but instead just generates plots, etc.). MATLAB is widely used in all areas of applied
mathematics, in education and research at universities, and in the industry. MATLAB
stands for MATrix LABoratory and the software is built up around vectors and matrices.
This makes the software particularly useful for linear algebra but MATLAB is also a
great tool for solving algebraic and differential equations and for numerical integration.
MATLAB has powerful graphic tools and can produce nice pictures in both 2D and 3D.
It is also a programming language, and is one of the easiest programming languages for
writing mathematical programs. MATLAB also has some tool boxes useful for signal
processing, image processing, optimization, etc. How to start MATLAB PC: Choose
the submenu Programs from the Start menu. From the Programs menu, open
the MATLAB submenu. From the MATLAB submenu, choose MATLAB.
Unix: At the prompt, type matlab.
You can quit MATLAB by typing exit in the command window.
The MATLAB environment Note: From now on an instruction to press a certain
key will be denoted by h i, e.g., pressing the enter key will be denoted as henter i. Com-

88

Fundamental Programming Language Lab Manual

mands that should be typed at the prompt, will be written in courier font.
The MATLAB environment (on most computer systems) consists of menus, buttons and
a writing area similar to an ordinary word processor. There are plenty of help functions
that you are encouraged to use. The writing area that you will see when you start
MATLAB, is called the command window. In this window you give the commands to
MATLAB. For example, when you want to run a program you have written for MATLAB you start the program in the command window by typing its name at the prompt.
The command window is also useful if you just want to use MATLAB as a scientific
calculator or as a graphing tool. If you write longer programs, you will find it more
convenient to write the program code in a separate window, and then run it in the command window.
In the command window you will see a prompt that looks like i i . You type your
commands immediately after this prompt. Once you have typed the command you wish
MATLAB to perform, presshenter i. If you want to interupt a command that MATLAB
is running, type hctrl i+hc i.
The commands you type in the command window are stored by MATLAB and can be
viewed in the Command History window. To repeat a command you have already used,
you can simply double-click on the command in the history window, or use the hup
arrow iat the command prompt to iterate through the commands you have used until
you reach the command you desire to repeat.
Useful functions and operations in MATLAB
Using MATLAB as a calculator is easy.
Example: Compute 5 sin(2.53-pi)+1/75. In MATLAB this is done by simply typing
5 sin(2.5( 3 pi)) + 1/75
at the prompt. Be careful with parantheses and dont forget to type * whenever you
multiply!
Note that MATLAB is case sensitive. This means that MATLAB knows a difference
between letters written as lower and upper case letters. For example, MATLAB will
understand sin(2) but will not understand Sin(2).
Here is a table of useful operations, functions and constants in MATLAB.

89

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

Obtaining Help on MATLAB commands:


To obtain help on any of the MATLAB commands, you simply need to type
help command
at the command prompt. For example, to obtain help on the gamma function, we type
at the command prompt:
help gamma
Try this now. You may also get help about commands using the Help Desk, which
can be accessed by selecting the MATLAB Help option under the Help menu.
Note that the description MATLAB returns about the command you requested help
on contains the command name in ALL CAPS. This does not mean that you use this
command by typing it in ALL CAPS. In MATLAB, you almost always use all lower case
letters when using a command.
Variables in MATLAB:
We can easily define our own variables in MATLAB. Lets say we need to use the value of
3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote
this variable as x by typing the following:
x=3.5*sin(2.9)
(Please try this in MATLAB.) Now type
x+1
and observe what happens. Note that we did not need to declare x as a variable that is

90

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

supposed to hold a floating point number as we would need to do in most programming


languages.
Often, we may not want to have the result of a calculation printed-out to the command
window. To supress this output, we put a semi-colon at the end of the command; MATLAB still performs the command in the background. If you defined x as above, now
type
y=2*x;
y
and observe what happened.
In many cases we want to know what variables we have declared. We can do this by typing whos. Alternatively, we can view the values by openning the Workspace window.
This is done by selecting the Workspace option from the View menu. If you want to
erase all variables from the MATLAB memory, type clear. To erase a specific variable,
say x, type clear x. To clear two specific variables, say x and y, type clear x y, that is
separate the different variables with a space. Variables can also be cleared by selecting
them in the Workspace window and selecting the delete option.
Vectors and matrices in MATLAB
We create a vector in MATLAB by putting the elements within [] brackets.
Example: x=[ 1 2 3 4 5 6 7 8 9 10]
We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can
be created by typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.
Matrices can be created according to the following example. The matrix A= is created
by typing:
A=[1 2 3 ; 4 5 6; 7 8 9],
i.e., rows are separated with semi-colons. If we want to use a specific element in a vector
or a matrix, study the following example:
Example:
x=[10 20 30]
A=[ 1 2 3 ; 4 5 6 ; 7 8 9]
x(2)
A(3,1)
Here we extracted the second element of the vector by typing the variable and the position within parantheses. The same principle holds for matrices; the first number specifies
the row of the matrix, and the second number specifies the column of the matrix. Note
that in MATLAB the first index of a vector or matrix starts at 1, not 0 as is common
with other programming languages.
If the matrices (or vectors which are special cases of a matrices) are of the same dimen-

91

Dhole-Patil College of Engineering,pune

Fundamental Programming Language Lab Manual

sions then matrix addition, matrix subtraction and scalar multiplication works just like
we are used to.
Example: Type
x=[1 2 3]
y =[4 5 6]
a=2
x+y
x-y
a*x
and observe what happens.
If want to apply an operation such as squaring each element in a matrix we have to
use a dot . before the operation we wish to apply. Type the following commands in
MATLAB.
x=1:10
x.2
A=[1 2 3 ; 4 5 6 ; 7 8 9 ]
A.2
A2
and observe the result. The dot allows us to do operations elementwise. All built-in
functions such as sin, cos, exp and so on automatically act elementwise on a matrix. Type
y=[0 1/4 1/2 3/4 1]
y=pi*y
sin(y)
and observe the result.
Conclusion: Hence we had studied program in MATLAB/OCTAVE to compute addition/subtraction/multiplication of two matrices. use functions to read, display, and
addition/subtraction/multiplication of two matrices.

92

Dhole-Patil College of Engineering,pune

Chapter 20
Assignment 20

Title:
Write a program in Eclipse- Python to generate prime numbers between 1 to n
Objective
To learn and understand basic of Eclipse- Python.
Theory:
1. Install Python 2.7.1 from http://www.python.org/download/releases/2.7.1/ Download the Windows x86 MSI Installer and run it (you must have admin privileges). Use
all the default settings. When the install completes, youll have a Python (command
line) shortcut available from your Start menu.
2. Install Eclipse Helios (3.6.1) from http://www.eclipse.org/downloads/ The Eclipse
IDE for Java Developers should be sufficient.
3. Install PyDev for Eclipse by following the directions at http://pydev.org/manual 101 install.h
under the heading Installing with the update site. Use the http://pydev.org/updates
URL to get the main update. Select PyDev from the list of updates.
4. Follow the instructions at http://pydev.org/manual 101 interpreter.html to configure the PyDev Python command-line interpreter for Eclipse. You do not need to worry
about the Jython or Iron Python interpreters. If you used the defaults when installing
Python in step (1), you should find the Python interpreter at C:\Python27\python.exe.
5. Now create a new PyDev project by following the instructions under Create a Project
at http://pydev.org/manual 101 project conf.html. Then create a new module called
example by following the directions at http://pydev.org/manual 101 first module.html.
You should then place an output statement in example.py and run it by following the
directions at http://pydev.org/manual 101 run.html.
Now read through the Python Quick Guide at
http://www.tutorialspoint.com/python/python quick guide.htm
which will give you a quick overview of the language. You may want to try out some of

93

Fundamental Programming Language Lab Manual

the syntax from the Guide in an interactive command-line interpreter. Start the Python
interpreter by using the Python (command line) shortcut option from your Start menu.
Then enter commands like so:
print Hello, Python!
Hello, Python!
Once you have read through the Guide, create a program called prime.py which will first
ask the user to enter a number N and then print all the prime numbers from 2 to N. To
determine if a single number is prime, create a boolean function called is prime().
printprimes.py
1 max value = eval(input(Display primes up to what value? ))
2 value = 2 ] Smallest prime number
3 while value = max value:
4]See if value is prime
5 is prime = True ] Provisionally, value is prime
6 ] Try all possible factors from 2 to value - 1
7 trial factor = 2
8 while trial factor value:
9 if value % trial factor == 0:
10 is prime = False; ] Found a factor
11 break ] No need to continue; it is NOT prime
12 trial factor += 1]Try the next potential factor
13 if is prime:
14 print(value, end= ) ] Display the prime number
15 value += 1]Try the next potential prime number
16 print() ]Move cursor down to next line
Heres how the program should run:
Enter a number: 11
Prime numbers:
2 3 5 7 11
Conclusion:
Hence we had studied use of Eclipse- Python.

94

Dhole-Patil College of Engineering,pune

Vous aimerez peut-être aussi