You are on page 1of 71

JSPM’s

JSPM’s and TSSM’s Groups of Institutes, Pune

Academic Year: 2015-16 (SEM -I)

LAB MANUAL
[V- 1]

Subject: Fundamentals of Programming Languages –I

Teaching Scheme Examination Scheme


Theory: 1 Hr. /Week Online Examination: 50 Marks
Practical: 2 Hrs. /Week
INDEX
Sr. Page
Topic
No. No.
1. Vision, Mission, Quality Policy 1
2. How to Use This Manual 2
3. Session Plan 4
Group A
Sessions
1 Use and study of LINUX GUI and commands 7
2 Handling and use of eclipse editor for creating projects in C, python(pydev),java 12
3 Using eclipse to write/test “Hello! World“program in C, Python. 17
Group B
Sessions
Write a C program to accept five numbers from console and then to display them back on
1 24
console in ascending order.
Write a C program to calculate the sum of all numbers from 0 to 100(both inclusive) that
2 28
all divisible by 4.
Program in C to accept the length of three sides of a triangle from console and print the
3
type of triangle - equilateral, isosceles, right angled or none of these.
4 Write a program in C to generate first 20 fibonacci numbers.
5 Write a program in C to compute the gcd of the given two integers.
6 Write a C program to find prime numbers between 1 to n.
7 Write a C program to sort n integers using bubble sort.
Write a program in C to carry out following operations on strings using library functions
a. To concatenate a string s2 to string s1.

b. To find the length of a given string


8
c. To compare two strings s1 and s2.

d. To copy a string s2 to another string s1.

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.

The Facilitator is expected to refer this Manual before the session.


K A D I

Applying Problem Design & Investigation


Knowledge Analysis Development of problems
M E E T
Environment
Modern Engineer & Sustainabilit Ethics
Tool Society y
Usage
T O M I

Individual Communication Project Life Long


& Team Management Learning
work & Finance

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.

Objective: To use and study of Linux GUI and commands.


Expected Outcome: Students will be able to
Illustrate basics of LINUX GUI operations and terminal 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

-1, --format Print one entry per line of output


single-column
-a, --all List all files, including the normally hidden files whose names begin with a period.

-b, --escape Display nonprinting characters in octal and alphabetic format.


-c, --time-ctime, List files by status change time (not creation/modification time).
--time=status
--color =when Colorize the names of files depending on the type of file. Accepted values for when are
never, always, or auto.

-d, --directory Report only on the directory, not its contents.


-f Print directory contents in exactly the order in which they are stored, without
attempting to sort them.

--help Print a help message and then exit.


2. dir
Syntax
dir [options] [file]
dir is equivalent to the command ls -C -b (list files in columns, sorted vertically, special
characters escaped), and it takes the same arguments as ls. This is an alternate invocation of the
ls command and is provided for the convenience of those converting from Microsoft Windows
and the DOS shell.
Options Description
-b Make a backup of each file that would otherwise be overwritten or removed.
--backup
-f --force Remove existing destination files and never prompt the user.
-I Prompt whether to overwrite each existing destination file,
Regard less of its permissions. If the response does not begin with `y' or `Y', the
--interactive file is skipped.

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.

--count Overrides all other options.

-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

--help Display Help


--version Display program version info.

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

-h Act on symbolic links themselves instead of what they point to.


--no-dereference
This is the default.

7. chmod
Syntax

chmod[Options] Mode [,Mode]... file...


chmod [Options]... Numeric_Mode file...
chmod [Options]... --reference=RFile file...

Change access permissions, change mode.

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

11. sudo, sudoedit - execute a command as another user


Syntax
sudo -K | -L | -V | -h | -k | -l | -v
sudo allows a permitted user to execute a command as the super user or another user, as specified in
the sudoers file.

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

Eclipse IDE Introduction:


Eclipse is a multi-language Integrated development environment (IDE) comprising a
base workspace and an extensible plug-in system for customizing the environment. It is written mostly in
Java. It can be used to develop applications in Java and, by means of various plug-ins, other programming
languages including Ada, C, C++, COBOL, Fortran, Haskell, JavaScript, Perl, PHP, 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.
Configuring Eclipse IDE for C Projects:
 To use eclipse IDE for ‘C’ projects, CDT must be installed.
