Professional Documents
Culture Documents
LAB MANUAL
[V- 1]
Group C
Sessions
1 Write a program in Eclipse-Python to generate prime numbers between 1 and n.
References
Vision: -
To satisfy the aspirations of youth force who want to lead the nation towards prosperity
through techno economic development.
Mission: -
To provide, nurture and maintain an environment of high academic excellence, research and
entrepreneurship for all aspiring students which will prepare to face global challenges maintaining
high ethical and moral standards.
Quality Policy: -
We at Rajarshi Shahu College of Engineering are committed to maximize student
satisfaction through improved performance by imparting value based quality education.
1
How to Use This Manual
This Manual assumes that the facilitators are aware of Collaborative Learning Methodologies.
This Manual will only provide them tool they may need to facilitate the session on
Fundamentals of Programming Languages – I module in collaborative learning environment.
2
Disk Approach- Digital Blooms Taxonomy
Creating
Evaluating
Analyzing
Applying
Understanding
Remembering
3
Practical Session Plan
Academic Year: 2015-2016/Semester: I
CLASS: F.E.
Subject: Fundamentals of Programming Languages-I Name of Faculty:
Teaching scheme: Examination scheme:
Practical: 2 hrs / week Online: 50 Marks
Outcomes
Experiment Planed Actual Reference
Description Objectives (Students will
No. Dates Dates used
be able to)
GROUP-A
Use and study of R2,L1 To use and Illustrate basics
Linux GUI and PPT study of Linux of Linux GUI
1 commands GUI and operations and
commands. terminal
commands.
Handling and use R5,L2, 1. To learn the Design and
of Eclipse editor PPT handling and develop a
for creating use of Eclipse simple program
projects in C, editor. in C, Java and
Python(pydev), 2. To Python using
Java understand Eclipse editor.
2
procedure to
create projects
in Eclipse
using C,
Python and
Java.
Using Eclipse to R5,L2, To implement Develop a
write/test “Hello! PPT “Hello World” simple “Hello
World” program in program in World!”
3 C, Python. Eclipse IDE program in
using C, Java eclipse editor
and Python. using C, Java
and Python.
GROUP-B
Write a C program R3, PPT 1. To learn Develop simple
to accept five how to accept program to
numbers from and display display the
console and then to values on numbers using
1 display them back console. an array.
on console in 2. To study
ascending order. one
dimensional
array.
Write a C program R3,R4, To study about Make use of
to calculate the sum PPT control for loop in
of all numbers from structure (for program.
2
0 to 100(both loop).
inclusive) that all
divisible by 4.
3 Write a program in R3,R4, 1. To Develop C
C to accept the PPT categorize program using
length of three triangles by nested if…else
sides of a triangle their sides. logic.
4
from console and 2. To study the
print the type of concept of
triangle - nested if...else.
equilateral,
isosceles, right
angled or none of
these.
Write a program in R3,R4, To learn Create
C to generate first PPT concept of fibonacci series
20 fibonacci fibonacci using for loop
4
numbers. series. in c
programming
language.
Write a program in R3,R4, To understand Make use of
C to compute the PPT mathematical if… else in
GCD of the given concept of program.
5
two integers. GCD and
develop
program.
Write a C program R3,R4, To learn the Develop C
to find prime PPT basic concept program to find
numbers between 1 of nested for prime number
6
to n. loop to find between 1 to n
prime using for loop.
numbers.
Write a C program R3,R4, 1. To Develop C
to sort n integers PPT understand program using
using bubble sort. concept of bubble sort.
sorting.
7
2. To learn
different
sorting
techniques.
Write a program in R3,R4, To understand Apply library
C to carry out PPT the C library functions in C
following functions for to perform
operations on String. different String
strings using operations.
library functions
a. To concatenate
a string s2 to
string s1.
8
b. To find the
length of a
given string
c. To compare
two strings s1
and s2.
d. To copy a
string s2 to
another string
s1.
GROUP-C
1 Write a program in To learn how Design and
5
eclipse-python to to create a develop a
generate prime program in prime number
numbers between 1 Eclipse editor program in
and n. using Python. Eclipse editor
using python.
Reference Books :
R1: William Shotts, “The Linux Command Line”.
R2: John Purcell,”Linux Complete Command Reference”.
R3: Yashavant Kanetkar, “Let Us c”- 7th Edition BPB Publications.
R4:E. Balagurusamy, “ Programming in ANSI C” Tata McGraw Hill
R5:Herbert Schildt ,”Java 2: The Complete Reference”, Tata McGraw-Hill-5th Edition
R6: Mark Lutz,” Learning Python: Powerful Object-Oriented Programming”- 5th Edition
Links :
1. http://www.w3schools.com/html/
2.
6
Assignment 1
Aim: Use and study of LINUX GUI and commands.
Software Required :
Fedora Operating System
Theory:
1. Ls
Syntax
ls [options] [names]
List contents of directories. If no names are given, list the files in the current directory. With one or
more names, list files contained in a directory name or that match a file name. Names can include file
name meta characters. The options let you display a variety of information in different formats.
Options Description
Do not move a non directory that has an existing destination with the same or
-u newer modification time.
--update
-V METHOD Change the type of backups made with `-b'
--version-
control
3. rmdir
Syntax
7
rmdir [options]... folder(s)...
Remove directory, this command will only work if the folders are empty.
Options Description
-p, --parents Remove explicit parent directories if being emptied
--verbose Output a diagnostic for every directory processed
--help Display help and exit
--version Output version information and exit
4. who
Syntax
who [options] [file] [am i]
Print who is currently logged in
Options Description
-m Print the current user id, name and domain(Same as `who am i')
-q
Print only the login names and the number of users logged on.
-s
Ignored; for compatibility with other versions of `who'.
-I
After the login time, print the number of hours and minutes that
-u
the user has been idle. `.' means the user was active in last
--idle
minute. `old' means the user was idle for more than 24 hours.
-l
This is not the default because it can cause significant delays on
--lookup
Systems with automatic dial-up internet access.
-H
--heading Print a line of column headings.
5. whoami
Syntax
whoami [options]
Print the current user id and name.
Options Description
6. chown
Syntax
chown [Options]... NewOwner File...
8
chown [Options]... :Group File...
chown [Options]... --reference=RFILE File...
Change owner, change the user and/or group ownership of each given File to a new Owner.
Chown can also change the ownership of a file to match the user/group of an existing reference file.
Options Description
-c Verbosely describe the action for each FILE whose ownership actually changes.
--changes Do not act on symbolic links themselves but rather on what they point to.
--dereference
-f Do not print error messages about files whose ownership cannot be changed.
--silent
--quiet
7. chmod
Syntax
8. chgrp
Syntax
chgrp [Options]... {Group | --reference=File} File...
Change group ownership 'chgrp' changes the group ownership of each given File to Group
(which can be either a group name or a numeric group id) or to match the same group as an existing
reference file.
Options Description
-c Verbosely describe the action for each File whose group actually
changes.
--changes
-f Do not print error messages about files whose group cannot be
changed.
--silent, --quiet
-f
--no-dereference Act on symbolic links themselves instead of what they point to.
9. passwd
Syntax
passwd [options...]
Modify a user password. If no options are specified - passwd will change the password of the
currently logged in user - will prompt for the old and new passwords.
Options Description
-d, --delete delete the password for the named account (root only)
-f, --force force operation
-k, --keep-tokens keep non-expired authentication tokens
9
-l, --lock lock the named account (root only)
-S, --status report password status on the named account (root only)
10. tty
Syntax
tty [option]...
Print file name of terminal on standard input, print the file name of the terminal connected
to standard input. It prints `not a tty' if standard input is not a terminal.
OPTIONS
-s
--silent
--quiet Print nothing; only return an exit status.
Exit status:
0 if standard input is a terminal
1 if standard input is not a terminal
2 if given incorrect arguments
3 if a write error occurs
Options Description
-H Set the HOME environment variable to the homedir of the target
user as specified in passwd. By default, sudo does not modify HOME .
like kill (-k) except that it removes the user's timestamp entirely.
-K Like -k, this option does not require a password.
list defaults, list out the parameters that may be set in a Defaults line
-L along with a short description for each.
Preserve group vector, causes sudo to preserve the invoking user's group
-P vector unaltered.
-S stdin, read the password from the standard input instead of the terminal.
12. Shutdown
Syntax
shutdown [options] when [message]
Shutdown or restart Linux
Options Description
-c Cancel a shutdown that is in progress
-f Reboot fast, by suppressing the normal call to fsck
-h When rebooting Halt the system when shutdown is complete.
-k Print the warning message, but suppress actual shutdown
-n Perform shutdown without a call to in it.
-r Reboot the system when shutdown is complete.
-t sec Ensure a sec-second delay between killing processes and
Changing the run level.
Conclusion:
In this way, we have studied LINUX GUI and commands.
10
Viva Question
I. How did it come about that most people call the system “Linux”?
Calling the system “Linux” is a confusion that has spread faster than the corrective
information. The people who combined Linux with the GNU system were not aware that
that's what their activity amounted to. They focused their attention on the piece that was
Linux and did not realize that more of the combination was GNU. They started calling it
“Linux” even though that name did not fit what they had. It took a few years for us to realize
what a problem this was and ask people to correct the practice. By that time, the confusion
had a big head start.
II. Should we always say “GNU/Linux” instead of “Linux”?
Not always—only when you're talking about the whole system. When you're referring
specifically to the kernel, you should call it “Linux”, the name its developer chose.
When people call the whole system “Linux”, as a consequence they call the whole system by
the same name as the kernel. This causes many kinds of confusion, because only experts can
tell whether a statement is about the kernel or the whole system. By calling the whole system
“GNU/Linux”, and calling the kernel “Linux”, you avoid the ambiguity.
III. Would Linux have achieved the same success if there had been no GNU?
In that alternative world, there would be nothing today like the GNU/Linux system, and
probably no free operating system at all. No one attempted to develop a free operating system
in the 1980s except the GNU Project and (later) Berkeley CSRG, which had been specifically
asked by the GNU Project to start freeing its code.
Linus Torvalds was partly influenced by a speech about GNU in Finland in 1990. It's
possible that even without this influence he might have written a Unix-like kernel, but it
probably would not have been free software.
IV. Wouldn't it be better for the community if you did not divide people with this request?
When we ask people to say “GNU/Linux”, we are not dividing people. We are asking them
to give the GNU Project credit for the GNU operating system. This does not criticize anyone
or push anyone away.
However, there are people who do not like our saying this. Sometimes those people push us
away in response. On occasion they are so rude that one wonders if they are intentionally
trying to intimidate us into silence. It doesn't silence us, but it does tend to divide the
community, so we hope you can convince them to stop.However, this is only a secondary
cause of division in our community. The largest division in the community is between people
who appreciate free software as a social and ethical issue and consider proprietary software a
social problem (supporters of the free software movement), and those who cite only practical
benefits and present free software only as an efficient development model (the open source
movement).
V. Doesn’t the GNU project support an individual’s free speech rights to call the system by any
name that individual choose?
Yes, indeed, we believe you have a free speech right to call the operating system by any
name you wish. We ask that people call it GNU/Linux as a matter of doing justice to the
GNU project, to promote the values of freedom that GNU stands for, and to inform others
that those values of freedom brought the system into existence.
Teaching Material :
Textbook
PPT
Assignment 2
Aim: Handling and use of Eclipse Editor for creating projects in C, Python, JAVA.
Objective:
11
1. To learn the Handling of Eclipse Editor.
2. To understand procedure to create projects in eclipses using ‘C’, Python, Java.
Expected Outcome: Students will be able to
Design and Develop a Simple Program in C, JAVA,
and Python by using Eclipse Editor.
Software Required :
For the installation of eclipse JRE must be installed
JDK Latest update for Java
Cygwin/MinGW is required for Windows
CDT for C project Development
Hardware Requirements(Minimum):
P-IV machine
2 GB RAM
10 GB Hard disk
12
Step 1: Open Eclipse IDE
When eclipse IDE is opened for the first time, the ‘welcome’ window is displayed.
One should close welcome window.
13
Creating a Python project in eclipse IDE
PyDev is a plugin that enables Eclipse to be used as a Python IDE (supporting also
Jython and IronPython). It uses advanced type inference techniques to provide features such code
completion and code analysis, while still providing many others such as a debugger, interactive console,
refactoring, etc.
Following steps should be followed to create a Python project in eclipse IDE
Step 1: Windows->Open Perspective->Other..
The following Window will be opened. In this windows, select PyDev and click on ok
14
Step 2: We get Java perspective for implementing Java program
Conclusion:
In this way, we have studied eclipse IDE.
We understood the perspectives for creating projects in C, Python and Java
Viva Questions
I. What is Python?
Python is a dynamic, strongly typed, object oriented, multipurpose programming language,
designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform
syntax.
II. What is Eclipse IDE?
Eclipse is a Java-based open source platform that allows a software developer to create a customized
development environment (IDE) from plug-in components built by Eclipse members. Eclipse is managed
and directed by the Eclipse.org Consortium.
II. What is JRE?
The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java
Development Kit (JDK), a set of programming tools for developing Java applications. The Java
Runtime Environment provides the minimum requirements for executing a Java application; it
consists of the Java Virtual Machine (JVM), core classes, and supporting files.
Teaching Material :
Textbook
PPT
15
Assignment 3
Aim: Using Eclipse to write/test “Hello! World” Program in C, Python
Objective:
1. To implement “Hello World” program in ‘C’ and Python using Eclipse IDE.
Expected Outcome: Students will be able to
Develop a Simple Hello! World Program in C, JAVA
and Python using Eclipse Editor.
Software Required :
For the installation of eclipse JRE must be installed
JDK Latest update for Java
Cygwin/MinGW is required for Windows
CDT for C project Development
Hardware Requirements(Minimum):
P-IV machine
2 GB RAM
10 GB Hard disk
Theory :
Step 1: Creating a ‘C’ project: to create a C project, follow the following procedure.
i. File->New->Project
16
iii. Click on Next button and we get the following window/
Give suitable project name and then from project type, select empty project and from
toolchains select Cygwin gcc and click on next button.
iv. Click on next button and we get following window then Click on finish button.
17
vi. Type c program in edit window and Compile it.
a. For compilation, do this Project->Build Project
b. Save your project File->Save/Use toolbar icon to save project/Use short cut key clt+c
18
d. After the execution of C program, we get the following output.
19
Step 2: To create a python project File->New->PyDev Project
Give appropriate name for the project. Choose the project type as Python. Configure an interpreter for
python. And select Create ‘src’ folder and add it to the PYTHONPATH. Click on
20
Step 4: Click on python file PyDev Module and following will open. Give suitable name e.g. hello
Step 5: Double click on hello.py and following window will open. Select empty from template.
21
Step 6: Edit python program in the edit windows.
22
Step 9: We get the following output.
Conclusion:
In this way, we have studied Eclipse IDE and developed program in C, Java and Python.
Viva Questions
Let us write a simple Python program in a script. Python files have extension .py. Type the following
source code in a test.py file:
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows
$ python test.py
Hello, Python!
II. What is Java technology and why do we need it?
Java is a programming language and computing platform first released by Sun Microsystems in
1995. There are lots of applications and websites that will not work unless you have Java installed, and more
are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to
scientific supercomputers, cell phones to the Internet, Java is everywhere
Teaching Material :
Textbook
PPT
23
GROUP B
Assignment 1
Aim: Write a C program to accept five numbers from console and then display them back on the console in
ascending order.
Objective:
1. To study one dimensional array.
2. To learn how to accept and display values on console in ascending order.
Expected Outcome: Students will be able to
Develop simple program to display values in
ascending order using C language.
Software Required :
Turbo C
Theory:
The Arrays are used in C to represent structures of consecutive elements of the same type.
The definition of a (fixed-size) array has the following syntax:
int array[100];
which defines an array named array to hold 100 values of the primitive type int.
Description of program:
Accessing elements
The primary facility for accessing the values of the elements of an array is the array subscript
operator. To access the i-indexed element of array, the syntax would be array[i], which refers to the value
stored in that array element.
Array subscript numbering begins at 0. The largest allowed array subscript is therefore equal to
the number of elements in the array minus 1. To illustrate this, consider an array a declared as having 10
elements; the first element would be a[0] and the last element would be a[9]. C provides no facility for
automatic bounds checking for array usage. Though logically the last subscript in an array of 10 elements
would be 9, subscripts 10, 11, and so forth could accidentally be specified, with undefined results.
Due to array↔pointer interchangeability, the addresses of each of the array elements can be
expressed in equivalent pointer arithmetic. The following table illustrates both methods for the existing
array:
Similarly, since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent
to *(i+a), the expression can also be written as i[a] (although this form is rarely used).
.
Algorithm:
Start.
Declare the one dimensional array.
Take input from user.
24
Find the minimum value in the list
Swap it with the value in the first position
int i, j; /* iterators*/
int temp; /* temporary store for swapping */
int numbers[5]; /* to stre numbers */
clrscr();
/* Display a message that we need 5 numbers */
printf("Please enter five numbers\n");
I. What is C language?
A high-level programming language developed by Dennis Ritchie at Bell Labs in the mid 1970s.
Although originally designed as a systems programming language, C has proved to be a
powerful and flexible language that can be used for a variety of applications, from
business programs to engineering. C is a particularly popular language for personal
computer programmers because it is relatively small -- it requires less memory than other
languages.
Teaching Material :
Video
PPT
Assignment 2
26
Aim: Write C program to calculate the sum of all numbers from 0 to 100 (both inclusive) that are divisible
by 4.
Objective:
To study the concept of control structure (for loop).
Software Required :
Turbo C
Theory:
Introduction to C
C is a general-purpose, imperative computer programming language. It supports structured
programming, lexical variable scope and recursion, while a static type system prevents many unintended
operations. By design, C provides constructs that map efficiently to typical machine instructions, and
therefore it has found lasting use in applications that had formerly been coded in assembly language,
including operating systems, as well as various application software for computers ranging from
supercomputers to embedded systems.
C was originally developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs, and used
to (re-)implement the Unix operating system. It has since become one of the most widely used programming
languages of all time, with C compilers from various vendors available for the majority of existing computer
architectures and operating systems. C has been standardized by the American National Standards Institute
(ANSI) since 1989 and subsequently by the International Organization for Standardization (ISO).
Form of a C program
C is made up entirely of building blocks which have a particular `shape' or form. The form is the same
everywhere in a program, whether it is the form of the main program or of a subroutine. A program is made
up of functions, functions are made up of statements and declarations surrounded by curly braces { }.
The basic building block in a C program is the function. Every C program is a collection of one or more
functions, written in some arbitrary order. One and only one of these functions in the program must have the
name main(). This function is always the starting point of a C program, so the simplest C program would be
just a single function definition:
main ()
{
}
The parentheses () which follow the name of the function must be included even though they apparently
serve no purpose at this stage. This is how C distinguishes functions from ordinary variables.
The function main() does not have to be at the top of a program so a C program does not necessarily start at
27
line 1. It always starts where main() is. Also, the function main() cannot be called from any other function in
the program. Only the operating system can call the function main(): this is how a C program is started.
The next most simple C program is perhaps a program which calls a function do_nothing and then ends.
/* Program : do nothing */
main() /* Main program */
{
do_nothing();
}
do_nothing() /* Function called */
{ }
The program now consists of two functions, one of which is called by the other. There are several new
things to notice about this program. Firstly the function do_nothing() is called by typing its name followed
by the characteristic () brackets and a semi-colon. This is all that is required to transfer control to the new
function. In some languages, words like CALL or PROC are used, or even a symbol like &. No such thing is
needed in C. The semi-colon is vital however. All instructions in C must end with a semi-colon. This is a
signal to inform the compiler that the end of a statement has been reached and that anything which follows
is meant to be a part of another statement. This helps the compiler diagnose errors.
The `brace' characters { and } mark out a block into which instructions are written. When the program meets
the closing brace } it then transfers back to main() where it meets another } brace and the program ends.
This is the simplest way in which control flows between functions in C. All functions have the same status
as far as a program is concerned. The function main() is treated just as any other function. When a program
is compiled, each function is compiled as a separate entity and then at the end the linker phase in the
compiler attempts to sew them all together.
The examples above are obviously very simple but they illustrate how control flows in a C program. Here
are some more basic elements which we shall cover.
comments
preprocessor commands
functions
declarations
variables
28
statements
typename variablename1,..,..,variablenameN;
For example:
Int i,j;
Char ch;
Double x, y, z, Fred;
Unsigned long int Name_of_Variable;
For is an entry controlled loop this is used when an action is to be repeated for predefined numbers.
Syntax
for (Initial value; Test ; Increment / Decrement )
{
Action 1;
}
Action 2;
Increment/Decrement: In this part we may increment or decrement the counter depends upon
condition.
Algorithm:
1. Start
2. Initialize one variable i check the nos.
29
3. Initialize another variable sum to calculate the sum of no’s divisible by 4
4. Check the counter i from 0 to 100 such that i%4 value is zero
5. If it is zero then increase value of sum by i that is sum = sum+i
6. Print the addition that is sum
7. Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sum=0;
n=100;
for(i=0;i<=n;i++)
{
if(i%4==0)
{
sum=sum+i;
}
printf("%d",sum);
getch();
}
Output:
sum=1300
Conclusion:
Thus, we have studied the control structure by using for loop & printed the sum of all numbers
from 0 to 100 which are divisible by 4.
30
Viva Questions
C programming language provides the following types of loop to handle looping requirements.
nested loops You can use one or more loop inside any another
while, for or do...while loop.
Teaching Material :
Video
PPT
31
Assignment 3
Aim: Program in C to accept the length of three sides of a triangle from console and print the type of
triangle - equilateral, isosceles, right angled or none of these.
Objective:
1. To categorize triangles by their sides and develop a program using nested if...else.
Expected Outcome: Students will be able to
Develop C program using nested if…else logic.
Software Required :
Fedora Operating System with Eclipse
Theory:
Properties of Equilateral Triangle:-
All sides are equal
Algorithm:
-------------------------------------------------------------------------------------------------
32
1. Read the value of three sides. i.e., a, b & c
2. If a+b<c or b+c<a or a+c<b, then display "Invalid Triangle"
3. (Triangle Rule: Sum of two sides should be greater than the third side.)
4. if all sides are equal, i.e., a=b=c then display "EQUILATERAL TRIANGLE"
5. if two sides are equal, i.e., a=b or b=c or c=a then display "ISOSCELES TRIANGLE."
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"
7. OTHERWISE.
8. Display "SCALENE"... i.e., each side is different.
9. End
Program:
#include <conio.h>
#include <stdio.h>
void main()
{
int x,y,z;
printf("\nEnter the sides of a triangle");
scanf("%d %d %d",&x,&y,&z);
if((x==y) && (y==z))
{
printf("\nThe triangle is equilateral");
33
}
else if((x==z) || (y==z) || (x==y))
{
printf("\nThe triangle is isoseles");
}
else
{
printf("\nThe triangle is scalene");
}
getch();
}
Output :
Enter the sides of a triangle
12
10
12
The triangle is isosceles
Conclusion:
Thus, we have implemented a program to accept the length of three sides of a triangle
from console and print the type of triangle - equilateral, isosceles, right angled or none of these.
Viva Questions
In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
Decision control
Syntax Description
statements
if (condition) In these type of statements, if condition is true, then
if
{ Statements; } respective block of code is executed.
if (condition)
In these type of statements, group of statements are
{ Statement1; Statement2; }
if…else executed when condition is true. If condition is
else
false, then else part statements are executed.
{ Statement3; Statement4; }
if (condition1){ Statement1; }
If condition 1 is false, then condition 2 is checked
else_if(condition2)
nested if and statements are executed if it is true. If condition
{ Statement2; }
2 also gets failure, then else part is executed.
else Statement 3;
int main()
{
int m=40,n=40;
if (m == n)
34
{
printf("m and n are equal");
}
}
Output:
m and n are equal
In C if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output:
m and n are not equal
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
Output:
m is greater than n
Teaching Material :
PPT
35
Assignment 4
Aim: Write a program in C to generate first 20 Fibonacci numbers.
Objective:
To learn concept of Fibonacci Series.
Expected Outcome: Students will be able to
Create Fibonacci Series using for loop in c programming language.
Software Required :
Fedora Operating System with Eclipse
Theory :
Consider an elementary example of geometric growth - asexual reproduction, like that of
the amoeba. Each organism splits into two after an interval of maturation time characteristic of
the species. This interval varies randomly but within a certain range according to external
conditions, like temperature, availability of nutrients and so on. We can imagine a simplified
model where, under perfect conditions, all amoebae split after the same time period of growth.
So, one amoeba becomes two, two become 4, then 8, 16, 32, and so on.
An =2An
This of course leads to exponential growth, one characteristic pattern of population growth.
Now in the Fibonacci rabbit situation, there is a lag factor; each pair requires some time to mature. So we
are assuming
If you were to try this in your backyard, here's what would happen:
The pattern we see here is that each cohort or generation remains as part of the next, and in addition, each
grown-up pair contributes a baby pair. The number of such baby pairs matches the total number of pairs in
the previous generation. Symbolically
36
So we have a recursive formula where each generation is defined in terms of the previous two generations.
Using this approach, we can successively calculate fn for as many generations as we like.
Pascal's response is to invent an entirely new branch of mathematics, the theory of probability. This theory
has grown over the years into a vital 20th century tool for science and social science. Pascal's work leans
heavily on a collection of numbers now called Pascal's Triangle, and represented like this:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int f1,f2,f3,i;
clrscr(); f1=0;
f2=1;
printf(“First 20 Fibonacci Numbers are:”);
printf("\n\n%d %d",f1,f2);
for(i=3;i<=20;i++)
{
f3=f1+f2;
printf(" %d",f3);
f1=f2;
f2=f3;
}
getch();
}
Output :
Viva Qusetions
Here is a listing of C language interview questions on “For Loops” along with answers, explanations and/or
solutions:
1. The following code ‘for(;;)’ represents an infinite loop. It can be terminated by.
a) break
b) exit(0)
c) abort()
d) All of the mentioned
Answer:a
2. The correct syntax for running two variable for loop simultaneously is.
a) for (i = 0; i < n; i++)
for (j = 0; j < n; j += 5)
b) for (i = 0, j = 0;i < n, j < n; i++, j += 5)
c) for (i = 0; i < n;i++){}
for (j = 0; j < n;j += 5){}
37
d) None of the mentioned
Answer:b
3. Which for loop has range of similar indexes of 'i' used in for (i = 0;i < n; i++)?
a) for (i = n; i>0; i–)
b) for (i = n; i >= 0; i–)
c) for (i = n-1; i>0; i–)
d) for (i = n-1; i>-1; i–)
Answer:d
4. Which of the following cannot be used as LHS of the expression in for (exp1;exp2; exp3) ?
a) Variable
b) Function
c) typedef
d) macros
Answer:d
1. #include <stdio.h>
2. int main()
3. {
4. short i;
5. for (i = 1; i >= 0; i++)
6. printf("%d\n", i);
7.
8. }
Answer:c
1. #include <stdio.h>
2. void main()
3. {
4. int k = 0;
5. for (k)
6. printf("Hello");
7. }
a) Compile time error
b) hello
c) Nothing
d) Varies
Answer:a
7. What is the output of this C code?
1. #include <stdio.h>
38
2. void main()
3. {
4. int k = 0;
5. for (k < 3; k++)
6. printf("Hello");
7. }
a) Compile time error
b) Hello is printed thrice
c) Nothing
d) Varies
Answer:a
Teaching Material :
PPT
Assignment 5
Aim: Write A Program In C To Compute The GCD Of The Given Two Integers.
Objective:
Understand Mathematical Concept of GCD and develop a program.
Expected Outcome: Students will be able to
Make use of if… else in program.
Software Required :
Fedora Operating System with Eclipse
Theory :
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:
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:
1. A sequential solution of any program that written in human language, called algorithm.
2. Algorithm is first step of the solution process, after the analysis of problem, programmers write the
algorithm of that problem.
Detailed Algorithm:
Print Num1
Num1=Num2
Num2=Num1+Num2
39
I++
Step 3: End
Flowchart:-
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,small,i;
clrscr();
printf("Insert any two number: ");
scanf("%d%d",&x,&y);
if(x>y)
small=y;
else
small=x;
for(i=small;i>=1;i--)
{
if(x%i==0&&y%i==0)
{
printf("\nGCD(Greatest Common Factor) of two number is : %d",i) ; break;
}
}
getch();
40
}
Output :
Insert any two number: 20 30
GCD(Greatest Common Factor) of two number is : 10
Conclusion: Thus, we have studied how to compute the GCD of the given two integers.
Viva Question
HFC is also called greatest common divisor (gcd). HCF of two numbers is a largest positive numbers which
can divide both numbers without any remainder. For example HCF of two numbers 4 and 8 is 2 since 2 is
the largest positive number which can dived 4 as well as 8 without a remainder.
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
It is clear that any number is not divisible by greater than number itself. In case of more than one numbers, a
possible maximum number which can divide all of the numbers must be minimum of all of that numbers.
Write a c program for finding GCD (greatest common divisor) of two given numbers
#include<stdio.h>
int main(){
scanf("%d%d",&x,&y);
if(x>y)
m=y;
else
m=x;
for(i=m;i>=1;i--){
if(x%i==0&&y%i==0){
printf("\nHCF of two number is : %d",i) ;
break;
}
}
41
return 0;
}
Other logic : HCF (Highest common factor) program with two numbers in c
#include<stdio.h>
int main(){
int n1,n2;
printf("\nEnter two numbers:");
scanf("%d %d",&n1,&n2);
while(n1!=n2){
if(n1>=n2-1)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\nGCD=%d",n1);
return 0;
}
#include<stdio.h>
int main(){
int x,y=-1;
printf("Insert numbers. To exit insert zero: ");
while(1){
scanf("%d",&x);
if(x<1)
break;
else if(y==-1)
y=x;
else if (x<y)
y=gcd(x,y);
else
y=gcd(y,x);
}
int gcd(int x,int y){
int i;
for(i=x;i>=1;i--){
if(x%i==0&&y%i==0){
break;
}
}
42
return i;
}
Teaching Material :
PPT
Assignment 6
Aim: Write a C program to find prime numbers between 1 to n.
Objective:
To learn the basic concept of nested for loop to find prime numbers.
Expected Outcome: Students will be able to
Develop C program to find prime number between 1 to n using for loop.
Software Required :
Fedora Operating System with Eclipse
Theory :
Prime number
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. The fundamental theorem of arithmetic
establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a
product of primes that is unique up to ordering. The uniqueness in this theorem requires excluding 1 as a
prime because one can include arbitrarily many instances of 1 in any factorization, e.g., 3, 1 · 3, 1 · 1 · 3,
etc. are all valid factorizations of 3.
The property of being prime (or not) is called primarily. A simple but slow method of verifying the
primarily of a given number n is known as trial division. It consists of testing whether n is a multiple of any
integer between 2 and . Algorithms much more efficient than trial division have been devised to test the
primarily of large numbers. Particularly fast methods are available for numbers of special forms, such as
Messene numbers. As of April 2014, the largest known prime number has 17,425,170 decimal digits.
There are infinitely many primes, as demonstrated by Euclid around 300 BC. There is no known useful
formula that sets apart all of the prime numbers from composites. However, the distribution of primes, that
is to say, the statistical behavior of primes in the large, can be modeled. The first result in that direction is
the prime number theorem, proven at the end of the 19th century, which says that the probability that a
given, randomly chosen number n is prime is inversely proportional to its number of digits, or to the
logarithm of n.
Many questions regarding prime numbers remain open, such as conjecture (that every even integer greater
than 2 can be expressed as the sum of two primes), and the twin prime conjecture (that there are infinitely
many pairs of primes whose difference is 2). Such questions spurred the development of various branches of
number theory, focusing on analytic or algebraic aspects of numbers. 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.
A natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) is called a prime number (or a prime) if it has exactly two
positive divisors, 1 and the number itself. Natural numbers greater than 1 that are not prime are called
composite.
Among the numbers 1 to 6, the numbers 2, 3, and 5 are the prime numbers, while 1, 4, and 6 are not prime.
43
1 is excluded as a prime number, for reasons explained below. 2 is a prime number, since the only natural
numbers dividing it are 1 and 2. Next, 3 is prime, too: 1 and 3 do divide 3 without remainder, but 3 divided
by 2 gives remainder 1. Thus, 3 is prime. However, 4 is composite, since 2 is another number (in addition to
1 and 4) dividing 4 without remainder:
4 = 2 · 2.
6 = 2 · 3.
Hence, 6 is not prime. The image at the right illustrates that 12 is not prime: 12 = 3 · 4. No even number
greater than 2 is prime because by definition, any such number n has at least three distinct divisors, namely
1, 2, and n. This implies that n is not prime. Accordingly, the term odd prime refers to any prime number
greater than 2. Similarly, when written in the usual decimal system, all prime numbers larger than 5 end in
1, 3, 7, or 9, since even numbers are multiples of 2 and numbers ending in 0 or 5 are multiples of 5.
If n is a natural number, then 1 and n divide n without remainder. Therefore, the condition of being a prime
can also be restated as: a number is prime if it is greater than one and if none of
2, 3, ..., n − 1
divides n (without remainder). Yet another way to say the same is: a number n > 1 is prime if it cannot be
written as a product of two integers a and b, both of which are larger than 1:
n = a · b.
In other words, n is prime if n items cannot be divided up into smaller equal-size groups of more than one
item.
The first 168 prime numbers (all the prime numbers less than 1000) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331,
337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587,
593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709,
719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853,
857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991,
997
Program :
#include<stdio.h>
void main(){
44
count = 0;
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
getch();
}
Output :
Enter max range: 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Teaching Material :
PPT
Assignment 7
Aim: Write A C Program To Sort N Integers Using Bubble Sort.
Objective:
1. To understand concept of sorting.
2. To learn different sorting techniques.
Expected Outcome: Students will be able to
Develop C program using bubble sort for sorting numbers.
Software Required :
Fedora Operating System with Eclipse
Theory :
Bubble Sort
In the bubble sort elements next to each other are compared and exchanged as needed.
By repeating this process of comparing adjacent elements the highest value bubbles its way to the
last position of the array, which gives rise to the name of this type of sorting. The principle behind
a bubble sort is outlined by the following:
Starting at one end of a list, each item is compared to its neighbor. Items out of order are exchanged.
Step 1: We begin by comparing the values in the first and second positions in the list. In this case the first is
larger so a swap is necessary.
Step 2: We now compare the value in the second position, this time the 9 with the third number. The 9 is
larger so a swap is needed.
46
Figure 2 Sorting, Pass 1, Comparison 2
Step 3: We now compare the value in the third position with the fourth. The 9 is larger than the 3 and a swap
is necessary.
Step 4: We compare the value in the fourth position with the fifth. The 9 is larger than the 1 so a swap is
necessary.
At this point ,we have completed one pass through the list of numbers. As illustrated above, the largest
number in the list has bubbled its way to the top of the array after the first pass. This results in one fewer
comparison in the next pass (we don't need to compare the 9 ever again).
Step 5 - 7: We begin our second pass though the list. We start again at the beginning of the array and
compare all neighbors, except for the last - it is already in it correct position.
47
Figure 5 Sorting, Pass 2, Comparison 1
After this pass, the 8 has now bubbled its way up to the second last position.
Steps 8 - 9: We begin the third pass. We start again at the beginning of the array and compare all neighbors,
except for the last 2 elements - the 8 and 9 are in their correct positions.
After this pass, the 5 has now bubbled its way up to the third last position.
Step 10: The fourth pass with a list of 5 items again begins back at the start of the array. The 2 remaining
neighbors are compared and exchanged if needed. The sort is now complete.
48
Figure 10 Sorting, Pass 4, Comparison 1
1. four passes are required before the list is arranged into ascending order
2. the number of comparisons decreases by one after each pass through the list
3. exactly one number is correctly positioned after each pass through the list
Each pass bubbles one item in the list into its correct position. The list is shortened to those remaining
unsorted values. For a list of n items, the sort continues until n-1 passes are complete.
Algorithm
The bubble sort makes n - 1 passes through the array. Each pass starts from the beginning of the array and
goes towards the end. Each step of the pass compares the current element to its right neighbor. If the
compared elements are in the wrong order, they swap their places. This way the larger “bubbles” make their
way to the top.
As usual, we will follow one example step by step: Sort the array: 7, 8, 0, 3, 5
Pass 1: 7, 8, 0, 3, 5
1. Compare 7 and 8. Are they in the wrong order? No. Continue with the next two numbers.
2. Compare 8 and 0. Are they in the wrong order? Yes. Swap them: 7, 0, 8, 3, 5
3. Compare 8 and 3 in the modified array. 8 > 3? -Yes => Swap: 7, 0, 3, 8, 5
4. Compare 8 and 5. 8 > 5? -Yes => Swap: 7, 0, 3, 5, 8
With this we reached the end of the array and the first pass is over. You may notice that the biggest number
in the array 8 moved to the last position.
Pass 2: 7, 0, 3, 5, 8
1. 7 > 0? -Yes. => Swap: 0, 7, 3, 5, 8
2. 7 > 3? -Yes => Swap: 0, 3, 7, 5, 8
3. 7 > 5? -Yes => Swap: 0, 3, 5, 7, 8
4. 7 > 8? -No.
Pass two is over. Notice that the array is already sorted, but the algorithm needs to do two more passes to
complete.
Pass 3: 0, 3, 5, 7, 8
1. 0 > 3? No
2. 3 > 5? No
3. 5 > 7? No
4. 7 > 8? No
Pass 4: 0, 3, 5, 7, 8
49
1. 0 > 3? No
2. 3 > 5? No
3. 5 > 7? No
4. 7 > 8? No
Flowchart:
Program :
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100];
int i, j, temp, n ;
printf("how many numbers you want to sort : \n");
scanf("%d",&n);
printf("\nEnter %d number values you want to sort\n", n);
50
for(j=1;j<n;j++)
{
for(i=0; i<n; i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}
Output :
how many numbers you want to sort :5
Enter 5 number values you want to sort
10 4 55 21 6
Array after sorting:
4 6 10 21 55
Conclusion: Thus we have studied how to sort n integers using bubble sort technique.
Viva Question
1. Two main measures for the efficiency of an algorithm are
a. Processor and memory
b. Complexity and capacity
c. Time and space
d. Data and space
ANS. c. Time and space
ANS: d. Item is the last element in the array or is not there at all
a. O(n)
b. O(log n)
Teaching Material :
PPT
Assignment 8
Aim: :- Write a program in C to carry out following operations on strings using library functions
Software Required :
Fedora Operating System with Eclipse
Theory :
1. Strcat function
(String Concatenation)
In the C Programming Language, the strcat function appends a copy of the string pointed to by s2 to the end
of the string pointed to by s1. It returns a pointer to s1 where the resulting concatenated string resides.
Syntax
The syntax for the strcat function in the C Language is:
char *strcat(char *s1, const char *s2);
Parameters or Arguments
s1
A pointer to a string that will be modified. s2 will be copied to the end of s1.
s2
A pointer to a string that will be appended to the end of s1.
Returns
The strcat function returns a pointer to s1 (where the resulting concatenated string resides).
Required Header
In the C Language, the required header for the strcat function is:
#include <string.h>
Note: Use the strcat function with caution as it is easy to concatenate more bytes into your variable using the
strcat function, which can cause unpredictable behavior.
strcat Example
Let's look at an example to see how you would use the strcat function in C program:
/* Example using strcat by TechOnTheNet.com */
#include <stdio.h>
#include <string.h>
/* Concatenate the following two strings to the end of the first one */
strcat(example, "is over 10 ");
strcat(example, "years old.");
return 0;
}
In this strcat example, the C program would concatenate "TechOnTheNet.com is over 10 years old."
2. strlen function
(String Length)
In the C Programming Language, the strlen function returns the length of the string pointed to by s. It does
not include the null character in the length calculation.
Syntax
The syntax for the strlen function in the C Language is:
size_t strlen(const char *s);
Parameters or Arguments
s
The string whose length you want to calculate.
Returns
The strlen function returns the length of the string pointed to by s. It does not include the null character in
the length calculation.
Required Header
In the C Language, the required header for the strlen function is:
#include <string.h>
3. strcmp function
(String Compare)
In the C Programming Language, the strcmp function returns a negative, zero, or positive integer depending
on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2.
Syntax
The syntax for the strcmp function in the C Language is:
int strcmp(const char *s1, const char *s2);
Parameters or Arguments
s1
An array to compare.
s2
An array to compare.
Returns
The strcmp function returns an integer. The return values are as follows:
Return Value Explanation
0 s1 and s2 are equal
Negative integer The stopping character in s1 was less than the stopping character in s2
Positive integer The stopping character in s1 was greater than the stopping character in s2
Required Header
54
In the C Language, the required header for the strcmp function is:
#include <string.h>
strcmp Example
Let's look at an example to see how you would use the strcmp function in C program:
#include <stdio.h>
#include <string.h>
return 0;
}
4. strcpy function
(String Copy)
In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object
pointed to by s1. It returns a pointer to the destination.
Syntax
The syntax for the strcpy function in the C Language is:
char *strcpy(char *s1, const char *s2);
Parameters or Arguments
s1
An array where s2 will be copied to.
s2
The string to be copied.
Returns
The strcpy function returns s1.
Required Header
55
In the C Language, the required header for the strcpy function is:
#include <string.h>
strcpy Example
Let's look at an example to see how you would use the strcpy function in C program:
#include <stdio.h>
#include <string.h>
/* Copy the string "TechOnTheNet.com knows strcpy!" into the example variable */
strcpy (example, "TechOnTheNet.com knows strcpy!");
return 0;
}
Program :
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{
char str1[20],str2[20]; int
ch,length1,length2; clrscr();
printf("\nEnter 1st string: ");
scanf("%s",str1); printf("\nEnter
2nd string: "); scanf("%s",str2);
do
{
printf("\n**********MENU********\n");
printf("\n1.Concatenate Strings\n"); printf("\
n2.Length of String\n"); printf("\n3.Compare two
Strings\n"); printf("\n4.Copy String\n"); printf(“\
n5.Exit”);
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
strcat(str1,str2);
printf("\nConcatenated String is : %s",str1); break;
case 2:
56
length1 = strlen(str1);
printf("\nLength of %s is %d",str1,length1);
length2 = strlen(str2);
printf("\nLength of %s is %d",str2,length2);
break;
case 3:
if(strcmp(str1,str2)==0) printf("\nStrings
are equal.");
else
printf("\nStrings are not equal.");
break;
case 4:
strcpy(str1,str2); printf("\nCopied
String is : %s",str1);
break; case
5: exit();
break;
}
getch();
}while(ch<5');
Output :
Enter 1st string: abc
**********MENU********
1.Concatenate Strings
5. Exit
1.Concatenate Strings
5. Exit
57
Enter your choice: 2
Length of abcefg is 6
Length of efg is 3
**********MENU********
1.Concatenate Strings
5. Exit
**********MENU********
1.Concatenate Strings
5. Exit
Conclusion: Thus we have studied how to concatenate, finding length of a given string, compare two
strings and copy a string to other string operations on strings using library functions.
Viva Question
1.
Input/output function prototypes and macros are defined in which header file?
stdio.h, which stands for "standard input/output header", is the header in the C standard library that
contains macro definitions, constants, and declarations of functions and types used for various standard
input and output operations.
2.
Which standard library function will you use to find the last occurrences of a character in a string in C?
strrchr() returns a pointer to the last occurrence of character in a string.
Example:
#include <stdio.h>
#include <string.h>
int main()
58
{
char str[30] = "12345678910111213";
printf("The last position of '2' is %d.\n",
strrchr(str, '2') - str);
return 0;
}
3.
What is stderr ?
The standard error(stderr) stream is the default destination for error messages and other diagnostic
warnings. Like stdout, it is usually also directed to the output device of the standard console (generally,
the screen).
4. Does there any function exist to convert the int or float to a string?
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int num1 = 12345;
float num2 = 5.12;
char str1[20];
char str2[20];
return 0;
}
// Output:
// integer = 12345 string = 12345
// float = 5.120000 string = 5.120000
Teaching Material :
PPT
59
GROUP C
Assignment 1
Aim: :- Write a program in Eclipse-Python to generate prime numbers between 1 and n.
Objective:
To learn how to create a program in Pyhton
Expected Outcome: Students will be able to
Design and Develope a Prime Number Program in
Python in Eclipse Editor.
Software Required :
For the installation of eclipse JRE must be installed
JDK Latest update for Java
Cygwin/MinGW is required for Windows
CDT for C project Development
Hardware Requirements(Minimum):
P-IV machine
2 GB RAM
10 GB Hard disk
Theory:
Installing with the update site
Note: Instructions are targeted at Eclipse 3.5 onwards
To install PyDev and PyDev Extensions using the Eclipse Update Manager, you need to use the Help
> Install New Software... menu (note that in older versions, this would be the 'Find and Install' menu).
60
In the next screen, add the update site(s) you want to work with ( See below for a list with the
available update sites).
After entering the update sites, select the update site you entered or select "All available sites" and add
a filter for PyDev, so that it shows the contents of all the update sites that have PyDev, then select what
you want to install and click 'Next'.
61
Then, UNCHECK the 'Contact all update sites during install to find required software' and press
'Next' again to confirm your selection.
And finally, read the license agreement and if you accept, select the accept radio button and click
'Finish'.
62
The steps for Python program in Eclipse
Select File -> New -> Project. Select Pydev -> Pydev Project.
63
Create a new project with the name "de.vogella.python.first". Select Python version 2.6 and your
interpreter.
Press finish.
64
Select Window->Open Perspective ->Other. Select the PyDev perspective.
Select the "src" folder of your project, right-click it and select New -> PyDev Modul. Create a module
"FirstModule".
65
Program:
def isprime(n):
if n == 1:
print("1 is special")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print(n, "is a prime number")
return True
for x in range(2,10) :
print x
The block starting with def isprime(n) is a function, with argument n. You can call it for any
n: isprime(100). At the bottom of the code, you are iterating over range(1,20) (if in doubt type it into the
prompt) and calling isprime for each value, i.e. 1,2,3,4,...,19.
66
Note that in this example, there isn't a need to create and return a list with range, you can use xrange, which
is a generator.
Output :
1
2
3
5
7
11
13
17
19
Conclusion: Thus we have studied how to generate prime numbers between 1 and n using Eclipse-Python.
Viva Question
Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter:
If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result:
Hello, Python!
Invoking the interpreter with a script parameter begins execution of the script and continues until the script
is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source
67
code in a test.py file:
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows
−
$ python test.py
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −
#!/usr/bin/python
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows −
Hello, Python!
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example −
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Teaching Material :
PPT
69