CDT:
The CDT Project provides a fully functional C and C++ Integrated Development Environment based
on the Eclipse platform. Features include: support for project creation and managed build for various tool
chains, standard make build, source navigation, various source knowledge tools, such as type hierarchy, call
graph, include browser, macro definition browser, code editor with syntax highlighting, folding and
hyperlink navigation, source code refactoring and code generation, visual debugging tools, including
memory, registers, and disassembly viewers.

Creating a ‘C’ project in eclipse IDE


 When we use eclipse for the first time, we need to create workspace to store projects.
By default it creates workspace in user directory.

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.

Step 2: To Create C project in eclipse, we have to open a ‘c’ perspective.


To open perspective, do this Windows-> Open Perspective->Other.. then select c/c++
(Default) and click on ok.

Step 3: We get c/c++ perspective for implementing c program.

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

Step 2: We get Python perspective for implementing Python program

Creating a Java project in Eclipse IDE


Following steps should be followed to create a Java project in eclipse IDE
Step 1: Windows->Open Perspective->Other..
The following Window will be opened. In this windows, select Java 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

ii. When we click on project, we get following window.

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.

v. The project is created. Now do the following to create source file


File->New->source file
We get following window. Give suitable file name with .c extension and 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

c. After compilation to execute the program do the following.


Run->Run

18
d. After the execution of C program, we get the following output.

Creating a Python Program 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 following to a hello 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

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

Next > button and then click on Finish button.

Step 3: Right click src->new->PyDev Module.


We get following window.

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.

Step 7: To Execute python program, do this Run->Run

Step 8: We get the following window. Click on Python Run->ok

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

I. How to write simple program in Python?


Script Mode Programming
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 code in a test.py file:

print "Hello, Python!";

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows

$ python test.py

This produces the following result:

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:

Array subscripts vs. pointer arithmetic


Element
1 2 3 n
index
Array
array[0] array[1] array[2] array[n-1]
subscript
Dereferenced
*array *(array + 1) *(array + 2) *(array + n-1)
pointer

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

Eg. 64 25 12 22 11 (Intial array elements)

11 25 12 22 64 (In 1st pass)


 Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)

11 12 25 22 64 (In 2nd pass)

11 12 22 25 64 (In 3rd pass)

11 12 22 25 64 (In 4th pass)


 Print the result.
 End program
Program:
#include <stdio.h>
#include<conio.h>
void main()
{

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");

/* Read the user input, store those numbers in 'numbers' array */


for(i = 0; i < 5; i++)
{
scanf("%d", &numbers[i]);
}

/* Sort those numbers in ascending order using bubble sort */


for(i = 0; i < 5; i++)
{
for(j = i + 1; j < 5; j++)
{
/* compare number at i with number at j (j's are on the right of i)*/
if(numbers[i] > numbers[j])
{
/* Swap the two numbers */
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
/* Display a message that we will now print those numbers in ascending order*/
printf("The numbers in ascending order are\n");
/* Print the input from 'numbers' array */
for(i = 0; i < 5; i++)
{
25
printf("%d\t", numbers[i]);
}
getch();
}
Output:
4 6 1 85 9
The numbers in ascending order are
1 4 6 9 85
Conclusion:
Thus, we have studied one dimensional array and printed the numbers in ascending order on console.
Viva Questions

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.

II. What is array in C language?


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.

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).

Expected Outcome: Students will be able to


 Make use of for loop in program.

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

Variables, Types and Declarations


char : A single ASCII character
short : A short integer (usually 16-bits)
short int : A short integer
int : A standard integer (usually 32-bits)
long : A long integer
long int : A long integer (usually 32-bits, but increasingly 64 bits)
float : A floating point or real number (short)
long float : a long floating point number
double : A long floating point number
To declare a variable in a C program one writes the type followed by a list of variable names which are to be
treated as being that type:

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;

Three parts of for loop as follows


 Initial Value: Variable can be defined and initialized.
 Test: As long as this condition is true the statement in loop gets executed. When condition becomes
false that time program control goes out of loop.

 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

I. What is the control structure in C language?


Programs written in procedural languages are three basic control structures in virtually
every procedural language are:
1. Sequence
2.Conditional
3. Iterative

II. How many looping structure are there in C language?


A loop statement allows us to execute a statement or group of statements multiple times and following
is the general form of a loop statement in most of the programming languages:

C programming language provides the following types of loop to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a


given condition is true. It tests the condition before
executing the loop body.

for loop Execute a sequence of statements multiple times


and abbreviates the code that manages the loop
variable.

do...while loop Like a while statement, except that it tests the


condition at the end of the loop body

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

Properties of Isosceles Triangle:-


Any two sides are equal

Properties of Right angle triangle:-


Square (C) = Square (A) + Square (B)

IF- ELSE Loop:


If statement can be followed by an optional else statement, which executes when the Boolean expression is
false.
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then if block of code will be executed, otherwise else block of
code will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either
zero or null, then it is assumed as false value.

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

“If”, “else” and “nested if” decision control statements in C:


 Syntax for each C decision control statements are given in below table with description.

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;

Example program for if statement in C:

      In “if” control statement, respective block of code is executed when condition is true.

int main()
{
int m=40,n=40;
if (m == n)
34
{
printf("m and n are equal");
}
}
Output:
m and n are equal

Example program for if else statement in C:

      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

Example program for nested if statement in C: 


 In “nested if” control statement, if condition 1 is false, then condition 2 is checked and statements
are executed if it is true. 
 If condition 2 also gets failure, then else part is executed.

#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.

We get a doubling sequence. Notice the recursive formula:

 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

 maturation time = 1 month


 gestation time = 1 month

If you were to try this in your backyard, here's what would happen:

Now let the computer draw a few more lines:

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

 fn = number of pairs during month n


 fn = fn-1 + fn-2

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 :

First 20 Fibonacci Numbers are:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Conclusion: Thus, we have studied how to generate Fibonacci series.

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

5. What is the output of this C code?

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. }

a) The control won’t fall into the for loop


b) Numbers will be displayed until the signed limit of short and throw a runtime error
c) Numbers will be displayed until the signed limit of short and program will successfully terminate
.d) This program will get into an infinite loop and keep printing numbers with no errors

Answer:c

6. What is the output of this C code?

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:

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 ...

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:

Step 1:  I=0, Num1=0, Num2=1

Step 2:  While (I < 11)

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

Definition of HCF (Highest common factor):

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. 

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:

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.

For example: 10, 20, and 30


Min (10, 20, 30) =10 can divide all there numbers. So we will take one for loop which will start form min of
the numbers and will stop the loop when it became one, since all numbers are divisible by one. Inside for
loop we will write one if conditions which will check divisibility of both the numbers.
Program:

Write a c program for finding GCD (greatest common divisor) of two given numbers

#include<stdio.h>

int main(){

    int x,y,m,i;

    printf("Insert any two number: ");

    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;
}

HCF  program with multiple numbers in c 

#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);
    }

    printf("GCD is %d",y);


   
    return 0;
}

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.

Definition and examples

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.

5 is again prime: none of the numbers 2, 3, or 4 divide 5. Next, 6 is divisible by 2 or 3, since

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 set of all primes is often denoted by P.

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(){

    int num,i,count,n;


    printf("Enter max range: ");
    scanf("%d",&n);

    for(num = 1;num<=n;num++){

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

Conclusion : Thus, we have studied how to find prime numbers between 1 to n.


Viva Questions
1. When a natural number n is divided by 4, the remainder is 3. What is the remainder when 2n is
divided by 4?
a. 1                   b. 2                  c. 3                   d. 6
 2. What is the last digit in the expansion of (2457)754?
a. 3                   b. 7                  c. 8                   d. 9
 3. The product of two alternate odd integers exceeds three times the smaller by 12. What is the larger
number?
a. 3                   b. 5                  c. 7                   d. 9
 4. Nine numbers are written in ascending order. The middle number is the average of the nine
numbers. The average of the first five larger numbers is 68 and that of five smaller numbers is 44.
What is the sum of all nine numbers?
a. 450               b. 501               c. 504               d. 540
 5. If a:b = 3/2:9/2 and b:c = 2:7/2 then what is a:b:c?
a. 12:8:21          b. 8:21:12         c. 8:12:21          d. 21:8:12
 6. A bag contains Rs. 114 in the form of 1 rupee, 50 paise and 10 paisa coins in the ratio 3:4:10. What
is the number of 50 paisa coins?
a. 76                 b. 72                 c. 56                 d. 48
 7. What is the total number of three digit numbers with unit digit 7 and divisible by 11?
a. 6                   b. 7                  c. 8                   d. 9
 8. What is the sum of positive integers less than 100 which leave a remainder 1 when divided by 3 and
leave a remainder 2 when divided by 4?
a. 416               b. 620               c. 1250             d. 1314
 9. What is the greatest number which divides 392, 486 and 627 so as to leave the same remainder in
each case?
a. 47                 b. 43                 c. 37                 d. 34
 10. Consider those numbers between 300 and 400 such that when each number is divided by 6, 9 and
12, it leaves 4 as remainder in each case. What is the sum of the numbers?
a. 692               b. 764               c. 1080             d. 1092
 11. A three digit number is divisible by 11 and has its digit in the unit’s place equal to 1. The number
is 297 more than the number obtained by reversing the digits. What is the number?
a. 121               b. 231               c. 561               d. 451
 12. If the highest common factor of two positive integers is 24 then their least common multiple
cannot be
a. 72                 b. 216               c. 372               d. 600
 13. Which of the following numbers is not a square of any natural numbers?
a. 5041             b. 9852             c. 1936             d. 6241
45
 14. The least number which when divided by 5, 6, 7 and 8 leaves a remainder is
a. 423               b. 843               c. 1683             d. 2523
15. When a certain number is divided by 5, the remainder is 1. When the same number is divided by
3, the remainder is 2. What is that number?
a. 8                   b. 11                 c. 16                 d. 21

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.

Consider this list: 9, 5, 8, 3, 1. We will sort the list in ascending order.

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.

Figure 1 Sorting, Pass 1, Comparison 1

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.

Figure 3 Sorting, Pass 1, Comparison 3

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.

Figure 4 Sorting, Pass 1, Comparison 4

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

Figure 6 Sorting, Pass 2, Comparison 2

Figure 7 Sorting, Pass 2, Comparison 3

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.

Figure 8 Sorting, Pass 3, Comparison 1

Figure 9 Sorting, Pass 3, Comparison 2

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

Note that for a list of 5 numbers:

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);

for(j=0; j<n; j++)


{
scanf("%d",&a[j]);
}

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

2. The time factor when determining the efficiency of algorithm is measured by


a. Counting microseconds
b. Counting the number of key operations
c. Counting the number of statements
d. Counting the kilobytes of algorithm

ANS: b. Counting the number of key operations


 

3. The space factor when determining the efficiency of algorithm is measured by


a. Counting the maximum memory needed by the algorithm
b. Counting the minimum memory needed by the algorithm
c. Counting the average memory needed by the algorithm
d. Counting the maximum disk space needed by the algorithm

ANS: a. Counting the maximum memory needed by the algorithm


 

4. Which of the following case does not exist in complexity theory


a. Best case
51
b. Worst case
c. Average case
d. Null case

ANS: d. Null case 

5. The Worst case occur in linear search algorithm when


a. Item is somewhere in the middle of the array
b. Item is not in the array at all
c. Item is the last element in the array
d. Item is the last element in the array or is not there at all

 ANS: d. Item is the last element in the array or is not there at all

6. The Average case occur in linear search algorithm


a. When Item is somewhere in the middle of the array
b. When Item is not in the array at all
c. When Item is the last element in the array
d. When Item is the last element in the array or is not there at all

 a. When Item is somewhere in the middle of the array

7. The complexity of the average case of an algorithm is


a. Much more complicated to analyze than that of worst case
b. Much more simpler to analyze than that of worst case
c. Sometimes more complicated and some other times simpler than that of worst case
d. None or above

a. Much more complicated to analyze than that of worst case


 

8. The complexity of linear search algorithm is


a. O(n)
b. O(log n)
c. O(n2)
d. O(n log n)

a. O(n)
 

9. The complexity of Binary search algorithm is


a. O(n)
b. O(log )
c. O(n2)
d. O(n log n)

b. O(log n)
 

10. The complexity of Bubble sort algorithm is


a. O(n)
b. O(log n)
c. O(n2)
d. O(n log n)
52
c. O(n2)

Teaching Material :
PPT

Assignment 8
Aim: :- Write a program in C to carry out following operations on strings using library functions

a. To concatenate a string s2 to string s1.

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.


Objective:
To understand the C library functions for string.
Expected Outcome: Students will be able to
Apply library functions in c to perform different string operations.

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>

int main(int argc, const char * argv[])


{
53
/* Define a temporary variable */
char example[100];

/* Copy the first string into the variable */


strcpy(example, "TechOnTheNet.com ");

/* Concatenate the following two strings to the end of the first one */
strcat(example, "is over 10 ");
strcat(example, "years old.");

/* Display the concatenated strings */


printf("%s\n", example);

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:

/* Example using strcmp by TechOnTheNet.com */

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])


{
/* Create a place to store our results */
int result;

/* Create two arrays to hold our data */


char example1[50];
char example2[50];

/* Copy two strings into our data arrays */


strcpy(example1, "C programming at TechOnTheNet.com");
strcpy(example2, "C programming is fun");

/* Compare the two strings provided */


result = strcmp(example1, example2);

/* If the two strings are the same say so */


if (result == 0) printf("Strings are the same\n");

/* If the first string is less than the second say so


(This is because the 'a' in the word 'at' is less than
the 'i' in the word 'is' */
if (result < 0) printf("Second string is less than the first\n");

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:

/* Example using strcpy by TechOnTheNet.com */

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])


{
/* Create an example variable capable of holding 50 characters */
char example[50];

/* Copy the string "TechOnTheNet.com knows strcpy!" into the example variable */
strcpy (example, "TechOnTheNet.com knows strcpy!");

/* Display the contents of the example variable to the screen */


printf("%s\n", example);

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

Enter 2nd string: efg

**********MENU********

1.Concatenate Strings

2.Length of String 3.Compare

two Strings 4.Copy String

5. Exit

Enter your choice: 1

Concatenated String is : abcefg


**********MENU********

1.Concatenate Strings

2.Length of String 3.Compare

two Strings 4.Copy String

5. Exit
57
Enter your choice: 2

Length of abcefg is 6
Length of efg is 3

**********MENU********

1.Concatenate Strings

2.Length of String 3.Compare

two Strings 4.Copy String

5. Exit

Enter your choice: 3

Strings are not equal.

**********MENU********

1.Concatenate Strings

2.Length of String 3.Compare

two Strings 4.Copy String

5. Exit

Enter your choice: 4

Copied String is : efg */

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;
}

Output: The last position of '2' is 14.

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?

1. itoa() converts an integer to a string.


2. ltoa() converts a long to a string.
3. ultoa() converts an unsigned long to a string.
4. sprintf() sends formatted output to a string, so it can be used to convert any type of values to string
type.

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
int num1 = 12345;
float num2 = 5.12;
char str1[20];
char str2[20];

itoa(num1, str1, 10); /* 10 radix value */


printf("integer = %d string = %s \n", num1, str1);

sprintf(str2, "%f", num2);


printf("float = %f string = %s", num2, str2);

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 n in range(1, 20):


isprime(n)

for x in range (2,n):


this n comes from the first def isprime(n) and is whatever this function is later called with. In this case it is
always the same n from the bottom.

print("{} equals {} x {}".format(n, x, n // x))


this writes the following text: A equals B x C where A is n, B is x and C is n/x rounded to the nearest
smaller integer. It is so called integer division (e.g. 9 // 2 = 4)

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

I. Explain in Brief How to Execute Simple Python Program.

First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming

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:

>>> print "Hello, Python!";

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!

II. Explain Script Mode Programming in Python?

Script Mode Programming

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:

print "Hello, Python!";

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows

$ python test.py

This produces the following result:

Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py file −

#!/usr/bin/python

print "Hello, Python!";

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows −

$ chmod +x test.py # This is to make file executable


$./test.py

This produces the following result −

Hello, Python!

III. Explain Python Identifiers, Reserve Words & Indentation?

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.

Here are naming conventions for Python identifiers −

 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.

And exec Not


68
Assert finally or
Break for pass
Class from print
Continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Lines and Indentation

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"

However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Teaching Material :
PPT

69

You might also like