Sie sind auf Seite 1von 125

A

LABORATORY MANUAL
For

COMPUTER PROGRAMMING LABORATORY

For First Year First Semester CSE Students

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY


CHINNAMACHUPALLI (V), CHENNUR ROAD, KADAPA

-: CREATING GLOBAL LEADERS


GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

2015-2016

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR


ANANTHAPURAMU
I B.Tech. I – Semester P C
4 2
(15A05102) COMPUTER PROGRAMMING LAB
(Common to All branches)
Objectives:
Learn C Programming language
To make the student solve problems, implement algorithms using C language.
List of Experiments/Tasks
1. Practice DOS and LINUX Commands necessary for design of C Programs.
2. Study of the Editors, Integrated development environments, and Compilers in chosen
platform.
3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the programming
environment.
4. Practice programs: Finding the sum of three numbers, exchange of two numbers, maximum of
two numbers, To read and print variable values of all data types of C language, to find the
size of all data types, to understand the priority and associativity of operators using
expressions, to use different library functions of C language.
5. Write a program to find the roots of a Quadratic equation.
6. Write a program to compute the factorial of a given number.
7. Write a program to check whether the number is prime or not.
8. Write a program to find the series of prime numbers in the given range.
9. Write a program to generate Fibonacci numbers in the given range.
10. Write a program to find the maximum of a set of numbers.
11. Write a program to reverse the digits of a number.
12. Write a program to find the sum of the digits of a number.
13. Write a program to find the sum of positive and negative numbers in a given set of numbers.
14. Write a program to check for number palindrome.
15. Write a program to evaluate the sum of the following series up to „n‟ terms e
x=1+x+x2/2!+x3/3!+x4/4!+--------

16. Write a program to generate Pascal Triangle.


17. Write a program to read two matrices and print their sum and product in the matrix form.
18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
19. Write a program to accept a line of characters and print the number of Vowels, Consonants,
blank spaces, digits and special characters.
20. Write a program to insert a substring in to a given string and delete few characters from the
string. Don‟t use library functions related to strings.
21. Write a program to perform the operations addition, subtraction, multiplication of complex
numbers.
22. Write a program to split a „file‟ in to two files, say file1 and file2. Read lines into the „file‟
from standard input. File1 should consist of odd numbered lines and file2 should consist of
even numbered lines.
23. Write a program to merge two files.

I.KAVITHA JACKLEEN M.Tech


2
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
24. Write a program to implement numerical methods Lagrange‟s interpolation, Trapezoidal rule.
25. Write a program to read a set of strings and sort them in alphabetical order.
26. Write a program to read two strings and perform the following operations without using builtin
string Library functions and by using your own implementations of functions.
i. String length determination ii .Compare Two Strings
iii. Concatenate them, if they are not equal iv. String reversing
27. Write programs using recursion for finding Factorial of a number, GCD, LCM, and solving
Towers of Hanoi problem.
28. Write a program to exchange two numbers using pointers.
29. Write a program to read student records into a file. Record consists of rollno, name and marks
of a student in six subjects and class. Class field is empty initially. Compute the class of a
student. The calculation of the class is as per JNTUA rules. Write the first class, second class,
third class and failed students lists separately to another file.
30. A file consists of information about employee salary with fields employeeid, name, Basic,
HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employeeid, name, and
basic have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is
20% of the basic, other deductions is user specified. Compute the Gross and Net salary of the
employee and update the file.
31. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.
32. Write a program to find the square root of a number without using built-in library function.
33. Write a program to convert from string to number.
34. Write a program to implement pseudo random generator.
35. Write a program to generate multiplication tables from 11 to 20.
36. Write a program to express a four digit number in words. For example 1546 should be written
as one thousand five hundred and forty six.
37. Write a program to generate a telephone bill. The contents of it and the rate calculation etc
should be as per BSNL rules. Student is expected to gather the required information through
the BSNL website.
38. Write a program to find the execution time of a program.
39. Design a file format to store a person's name, address, and other information. Write a program
to read this file and produce a set of mailing labels
Note:
1. Instructors are advised to conduct the lab in LINUX/UNIX environment also
2. The above list consists of only sample programs. Instructors may choose other programs to
illustrate certain concepts, wherever is necessary. Programs should be there on all the
concepts studied in Theory. Instructors are advised to change atleast 25% of the programs
every year until the next syllabus revision.

References:
1. “How to Solve it by Computer”, R.G. Dromey, Pearson.
2. “The C Programming Language”, Brian W. Kernighan, Dennis M. Ritchie, Pearson.
3. “Let us C”, Yeswant Kanetkar, BPB publications
4. “Pointers in C”, Yeswant Kanetkar, BPB publications.
5. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A.Ananda Rao,
Pearson Education.

Outcomes:
Apply problem solving techniques to find solutions to problems
Able to use C language features effectively and implement solutions using C language.

I.KAVITHA JACKLEEN M.Tech


3
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
Improve logical skills.

CONTENTS

S.NO. TITLE OF EXPERIMENT PAGE.NO


Practice DOS and LINUX Commands necessary for design of C
1
Programs.
Study of the Editors, Integrated development environments, and
2
Compilers in chosen platform.
Write, Edit, Debug, Compile and Execute Sample C programs to
3
understand the programming environment.
Practice programs: Finding the sum of three numbers, exchange of two
numbers,maximum of two numbers, to read and print variable values of
4 all data types of C language, to find the size of all data types, to
understand the priority and associativity of operators using expressions,
to use different library functions of C language.
5 Write a program to find the roots of a quadratic equation.
6 Write a program to compute the factorial of a given number.
7 Write a program to check whether the number is prime or not.
8 Write a program to find the series of prime numbers in the given range
9 Write a program to generate Fibonacci numbers in the given range.
10 Write a program to find the maximum of a set of numbers.
11 Write a program to reverse the digits of a number.
12 Write a program to find the sum of the digits of a number.
Write a program to find the sum of positive and negative numbers in a
13 given set of numbers.
14 Write a program to check for number palindrome.
Write a program to evaluate the sum of the following series up to ‘n’
15
terms e =1+x+x /2!+x /3!+x /4!+--------
x 2 3 4

16 Write a program to generate Pascal Triangle


Write a program to read two matrices and print their sum and product in
17
the matrix form.
Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
18
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix.
Write a program to accept a line of characters and print the number of Vowels,
19
Consonants, blank spaces, digits and special characters.

20 Write a program to insert a substring in to a given string and delete few


characters from the string. Don‟t use library functions related to strings.
Write a program to perform the operations addition, subtraction, multiplication
21
of complex numbers.
22 Write a program to split a „file‟ in to two files, say file1 and file2. Read lines
into the „file‟ from standard input. File1 should consist of odd numbered lines

I.KAVITHA JACKLEEN M.Tech


4
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

and file2 should consist of even numbered lines.

23 Write a program to merge two files.


Write a program to implement numerical methods Lagrange‟s interpolation,
24
Trapezoidal rule.

25 Write a program to read a set of strings and sort them in alphabetical order.
Write a program to read two strings and perform the following operations
without using builtin string Library functions and by using your own
26
implementations of functions. i. String length determination ii .Compare Two
Strings iii. Concatenate them, if they are not equal iv. String reversing.
Write programs using recursion for finding Factorial of a number, GCD, LCM,
27
and solving Towers of Hanoi problem.

28 Write a program to exchange two numbers using pointers.


Write a program to read student records into a file. Record consists of rollno,
name and marks of a student in six subjects and class. Class field is empty
initially. Compute the class of a student. The calculation of the class is as per
29
JNTUA rules. Write the first class, second class, third class and failed students
lists separately to another file.

A file consists of information about employee salary with fields employeeid,


name, Basic, HRA, DA, IT, other-deductions, Gross and Net salary. Initially
only employeeid, name, and basic have valid values. HRA is taken as 10% of
30
the basic, DA is taken as 80% of basic, IT is 20% of the basic, other deductions
is user specified. Compute the Gross and Net salary of the employee and update
the file.
31 Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.

Write a program to find the square root of a number without using built-in
32
library function.

33 Write a program to convert from string to number.


34 Write a program to implement pseudo random generator.

35 Write a program to generate multiplication tables from 11 to 20.

Write a program to express a four digit number in words. For example 1546
36
should be written as one thousand five hundred and forty six.
Write a program to generate a telephone bill. The contents of it and the rate
37 calculation etc should be as per BSNL rules. Student is expected to gather the
required information through the BSNL website.
38
Write a program to find the execution time of a program.

Design a file format to store a person's name, address, and other information.
39
Write a program to read this file and produce a set of mailing labels.

I.KAVITHA JACKLEEN M.Tech


5
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

1.DOS and LINUX Commands

AIM:- To Practice a DOS and LINUX Commands necessary for design of C Programs

DOS commands:
Summary:

cd <directory name> -- cd is the basic DOS command, it allows you to change directory

dir [name of directory] -- dir allows you to list all contents of the specified directory

copy <source> <destination> --

Allows you to copy a file from a <source> folder to a <destination folder>

del<file> -- Deletes a specific file

move <source> <destination> --

Allows you to move a file from a <source> folder to a <destination folder>

ren <source> <destination> -- Renames the specified file

edit <filename> -- Opens the default DOS editor to allow modification of a specified file

cls -- Clears the DOS screen

exit -- Leaves the DOS terminal

Path to enter into DOS environment:


Start menu  Run type cmd

MS-DOS Basics - A Tutorial

This tutorial gives you an opportunity to try basic MS-DOS commands. By following the
procedures in this section, you will learn to:

1. View the contents of a directory

I.KAVITHA JACKLEEN M.Tech


6
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
2. Make a directory
3. Change from one directory to another
4. Create and delete directories
5. Change from one drive to another
6. Copy files
7. Rename files
8. Delete files
9. Developing C program

The Command Prompt

When you first turn on your computer, you will see some cryptic information flash by. MS-DOS
displays this information to let you know how it is configuring your computer. You can ignore it for now.
When the information stops scrolling past, you'll see the following:

C:\>
This is called the command prompt or DOS prompt. The flashing underscore next to the
command prompt is called the cursor. The cursor shows where the command you type will appear.

Typing a Command

This section explains how to type a command at the command prompt and demonstrates the "Bad
command or file name" message.

To type a command at the command prompt

1. Type the following at the command prompt (you can type the command in either uppercase or
lowercase letters ):

nul

If you make a typing mistake, press the BACKSPACE key to erase the mistake, and then try again.

2. Press ENTER.

You must press ENTER after every command you type.

The following message appears:

Bad command or file name

The "Bad command or file name" message appears when you type something that MSDOS does
not recognize. Because nul is not a valid MS-DOS command, MS-DOS displays the "Bad command or
file name" message.

3. Now, type the following command at the command prompt:

ver

The following message appears on your screen:

MS-DOS version 6.22

I.KAVITHA JACKLEEN M.Tech


7
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
1Viewing the Contents of a Directory

In this section, you will view the contents of a directory by using the dir command. The dir command
stands for "directory."

• To view the contents of a directory

1. Type the following at the command prompt:

dir :- A list of the files in the WINDOWS directory appears, but scrolls by too quickly to read. You can
modify the dir command so that it displays only one screen of information at a time.

o To view the contents of a directory one screen at a time(Use dir command)

A list similar to the following appears:

Volume in drive C is MS-DOS_6.22

Volume Serial Number is lE49-15E2

Directory of C:\

WINDOWS <DIR> 09-08-92 10:27p

TEMP <DIR> 05-15-92 12:09p

CONFIG SYS 278 09-23-92 10:50a

COMMAND COM 53014 09-18-92 6:00a

WINA20 386 9349 11-11-91 5:00a

DOS <DIR> 09-02-92 4:23p

AUTOEXEC BAT 290 09-23-92 10:54a

7 file(s) 62931 bytes

8732672 bytes free

This is called a directory list. A directory list is a list of all the files and subdirectories that a
directory contains. In this case, you see all the files and directories in the main or root directory of your
drive. All the files and directories on your drive are stored in the root directory.

dir

1. Type the following at the command prompt:

dir /p

One screen of information appears. At the bottom of the screen, you will see the following message:

Press any key to continue . . .

I.KAVITHA JACKLEEN M.Tech


8
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
2. To view the next screen of information, press any key on your keyboard. Repeat this step until the
command prompt appears at the bottom of your screen.

When you typed the dir command this time, you included the /p switch after the command. A switch
modifies the way MS-DOS carries out a command. Generally, a switch consists of a forward slash (/) that
is followed by one or more letters or numbers.

When you used the /p switch with the dir command, you specified that MS-DOS should pause after it
displays each screen of directory list information. The p actually stands for

"page"

Another helpful switch you can use with the dir command is the /w switch. The /w switch indicates that
MS-DOS should show a wide version of the directory list.

o To view the contents of a directory in wide format

1. Type the following at the command prompt:

dir /w

The directory list appears, with the filenames listed in wide format. Note that only filenames are listed.
No information about the files' size or date and time of creation appears.

2. If the directory contains more files than will fit on one screen, you can combine the /p and /w switches
as follows:

dir /w /p

Changing Back to the Root Directory

Next, you will change from the DOS directory to the root directory. The root directory is the directory
you were in before you changed to the DOS directory. Before you begin this section, make sure your
command prompt looks like the following:

C:\DOS>

o To change to the root directory

1. Type the following at the command prompt:

cd \

Note : that the slash you type in this command is a backslash (\), not a forward slash (/).

No matter which directory you are in, this command always returns you to the root directory of a
drive. The root directory does not have a name. It is simply referred to by a backslash (\).

The command prompt should now look like the following:

C:\>

I.KAVITHA JACKLEEN M.Tech


9
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
When your command prompt appears similar to this---that is, when it does not contain the name
of a directory---you are in the root directory.

Changing Directories

Look at the list on your screen. All the names that have <DIR> beside them are directories. You
can see a list of the files in another directory by changing to that directory, and then using the dir
command again. In this case, you will change to the DOS directory. Before you begin this section, make
sure you have a directory named DOS by carrying out the following procedure.

o To make sure you have a directory named Windows

1.If you do not see a line in the directory list indicating that you have a directory named Windows, type
the following at the command prompt:

dir /s Windows

You will see a message that includes a line such as the following:

Directory of C:\DIRNAME

o To change from the root directory to the WINDOWS directory

To change directories, you will use the cd command. The cd command stands for "change directory."

1. Type the following at the command prompt:

cd windows

The command prompt changes. It should now look like the following:

C:\WINDOWS>

Next, you will use the dir command to view a list of the files in the DOS directory.

o To view a list of the files in the WINDOWS directory

1. Type the following at the command prompt:

2Make a Directory

Creates a directory.

MKDIR [drive:]path (OR) MD [drive:]path

If Command Extensions are enabled MKDIR changes as follows:

MKDIR creates any intermediate directories in the path, if needed. For example, assume \a does not exist
then:

Syntax: C:\>md <directory_name>

Ex: C:\>md Fruit

I.KAVITHA JACKLEEN M.Tech


10
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
3

4(a)Creating a Directory

In this section, you will create two directories. Creating a directory is helpful if you want to organize
related files into groups to make them easy to find. Before you begin this section, make sure the
command prompt looks like the following:

C:\>

To create a directory, you will use the md command. The md command stands for "make directory."

o To create and change to a directory named FRUIT

1. Type the following at the command prompt:

md fruit

You have now creat ed a directory named FRUIT. You won't see the new FRUIT directory until you carry
out the dir command in the next step.

2. To confirm that you successfully created the FRUIT directory, type the following at the command
prompt:

dir

or

dir /p

Look through the directory list. A new entry somewhere in the list should look

similar to the following:

FRUIT <DIR> 09-25-93 12:09p

3. To change to the new FRUIT directory, type the following at the command

prompt:

cd fruit

The command prompt should now look like the following:

C:\FRUIT>

You will now create a directory within the FRUIT directory, named GRAPES.

o To create and work with a directory named GRAPES

1. Type the following at the command prompt:

md grapes

You will not see the new GRAPES directory until you carry out the dir command in the
I.KAVITHA JACKLEEN M.Tech
11
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
next step.

2. To confirm that you successfully created the GRAPES directory, type the following at the

command prompt:

dir

A list similar to the following appears:

Volume in drive C is MS-DOS-6

Volume Serial Number is lE49-15E2

Directory of C:\FRUIT

. <DIR> 09-25-93 12:08p

.. <DIR> 09-25-93 12:08p

GRAPES <DIR> 09-25-93 12:10p

3 file(s) 0 bytes

11534336 bytes free

Note that there are three entries in the FRUIT directory. One is the GRAPES directory that you just
created. There are two other entries---one looks like a single period (.) and the other looks like a double
period (..). These directory entries are important to MSDOS, but you can ignore them. They appear in
every directory and cont ain information

relation to the directory structure.

The GRAPES directory is a subdirectory of the FRUIT directory. A subdirectory is a directory within
another directory. Subdirectories are useful if you want to further subdivide information.

3. To change to the GRAPES directory, type the following at the command prompt:

cd grapes

The command prompt should now look like the following:

C:\FRUIT\GRAPES>

4. To switch back to the FRUIT directory, type the following:

cd ..

The command prompt should now look like the following:

C:\FRUIT>

When the cd command is followed by two periods (..), MS-DOS moves up one level in the directory
structure. In this case, you moved up one level from the GRAPES directory to the FRUIT directory.

I.KAVITHA JACKLEEN M.Tech


12
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
4(b)Deleting a Directory

If you no longer use a particular directory, you may want to delete it to simplify your directory structure.
Deleting a directory is also useful if you type the wrong name when you are creating a directory and you
want to delete the incorrect

directory before creating a new one. In this section, you will delete the GRAPES directory. Before you
begin this

section, make sure the command prompt looks like the following:

C:\FRUIT>

To delete a directory, use the rd command. The rd command stands for "remove

directory."

o To delete the GRAPES directory

1. Type the following at the command prompt:

rd grapes

2. To confirm that you successfully deleted the GRAPES directory, type the following at the command
prompt:

dir

The GRAPES directory should no longer appear in the directory list.

Note You cannot delete a directory if you are in it. Before you can delete a directory, you must make the
directory that is one level higher the current directory. To do this, type cd.. at the command prompt.

5Changing Drives

This section describes how to change drives. Changing drives is useful if you want to work with files that
are on a different drive. So far, you have been working with drive C. You have other drives you can use to
store information. For example, drive D.

following:

C:\FRUIT>

o To change to and view files on a different drive

1. Type the following at the command prompt:

d:

Note that the command prompt changed to the following:

D:\>
I.KAVITHA JACKLEEN M.Tech
13
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

2. Change back to drive C by typing the following at the command prompt:

c:\> cd Fruit

Your command prompt should return to the following:

C:\FRUIT>

When you type a drive letter followed by a colon, you change to that drive. The drive letter that appears
in the command prompt shows which drive is the current drive.

following this procedure.

o To view the contents of the WINDOWS directory on drive C

1. Type the following at the command prompt:

dir c:\windows

A list of the files in the DOS directory on drive C should scroll past on your screen.

6Copying Files

This section describes how to copy a single file and a group of files. Copying files creates a duplicate of
the original file and does not remove the original file. This is useful for many reasons. For example, if
you want to work on a document at home, you can copy it from your computer at work to a floppy disk
and then take the floppy disk home. To copy a file, you will use the copy command. When you use the
copy command, you must include two parameters. The first is the location and name of the file you want
to copy, or the source. The second is the location to which you want to copy the file, or the destination.
You separate the source and destination with a space. The copy command follows this pattern:

syntax:

copy <source path> <destination path>

• Copying a Single File

In this section, you will copy the notepad.exe files from the WINDOWS directory to the FRUIT
directory. You will specify the source and destination of these files in two different ways. The difference
between the two methods is explained at the end of this section. Before you begin this section, make sure
the command prompt looks like the following:

C:\FRUIT>

To copy the NOTEPAD.EXE files from the WINDOWS directory to the FRUIT directory

1. Return to the root directory by typing the following at the command prompt:

cd\

I.KAVITHA JACKLEEN M.Tech


14
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
The command prompt should now look like the following:

C:\>

Change to the DOS directory by typing the following at the command prompt:

cd windows

The command prompt should now look like the following:

C:\WINDOWS>

2. Make sure the file you are going to copy, NOTEPAD.EXE, is located in the WINDOWS directory by
using the dir command followed by a filename.

dir notepad.exe

A list similar to the following appears:

3. To copy the NOTEPAD.EXE file from the WINDOWS directory to the FRUIT directory, type the
following at the command prompt:

ex:

copy c:\windows\notepad.exe c:\fruit

The following message appears:

1 file(s) copied

4. To confirm that you copied the files successfully, view the contents of the FRUIT directory by typing
the following at the command prompt:

dir \fruit

You should see the file listed in the FRUIT directory.

7Renaming Files

This section explains how to rename files. You may want to rename a file if the information in it changes
or if you decide you prefer another name.

To rename a file, you will use the ren command. The ren command stands for "rename." When you use
the ren command, you must include two parameters. The first is the file you want to rename, and the
second is the new name for the file. You separate the two names with a space. The ren command follows
this pattern:

ren oldname newname

• Renaming a File

I.KAVITHA JACKLEEN M.Tech


15
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
In this section, you will rename the README.TXT file. Before you begin this section, make sure your
command prompt looks like the following:

C:\FRUIT>

1. To rename the NOTEPAD.EXE file to PADNOTE.TXT, type the following at the command prompt:

ren notpad.exe padnote.txt

2. To confirm that you renamed the file successfully, type the following at the command prompt:

dir

8Deleting Files

This section explains how to delete, or remove, a file that you no longer want on your disk. If you don’t

have very much disk space, deleting files you no longer use is essential.

To delete a file, you will use the del command. The del command stands for "delete."

• Deleting a File

In this section, you will delete two files using the del command.

Before you begin, make sure your command prompt looks like the following:

C:\FRUIT>

To delete the PEARCOM and PEAR.HLP files

1. Delete the PADNOTE.TXT file by typing the following at the command prompt:

del PADNOTE.TXT

2. To confirm that you deleted the files successfully, type the following at the command prompt:

dir

Deleting a Group of Files

In this section, you will use wildcards to delete a group of files.

Before you begin this section, make sure your command prompt looks like the following:

C:\FRUIT>

To delete files in the current directory that end with the extension OLD by using wildcards

1. View all files that end with the extension OLD by typing the following at the command prompt:

dir *.old

I.KAVITHA JACKLEEN M.Tech


16
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
A list of all the files that end with the extension OLD appears. Make sure that these are the files you want
to delete. When you are deleting files by using wildcards, this step is very important. It will prevent you
from deleting files accidentally.

2. Delete all files ending with OLD by typing the following at the command prompt:

del *.old

3. To confirm that all the files with the extension OLD have been deleted, type the following at the

command prompt:

dir

The FRUIT directory should contain no files.

Now that the FRUIT directory is empty, you can delete it by using the rd (remove directory) command
that

you learned to use in "Deleting a Directory" earlier in this chapter.

9Developing C program
Use Command called tc for Turboc IDE
C:\>cd FRUIT
C:\Fruit\>tc

Linux commands:
Basic File handling commands:
1. mkdir – make directories
I.KAVITHA JACKLEEN M.Tech
17
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
Usage: mkdir [OPTION] DIRECTORY...
eg. mkdir ece
2. ls – list directory contents
Usage: ls [OPTION]... [FILE]...
eg. ls ece, ls l ece, ls
3. pwd print name of current working directory
Usage: pwd
4. cd – changes directories
Usage: cd [DIRECTORY]
eg. cd ece
5. cp – copy files and directories
Usage: cp [OPTION]... SOURCE DEST
eg. cp sample.txt sample_copy.txt
cp sample_copy.txt target_dir
6. mv – move (rename) files
Usage: mv [OPTION]... SOURCE DEST
eg. mv source.txt target_dir
mv old.txt new.txt
7. rm remove files or directories
Usage: rm [OPTION]... FILE...
eg. rm file1.txt , rm rf some_dir
8. find – search for files in a directory hierarchy
Usage: find [OPTION] [path] [pattern]
eg. find file1.txt, find name file1.txt
9. history – prints recently used commands
Usage: history
10. vi – Visual editor, a programmers text editor
Usage: vi [OPTION] [file]...
eg. vi file1.txt
Getting Started with C :
Towards Running a C program
To begin with, a C program has to be prepared in two stages
i. Firstly, the program is written in a file using an editor (vi in our case). This form of the program is
called the source program (or source text), and it is not possible to execute this file as is.

ii. Secondly, the completed source file is passed to a compiler – a program which generates a new file
containing a machine code translation of the source text. This file is called as object file or executable
file. The executable file is said to have been compiled from the source text.

I.KAVITHA JACKLEEN M.Tech


18
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

Steps in creating executable files are as shown in figure below.


The compilation and execution process of C can be divided in to multiple steps:
1. Compilation - Using a Compiler program to convert C source to assembly code.
2. Assembly - Using a Assembler program to convert assembly source code to object code.
3. Linking - Using a Linker program to convert object code to executable code. Multiple units of
object codes are linked to together in this step.
4. Loading - Using a Loader program to load the executable code into CPU for execution.

Each instruction in a C program is written as a separate statement, ending with a semicolon. These
statements must appear in the same order in which we wish them to be executed; unless the logic of the
problem demands transfer of control to a statement which is out of sequence. [If you don’t understand
this last statement it is alright!]
Your First C Program
Step #1: Typing the program
1(a) Using the vi editor create a file called prog1.c

Commands for Editing text and quit form the vi editor


I Inserts text to the left of the cursor.

:w To save your file but not quit vi

:w <filename> To save the contents in the screen (buffer) into the file

:q To quit if you haven't made any edits

I.KAVITHA JACKLEEN M.Tech


19
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
:q! To quit with out saving the changes made in the current edit

:wq To both quit and save your edits.

ZZ To both quit and save your edits.


[user@localhost: Lab2] $ vi prog1.c
1(b) Type the following program in the file, prog1.c
#include<stdio.h>
int main(void) /* main() is the entry point of the program */
{
int a,b,c; /* Variable Declaration */
/* a,b,c are declared to be of type “int” */
a=10; /* Assign some number values to ‘a’ and ‘b’ */
b=20;
c=a+b; /* Add the data in ‘a’ and ‘b’ */
/* and store the result in ‘c’ */
/* Print the result of addition */
printf(“The result is %d\n”,c);
return 0;
}
Note: In the above program, the statements that appear enclosed in “/* */” are called comments. These
comments are not strictly a part of the program itself. The comments are just added to improve the
understanding of the reader. These are ignored by the compiler and have no effect on the outcome of the
program
1(c) Save and quit from the file, prog1.c (by typing ESC and :wq)
Step #2: Compiling the C program
You need the GNU C compiler(gcc) for compiling a C program and creating an executable file. Use the
command named gcc to compile program. First make sure you have gcc available in your computer: type
the following command to verify that.
[user@localhost: Lab2] $ which gcc
Output will be /usr/bin/gcc
Type the following command to find the version of gcc
[user@localhost: Lab2] $ gcc –- version
In order to invoke the gcc compiler and compile your c program, type the following command:
Method 1:
[user@localhost: Lab2] $ gcc prog1.c

If the program has any errors/mistakes, those will get listed. Most of the times, the error messages also
contain the exact line number where we have made the mistake. Errors at this stage would be primarily
because of incorrect usage of the syntax (bad typing of the code), these errors are known as syntax errors.
Look at the given program carefully and correct errors, if any.
If there are no errors, you are ready to see the result of compilation. As already mentioned, the result of
successful compilation should have generated an output file. This output file is called a.out. You can see
this file by typing the “ls” command.
Step #3: Executing the C program
Now we have an output file, a.out ready. To make our machine execute the instructions in the a.out file,
the following command is typed.
[user@localhost: Lab2] $./a.out
Note carefully the usage: we are referring to the current directory ‘.’ and then instructing the computer to
execute the file named ‘a.out’ in the current directory.
a.out is default name of the output file, but you can name the output file by using –o when compiling
your .c file.

I.KAVITHA JACKLEEN M.Tech


20
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

Method 2:
[user@localhost: Lab2] $gcc –o exefile prog1.c
use ls command to see the file exefile existed or not.
Now execute your program as below
[user@localhost: Lab2] $./exefile

I.KAVITHA JACKLEEN M.Tech


21
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
PROGRAM 2: Study of the Editors, Integrated development environments, and Compilers in
chosen platform.

AIM: To Study of the Editors, Integrated development environments, and Compilers in chosen
Editors:
Definition :A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages, and can be
used to change configuration files and programming language source code.
Plain text files vs. word processor files
There are important differences between plain text files created by a text editor and document files
created by word processors such asMicrosoft Word, WordPerfect, and OpenOffice.org.

 A plain text file uses a simple character set such as ASCII to represent numbers, letters, and a
small number of symbols. The onlynon-printing characters in the file that can be used to format the
text, are newline, tab, and formfeed.

 Word processor documents generally contain formatted text, such as enabling text to appear in
boldface and italics, to use multiplefonts, and to be structured into columns and tables. These
capabilities were once associated only with desktop publishing, but are now available in the simplest
word processor.

 Web pages are plain text, with HTML tags to achieve formatting.
Word processors were developed to allow formatting of text for presentation on a printed page, while text
produced by text editors is generally used for other purposes, such as input data for a computer program.
When both formats are available, the user must select with care. Saving a plain text file in a word-
processor format will add formatting information that could disturb the machine-readability of the text.
Saving a word-processor document as a text file will lose formatting information.
Types of text editors :
1) Small and Simple Text Editors:,
Under Microsoft Windows systems come with the simpleNotepad, though many people—
especially programmers—prefer another Windows text editor with more features.
Under Apple Macintosh's classic Mac OS there was the native SimpleText, which was replaced
under Mac OS X by TextEdit, which merges features of a text editor with those of a word
processor such as rulers, margins and multiple font selection.
2) A Text editor with complex functions :
In Unix-like operating systems have the
a) vi editor (or a variant)
b) Emacs editor.
3) Dual operating modes editors: It can allow either a text editor or a word processor., Such
as WordStar

I.KAVITHA JACKLEEN M.Tech


22
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
4) Text editors for professional users : It can edit files of arbitrary sizes, such as log files or
unusually large texts, such as an entire dictionary placed in a single file.
5) Programmable editors:
a) It can be customized for specific uses. For example, Emacs can be customized by
programming in Lisp. Its Functionality is to make a text editor use the commands of another
text editor with which the user is more familiar.
b) An important group of programmable editors uses REXX as the scripting language. These
"orthodox editors" let the user open a "command line" into which commands and REXX
statements can be typed.
c) IBM's editor forVM/CMS. Among them are THE, KEDIT, SlickEdit, X2, Uni-edit, UltraEdit,
and SEDIT.
d) In Unix environment has vi derivatives such as Vim also support folding as well as macro
languages, and also have a command line.
6) A Text editors for software developers: It include source code syntax highlighting and
automatic completion to make programs easier to read and write.
Editor Features:

1. String searching algorithm – search string with a replacement string. Different methods are
employed, Global(ly) Search And Replace, Conditional Search and Replace, Unconditional
Search and Replace.

2. Cut, copy, and paste – most text editors provide methods to duplicate and move text within the
file, or between files.

3. Text formatting – Text editors often provide basic formatting features like line wrap, auto-
indentation, bullet list formatting, comment formatting, and so on.

4. Undo and redo – As with word processors, text editors will provide a way to undo and redo the
last edit. Often—especially with older text editors—there is only one level of edit history
remembered and successively issuing the undo command will only "toggle" the last change.
Modern or more complex editors usually provide a multiple level history such that issuing the
undo command repeatedly will revert the document to successively older edits. A separate redo
command will cycle the edits "forward" toward the most recent changes. The number of changes
remembered depends upon the editor and is often configurable by the user.

5. Data transformation – Reading or merging the contents of another text file into the file currently
being edited. Some text editors provide a way to insert the output of a command issued to the
operating system's shell.

6. Ability to handle UTF-8 encoded text.

7. Filtering – Some advanced text editors allow the editor to send all or sections of the file being
edited to another utility and read the result back into the file in place of the lines being "filtered".
This, for example, is useful for sorting a series of lines alphabetically or numerically, doing
mathematical computations, and so on.

I.KAVITHA JACKLEEN M.Tech


23
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
8. Syntax highlighting – contextually highlights software code and other text that appears in an
organized or predictable format.
Specialised editors:
Some editors include special features and extra functions, for instance,

1. Source code editors : are text editors with additional functionality to facilitate the production of
source code. These often feature user-programmable syntax highlighting, and coding tools or
keyboard macros similar to an HTML editor (see below).

2. Folding editors : This subclass includes so-called "orthodox editors" that are derivatives of Xedit.
The specialized version of folding is usually called outlining (see below).
3. IDEs (integrated development environments) : are designed to manage and streamline larger
programming projects. They are usually only used for programming as they contain many features
unnecessary for simple text editing.
4. World Wide Web authors are offered a variety of text editors dedicated to the task of web
development. These create the plain text files that deliver web pages.
HTML editors include: Dreamweaver, E Text Editor, Microsoft
FrontPage, HotDog, Homesite, Nvu, Tidy, and GoLive. Many offer the option of viewing a work
in progress on a built-in web browser. XML editors share many traits.

5. For Mathematicians, physicists, and computer scientists often produce articles and books
using TeX or LaTeX in plain text files.
6. Outliners( also called tree-based editors) :They combine a hierarchical outline tree with a text
editor. Folding (see above) can generally be considered a generalized form of outlining.
7. Simultaneous editing : It is a technique in End-user development research to edit all items in a
multiple selection. It allows the user to manipulate all the selected items at once through direct
manipulation. The Lapis text editor and the multi edit plugin for geditare examples of this
technique. The Lapis editor can also create an automatic multiple selection based on an example
item.
8. Distraction-free editors : provide a minimalistic interface with the purpose of isolating the writer
from the rest of the applications and operating system, thus being able to focus on the writing
alone.
IDE(Integrated Development Environment)
An integrated development environment (IDE) or interactive development environment is
a software application that provides comprehensive facilities to computer programmers for software
development.An IDE normally consists of a source code editor, build automation tools and adebugger.
Several modern IDEs integrate with Intelli-sense coding features.
Some IDEs contain a compiler, interpreter, or both, such as Net Beans and Eclipse; others do not,
such as SharpDevelop and Lazarus. The boundary between an integrated development environment and
other parts of the broadersoftware development environment is not well-defined. Sometimes a version
control system and various tools are integrated to simplify the construction of a GUI(Graphical User
Interface). Many modern IDEs also have a class browser, an object browser, and a class
hierarchy diagram, for use in object-oriented software development.
 Some familiar IDEs for doing C-programming in windows and in linux environments are
given below:
Fig (a): Turbo c IDE in windows environment

I.KAVITHA JACKLEEN M.Tech


24
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

Fig (b): Turboc++ IDE in windows environment

I.KAVITHA JACKLEEN M.Tech


25
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual

Fig(b): Anjuta, a C and C++ IDE for the GNOME environment(LINUX Envrionment)
Compilers in chosen platform

1.1Compilation:

I.KAVITHA JACKLEEN M.Tech


26
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
Compilation is a process that translates a program in one language (the source

language) into an equivalent program in another language (the object or target language).

Compilation is a fundamental concept in the production of software: it is the link between the
(abstract) world of application development and the low-level world of application execution on
machines.

Compiler :
An important part of any compiler is the detection and reporting of errors.

Commonly, the source language is a highlevel programming language (i.e. a problem-oriented


language), and the target language is a machine language or assembly language (i.e. a machine-oriented
language).

1) Compiler is a program that translates source code into object code.


2) The compiler derives its name from the way it works, looking at the entire piece of source code
and collecting and reorganizing the instructions.
3) Compiler differs from an interpreter, that which analyzes interpreter executes each line of source
code in succession, without looking at the entire program.
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a compiler
is often called a “cross-compiler”.

On the other hand, a compiler need not target a real assembly (or machine) language.

Compilers translate source code into object code, which is unique for each type of computer.
many compilers are available for the same language. For example, there is a FORTRAN compiler for PCs
I.KAVITHA JACKLEEN M.Tech
27
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
and another for Apple Macintosh computers. In addition, the compiler industry is quite competitive, so
there are actually many compilers for each language on each type of computer. More than a dozen
companies develop and sell C compilers for the PC.

1.2Asse
mbler:

An assembler is also a type of translator, which converts Assembly program into Machine Program.

1.3 Interpreter:

An interpreter is closely related to a compiler, but takes both source program and input data.

The translation and execution phases of the source program are one and the same.

E.g. Java compilers generate code for a virtual machine called the “Java Virtual Machine” (JVM).
The JVM interpreter then interprets JVM instructions without any further translation.
The advantages of using an interpreter are that is easy to port a language to a new machine: all
one has to do is to implement the virtual machine on the new hardware. Also, since instructions are
evaluated and examined at run-time, it becomes possible to implement very flexible languages. E.g. for
an interpreter it is not a problem to support variables that have a dynamic type, something which is hard
to do in a traditional compiler. Interpreters can even construct “programs” at run time and interpret those
without difficulties, a capability that is available e.g. for Lisp or Prolog.

I.KAVITHA JACKLEEN M.Tech


28
GLOBAL COLLEGE OF ENGINEERING AND TECHNOLOGY::KADAPA
I-B.Tech I-Sem Computer Programming Lab Manual
Although the above types of translator are the most well-known, we also need knowledge of

compilation techniques to deal with the recognition and translation of many other types of

languages including:

• Command-line interface languages;

• Typesetting / word processing languages (e.g.TEX);

• Natural languages;

• Hardware description languages;

• Page description languages (e.g. PostScript);

• Set-up or parameter files.

Advantages of interpreter over compiler:


a) The advantage of interpreters is that they can execute a program immediately.
b) Compilers require some time before an executable program emerges.
Advantages of compiler over interpreter:
Programs produced by compilers run much faster than the same programs executed by an
interpreter.
2. The Context of a Compiler:

The complete process of compilation is illustrated (a) Expanding macros (shorthand notations for
as: longer constructs). For example, in C,

#define foo(x,y) (3*x+y*(2+x))

defines a macro foo, that when used in later in the


program, is expanded by the

preprocessor. For example, a = foo(a,b) becomes

a = (3*a+b*(2+a))

(b) Inserting named files. For example, in C,

#include "header.h"
2.1 Preprocessors:
is replaced by the contents of the file header.h
Preprocessing performs (usually simple) operations
on the source file(s) prior to compilation.Typical
preprocessing operations include:

I.KAVITHA JACKLEEN M.Tech


29
2.2 Linkers:

A linker combines object code (machine code that has not yet been linked) produced from compiling and
assembling many source programs, as well as standard library functions and resources supplied by the
operating system. This involves resolving references in each object file to external variables and
procedures declared in other files.

2.3 Loaders:

Compilers, assemblers and linkers usually produce code whose memory references are made relative to
an undetermined starting location that can be anywhere in memory (relocatable machine code). A loader
calculates appropriate absolute addresses for these memory locations and amends the code to use these
addresses.

Cross Compiler :
A cross compiler is a compiler capable of creating executable code for a platform other than the
one on which the compiler is running. Cross compiler tools are used to generate executables
for embedded system or multiple platforms. It is used to compile for a platform upon which it is not
feasible to do the compiling, like microcontrollers that don't support an operating system. It has become
more common to use this tool for paravirtualization where a system may have one or more platforms in
use.
Not targeted by this definition are source to source translators, which are often mistakenly called
cross compilers.
The Canadian Cross is a technique for building cross compilers for other machines. Given three
machines A, B, and C, one uses machine A (e.g. running Windows XP on an IA-32 processor) to build a
cross compiler that runs on machine B (e.g. running Mac OS Xon an x86-64 processor) to create
executables for machine C (e.g. running Android on an ARM processor). When using the Canadian
Cross with GCC, there may be four compilers involved:
1) The proprietary native Compiler for machine A (1) (e.g. compiler from Microsoft Visual Studio)
is used to build the gcc native compiler for machine A (2).
2) The gcc native compiler for machine A (2) is used to build the gcc cross compiler from machine A
to machine B (3)
3) The gcc cross compiler from machine A to machine B (3) is used to build the gcc cross compiler
from machine B to machine C (4)
[Type the document title] [Year]
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a compiler
is often called a “cross-compiler”.

On the other hand, a compiler need not target a real assembly (or machine) language.

Uses of cross compilers:


The fundamental use of a cross compiler is to separate the build environment from target environment.
This is useful in a number of situations:
 Embedded computers where a device has extremely limited resources. For example, a microwave
oven will have an extremely small computer to read its touchpad and door sensor, provide output to a
digital display and speaker, and to control the machinery for cooking food. Compiling for multiple
machines. For example, a company may wish to support several different versions of an operating system
or to support several different operating systems. By using a cross compiler, a single build environment
can be set up to compile for each of these targets.
 Compiling on a server farm. Similar to compiling for multiple machines, a complicated build that
involves many compile operations can be executed across any machine that is free, regardless of its
underlying hardware or the operating system version that it is running.
 Bootstrapping to a new platform. When developing software for a new platform, or the emulator
of a future platform, one uses a cross compiler to compile necessary tools such as the operating system
and a native compiler.
 Compiling native code for emulators for older now-obsolete platforms like the Commodore
64 or Apple II by enthusiasts who use cross compilers that run on a current platform (such as Aztec
C's MS-DOS 6502 cross compilers running under Windows XP).
Editors:
Definition :A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages, and can be
used to change configuration files and programming language source code.
Plain text files vs. word processor files
There are important differences between plain text files created by a text editor and document files
created by word processors such asMicrosoft Word, WordPerfect, and OpenOffice.org.

 A plain text file uses a simple character set such as ASCII to represent numbers, letters, and a
small number of symbols. The onlynon-printing characters in the file that can be used to format the
text, are newline, tab, and formfeed.

 Word processor documents generally contain formatted text, such as enabling text to appear in
boldface and italics, to use multiplefonts, and to be structured into columns and tables. These
capabilities were once associated only with desktop publishing, but are now available in the simplest
word processor.

 Web pages are plain text, with HTML tags to achieve formatting.
Word processors were developed to allow formatting of text for presentation on a printed page, while text
produced by text editors is generally used for other purposes, such as input data for a computer program.

P.SRILATHA M.Tech
Departement of CSE 31
[Type the document title] [Year]
When both formats are available, the user must select with care. Saving a plain text file in a word-
processor format will add formatting information that could disturb the machine-readability of the text.
Saving a word-processor document as a text file will lose formatting information.
Types of text editors :
7) Small and Simple Text Editors:,
Under Microsoft Windows systems come with the simpleNotepad, though many people—
especially programmers—prefer another Windows text editor with more features.
Under Apple Macintosh's classic Mac OS there was the native SimpleText, which was replaced
under Mac OS X by TextEdit, which merges features of a text editor with those of a word
processor such as rulers, margins and multiple font selection.
8) A Text editor with complex functions :
In Unix-like operating systems have the
c) vi editor (or a variant)
d) Emacs editor.
9) Dual operating modes editors: It can allow either a text editor or a word processor., Such
as WordStar
10) Text editors for professional users : It can edit files of arbitrary sizes, such as log files or
unusually large texts, such as an entire dictionary placed in a single file.
11) Programmable editors:
e) It can be customized for specific uses. For example, Emacs can be customized by
programming in Lisp. Its Functionality is to make a text editor use the commands of another
text editor with which the user is more familiar.
f) An important group of programmable editors uses REXX as the scripting language. These
"orthodox editors" let the user open a "command line" into which commands and REXX
statements can be typed.
g) IBM's editor forVM/CMS. Among them are THE, KEDIT, SlickEdit, X2, Uni-edit, UltraEdit,
and SEDIT.
h) In Unix environment has vi derivatives such as Vim also support folding as well as macro
languages, and also have a command line.
12) A Text editors for software developers: It include source code syntax highlighting and
automatic completion to make programs easier to read and write.
Editor Features:

9. String searching algorithm – search string with a replacement string. Different methods are
employed, Global(ly) Search And Replace, Conditional Search and Replace, Unconditional
Search and Replace.

10. Cut, copy, and paste – most text editors provide methods to duplicate and move text within the
file, or between files.

P.SRILATHA M.Tech
Departement of CSE 32
[Type the document title] [Year]
11. Text formatting – Text editors often provide basic formatting features like line wrap, auto-
indentation, bullet list formatting, comment formatting, and so on.

12. Undo and redo – As with word processors, text editors will provide a way to undo and redo the
last edit. Often—especially with older text editors—there is only one level of edit history
remembered and successively issuing the undo command will only "toggle" the last change.
Modern or more complex editors usually provide a multiple level history such that issuing the
undo command repeatedly will revert the document to successively older edits. A separate redo
command will cycle the edits "forward" toward the most recent changes. The number of changes
remembered depends upon the editor and is often configurable by the user.

13. Data transformation – Reading or merging the contents of another text file into the file currently
being edited. Some text editors provide a way to insert the output of a command issued to the
operating system's shell.

14. Ability to handle UTF-8 encoded text.

15. Filtering – Some advanced text editors allow the editor to send all or sections of the file being
edited to another utility and read the result back into the file in place of the lines being "filtered".
This, for example, is useful for sorting a series of lines alphabetically or numerically, doing
mathematical computations, and so on.

16. Syntax highlighting – contextually highlights software code and other text that appears in an
organized or predictable format.
Specialised editors:
Some editors include special features and extra functions, for instance,

9. Source code editors : are text editors with additional functionality to facilitate the production of
source code. These often feature user-programmable syntax highlighting, and coding tools or
keyboard macros similar to an HTML editor (see below).

10. Folding editors : This subclass includes so-called "orthodox editors" that are derivatives of Xedit.
The specialized version of folding is usually called outlining (see below).
11. IDEs (integrated development environments) : are designed to manage and streamline larger
programming projects. They are usually only used for programming as they contain many features
unnecessary for simple text editing.
12. World Wide Web authors are offered a variety of text editors dedicated to the task of web
development. These create the plain text files that deliver web pages.
HTML editors include: Dreamweaver, E Text Editor, Microsoft
FrontPage, HotDog, Homesite, Nvu, Tidy, and GoLive. Many offer the option of viewing a work
in progress on a built-in web browser. XML editors share many traits.

13. For Mathematicians, physicists, and computer scientists often produce articles and books
using TeX or LaTeX in plain text files.
14. Outliners( also called tree-based editors) :They combine a hierarchical outline tree with a text
editor. Folding (see above) can generally be considered a generalized form of outlining.

P.SRILATHA M.Tech
Departement of CSE 33
[Type the document title] [Year]
15. Simultaneous editing : It is a technique in End-user development research to edit all items in a
multiple selection. It allows the user to manipulate all the selected items at once through direct
manipulation. The Lapis text editor and the multi edit plugin for geditare examples of this
technique. The Lapis editor can also create an automatic multiple selection based on an example
item.
16. Distraction-free editors : provide a minimalistic interface with the purpose of isolating the writer
from the rest of the applications and operating system, thus being able to focus on the writing
alone.
IDE(Integrated Development Environment)
An integrated development environment (IDE) or interactive development environment is
a software application that provides comprehensive facilities to computer programmers for software
development.An IDE normally consists of a source code editor, build automation tools and adebugger.
Several modern IDEs integrate with Intelli-sense coding features.
Some IDEs contain a compiler, interpreter, or both, such as Net Beans and Eclipse; others do not, such
as SharpDevelop and Lazarus. The boundary between an integrated development environment and other
parts of the broadersoftware development environment is not well-defined. Sometimes a version control
system and various tools are integrated to simplify the construction of a GUI(Graphical User Interface).
Many modern IDEs also have a class browser, an object browser, and a class hierarchy diagram, for use
in object-oriented software development.
 Some familiar IDEs for doing C-programming in windows and in linux environments are
given below:
Fig (a): Turbo c IDE in windows environment

Fig (b): Turboc++ IDE in windows environment

P.SRILATHA M.Tech
Departement of CSE 34
[Type the document title] [Year]

Fig(b): Anjuta, a C and C++ IDE for the GNOME environment(LINUX Envrionment)

P.SRILATHA M.Tech
Departement of CSE 35
[Type the document title] [Year]

Compilers in chosen platform

1.1Compilation:

Compilation is a process that translates a program in one language (the source

language) into an equivalent program in another language (the object or target language).

Compilation is a fundamental concept in the production of software: it is the link between the
(abstract) world of application development and the low-level world of application execution on
machines.

Compiler :
An important part of any compiler is the detection and reporting of errors.

Commonly, the source language is a highlevel programming language (i.e. a problem-oriented


language), and the target language is a machine language or assembly language (i.e. a machine-oriented
language).

4) Compiler is a program that translates source code into object code.

P.SRILATHA M.Tech
Departement of CSE 36
[Type the document title] [Year]
5) The compiler derives its name from the way it works, looking at the entire piece of source code
and collecting and reorganizing the instructions.
6) Compiler differs from an interpreter, that which analyzes interpreter executes each line of source
code in succession, without looking at the entire program.
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a compiler
is often called a “cross-compiler”.

On the other hand, a compiler need not target a real assembly (or machine) language.

Compilers translate source code into object code, which is unique for each type of computer.
many compilers are available for the same language. For example, there is a FORTRAN compiler for
PCs and another for Apple Macintosh computers. In addition, the compiler industry is quite competitive,
so there are actually many compilers for each language on each type of computer. More than a dozen
companies develop and sell C compilers for the PC.

1.2Asse
mbler:

An assembler is also a type of translator, which converts Assembly program into Machine Program.

P.SRILATHA M.Tech
Departement of CSE 37
[Type the document title] [Year]

1.3 Interpreter:

An interpreter is closely related to a compiler, but takes both source program and input data.

The translation and execution phases of the source program are one and the same.

E.g. Java compilers generate code for a virtual machine called the “Java Virtual Machine” (JVM).
The JVM interpreter then interprets JVM instructions without any further translation.
The advantages of using an interpreter are that is easy to port a language to a new machine: all
one has to do is to implement the virtual machine on the new hardware. Also, since instructions are
evaluated and examined at run-time, it becomes possible to implement very flexible languages. E.g. for
an interpreter it is not a problem to support variables that have a dynamic type, something which is hard
to do in a traditional compiler. Interpreters can even construct “programs” at run time and interpret those
without difficulties, a capability that is available e.g. for Lisp or Prolog.

Although the above types of translator are the most well-known, we also need knowledge of

compilation techniques to deal with the recognition and translation of many other types of

languages including:

• Command-line interface languages;

• Typesetting / word processing languages (e.g.TEX);

• Natural languages;

• Hardware description languages;

• Page description languages (e.g. PostScript);

• Set-up or parameter files.

Advantages of interpreter over compiler:


c) The advantage of interpreters is that they can execute a program immediately.
P.SRILATHA M.Tech
Departement of CSE 38
[Type the document title] [Year]
d) Compilers require some time before an executable program emerges.
Advantages of compiler over interpreter:
Programs produced by compilers run much faster than the same programs executed by an
interpreter.

2. The Context of a Compiler:

The complete process of compilation is


illustrated as:
Preprocessing performs (usually simple)
operations on the source file(s) prior to
compilation.Typical preprocessing operations
include:

(a) Expanding macros (shorthand notations for


longer constructs). For example, in C,

#define foo(x,y) (3*x+y*(2+x))

defines a macro foo, that when used in later in


the program, is expanded by the

preprocessor. For example, a = foo(a,b)


becomes

a = (3*a+b*(2+a))

(b) Inserting named files. For example, in C,

#include "header.h"
2.1 Preprocessors: is replaced by the contents of the file header.h

P.SRILATHA M.Tech
Departement of CSE 39
2.2 Linkers:

A linker combines object code (machine code that has not yet been linked) produced from
compiling and assembling many source programs, as well as standard library functions and
resources supplied by the operating system. This involves resolving references in each object file to
external variables and procedures declared in other files.

2.3 Loaders:

Compilers, assemblers and linkers usually produce code whose memory references are made
relative to an undetermined starting location that can be anywhere in memory (relocatable machine
code). A loader calculates appropriate absolute addresses for these memory locations and amends
the code to use these addresses.

Cross Compiler :
A cross compiler is a compiler capable of creating executable code for a platform other than
the one on which the compiler is running. Cross compiler tools are used to generate executables
for embedded system or multiple platforms. It is used to compile for a platform upon which it is not
feasible to do the compiling, like microcontrollers that don't support an operating system. It has
become more common to use this tool for paravirtualization where a system may have one or more
platforms in use.
Not targeted by this definition are source to source translators, which are often mistakenly called
cross compilers.
The Canadian Cross is a technique for building cross compilers for other machines. Given
three machines A, B, and C, one uses machine A (e.g. running Windows XP on an IA-32 processor)
to build a cross compiler that runs on machine B (e.g. running Mac OS Xon an x86-64 processor) to
create executables for machine C (e.g. running Android on an ARM processor). When using the
Canadian Cross with GCC, there may be four compilers involved:
4) The proprietary native Compiler for machine A (1) (e.g. compiler from Microsoft Visual
Studio) is used to build the gcc native compiler for machine A (2).
5) The gcc native compiler for machine A (2) is used to build the gcc cross compiler from
machine A to machine B (3)
6) The gcc cross compiler from machine A to machine B (3) is used to build the gcc cross
compiler from machine B to machine C (4)
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Sometimes, a compiler translates between high level languages. E.g. the first C++
implementations used a compiler called “cfront” which translated C++ code to C code. Such a
compiler is often called a “cross-compiler”.

On the other hand, a compiler need not target a real assembly (or machine) language.

Uses of cross compilers:


The fundamental use of a cross compiler is to separate the build environment from target
environment. This is useful in a number of situations:
 Embedded computers where a device has extremely limited resources. For example, a
microwave oven will have an extremely small computer to read its touchpad and door sensor,
provide output to a digital display and speaker, and to control the machinery for cooking food.
Compiling for multiple machines. For example, a company may wish to support several different
versions of an operating system or to support several different operating systems. By using a cross
compiler, a single build environment can be set up to compile for each of these targets.
 Compiling on a server farm. Similar to compiling for multiple machines, a complicated build
that involves many compile operations can be executed across any machine that is free, regardless
of its underlying hardware or the operating system version that it is running.
 Bootstrapping to a new platform. When developing software for a new platform, or the
emulator of a future platform, one uses a cross compiler to compile necessary tools such as the
operating system and a native compiler.
 Compiling native code for emulators for older now-obsolete platforms like the
Commodore 64 or Apple II by enthusiasts who use cross compilers that run on a current
platform (such as Aztec C's MS-DOS 6502 cross compilers running under Windows XP).

N.VENKATASIVA REDDY GCET, KADAPA Page 41 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 3: Write, Edit, Debug, Compile and Execute Sample C programs to understand
the programming environment.

AIM : To Write, Edit, Debug, Compile and Execute Sample C programs to understand the
programming environment.

1Writing a Program:
A sample C program have to write in an Turbo C or Turbo C++ Editor for that
Keys are ALT+F+N
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf(“ Welcome to C Programming Lab“);
getch( );
}
After that save the program with keys ALT+F+S or F2
OUTPUT:
Welcome to C programming Lab_
2Editing the Program:
For editing a program first we have to open the program, for that use the following keys
ALT+F+O or F3
1) Here open your respect C- file from your respective directory.
2) Edit the program( adding or making changes where the error happens).
3Debug the Program:
Debugging is a methodical process of finding and reducing the number of bugs(errors).
The purpose of a debugger is to allow you to see what is going on inside your C program
while it runs.
A debugger is a computer program that lets you run your program, line by line and
examine the values of variables or look at values passed into functions and let you figure out
why it isn't running the way you expected it to.
Here we use Turbo c++ IDE or Turbo C IDE
Step 1:
First we have to add the variable to which you have to inspect the value for that we have to
use
Add watch(ALT+D+W+A or CTRL+F7)
Step 2:
For Inspecting the Program line by line use ALT+R+T or F7
4 Compiling the program :
Use the keys ALT+C+C or ALT+F9
5 Executing or Running the program(To see the output):
Use the keys ALT+R+R or CTRL+F9

N.VENKATASIVA REDDY GCET, KADAPA Page 42 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 4 : Practice programs: Finding the sum of three numbers, exchange of two
numbers,maximum of two numbers, to read and print variable values of all data types of C
language, to find the size of all data types, to understand the priority and associativity of
operators using expressions, to use different library functions of C language.

4a) AIM: To Finding the sum of three numbers


Program:
#include<stdio.h>
void main( )
{
int a,b,c,sum;
clrscr();
printf("Enter Three values:");
scanf("%d%d%d",&a, &b, &c);
sum=a+b+c;
printf("\nsum of 3 numbers is:: %d",sum);
getch();
}
OUTPUT:
Enter a, b and c values:
5
6
2
4b)AIM: To Exchange of two numbers
Program:
#include <stdio.h>
void main( )
{
int a, b, temp;
clrscr( );
printf("Enter the value of a and b\n");
scanf("%d%d", &a, &b);
printf("Before Exchanging\na = %d\nb = %d\n", a, b);
temp = a;
a = b;
b = temp;

printf("After Exchangng\na = %d\nb = %d\n", a, b);


getch();
}
OUTPUT:
Enter the value of a and b
15
53
Before Swapping
a = 15

N.VENKATASIVA REDDY GCET, KADAPA Page 43 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
b = 53
After Swapping
a = 53
b=1
4c)AIM:To Find the Maximum of two numbers
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr( );
a=4;
b=8;

if(a>b)
{
max=a;
}
else
{
max=b;
}
printf("The Maximum of 2 values is : %d", max);
getch();
}
OUTPUT:

The Maximum of 2 values is : 8

4d)AIM: To read and print variable values of all data types of C language
Data type
Char Note Example
Name(data type)

Character(char) ‘c’ Character Notation %c

Integer(int) 'd' decimal notation (e.g. "254") %d, %5d, %05d

Integer(int) 'x' hexadecimal notation (e.g. "EF") %x, %4x, %04x

Float(float) ‘f’ %f

is shown in the
'le' format: [-]d.ddde[+-]dd %le
Double(double)
'lf' is shown in the %lf, %4.7lf
format: [-]dddd.ddd

N.VENKATASIVA REDDY GCET, KADAPA Page 44 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Long(long) 'ld' %ld, %7ld, %07d

String(char
's' String Notation %s
name[size])

Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i;
char c,str[11];
float f;
double d;
long L;
clrscr();
printf("Enter an Integer value ::");
scanf("%d",&i); //Here you can use %x in place of %d
printf("Enter a Long value ::");
scanf("%ld",&L);
printf("Enter a Float value ::");
scanf("%f",&f);
printf("Enter a Double value ::");
scanf("%lf",&d);
fflush(stdin);
printf("Enter a Character value ::");
scanf("%c",&c);
printf("Enter a String ::");
scanf("%s",str);
printf("\nInteger value is :: %d", i);
printf("\nLong Integer value is:: %ld", L);
printf("\nFloat value is :: %f", f);
printf("\nDouble value is :: %lf", d);
printf("\nCharacter value is :: %c",c);
printf("\nString value is :: %s", str);
getch( );
}

OUTPUT:
Enter an Integer value ::15
Enter a Long value ::236589
Enter a Float value ::3.2
Enter a Double value ::6.358954
Enter a Character value ::a
Enter a String ::california

N.VENKATASIVA REDDY GCET, KADAPA Page 45 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Integer value is :: 15
Long Integer value is:: 236589
Float value is :: 3.200000
Double value is :: 6.358954
Character value is :: a
String value is :: california

4e)AIM :To Find the size of all data types


PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("size of char datatype :: %d\n", sizeof(char) );
printf("size of short datatype :: %d\n", sizeof(short) );
printf("size of int datatype :: %d\n", sizeof(int) );
printf("size of long datatype :: %d\n", sizeof(long) );
printf("size of float datatype :: %d\n", sizeof(float) );
printf("size of double datatype :: %d\n", sizeof(double) );
printf("size of long double datatype :: %d\n", sizeof(long double) );
getch();
}
OUTPUT:
size of char datatype :: 1
size of short datatype :: 2
size of int datatype :: 2
size of long datatype :: 4
size of float datatype :: 4
size of double datatype :: 8
size of long double datatype :: 10

4f) AIM: To understand the priority and associativity of Operators using Expressions.

#include <stdio.h>
#include<conio.h>
void main( )
{
int a = 20;
int b = 10;

N.VENKATASIVA REDDY GCET, KADAPA Page 46 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
int c = 15;
int d = 5;
int result;
clrscr( );
result = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is :: %d \n", result );
result = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is :: %d \n" , result );
result = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is :: %d \n", result );
result = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is :: %d \n" , result );
getch( );
}
OUTPUT:
Value of (a + b) * c / d is :: 90
Value of ((a + b) * c) / d is :: 90
Value of (a + b) * (c / d) is :: 90
Value of a + (b * c) / d is :: 50

4g) AIM: To use different library functions of C language


#include<stdio.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
void main()
{
char ch,lc,str[10];
int val,sr,len;
clrscr();
printf("\n\n\n***Using library functions***\n\n");
printf("Enter a upper case character ::");
scanf("%c",&ch);
lc=tolower(ch);
printf("\nThe converted lower case character is ::%c",lc);
printf("\nEnter a value ::");
scanf("%d",&val);
sr=sqrt(val);
printf("\nThe square root of %d is %d",val,sr);
printf("\nEnter a string(without space) ::");
scanf("%s",str);
len=strlen(str);
printf("\nThe length of the given string %s is %d",str,len);
getch( );
}
OUTPUT:
N.VENKATASIVA REDDY GCET, KADAPA Page 47 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
***Using library functions***
Enter a upper case character ::L
The converted lower case character is ::l
Enter a value ::25
The square root of 25 is 5
Enter a string(without space) :: aec_college
The length of the given string aec_college is 11

N.VENKATASIVA REDDY GCET, KADAPA Page 48 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 5: Write a program to find the roots of a quadratic equation.
ALGORITHM:

Step 1: start

Step 2: read a,b,c

Step 3: d=b*b-4*a*c

Step 4: if(d>0)

(i)

(a) root1=(-b+sqrt(d))/(2*a)

(b) root2=(-b-sqrt(d))/(2*a)

(c)print root1,root2

(d)print roots are real

Else

if(d==0)

(i)

(a) root1=-b/(2*a)

(b) root2=-b/(2*a)

(c)print root1,root2

(d)print roots are real and equal

Else

(ii)print roots are imaginary

Step 6: stop

Program:-

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

float a,b,c,d,root1,root2;
N.VENKATASIVA REDDY GCET, KADAPA Page 49 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
clrscr();

printf("Enter the values of a,b,c:");

scanf("%f %f %f",&a,&b,&c);

d=(b*b)-(4*a*c);

if(d>0)

root1=-b+sqrt(d)/(2*a);

root2=-b-sqrt(d)/(2*a);

printf("\nFirst root :: %f\nSecond root ::%f\n",root1,root2);

printf("\nROOTS ARE REAL");

else if(d<0)

printf("\nROOTS ARE IMAGINARY");

else

printf("\nROOTS ARE REAL AND EQUAL");

getch();

OUTPUT:
Enter the values of a,b,c :: 1 2
3
ROOTS ARE IMAGINARY

N.VENKATASIVA REDDY GCET, KADAPA Page 50 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 6: Write a program to compute the factorial of a given number.
AIM: Programs that use recursive function to find the factorial of a given integer.

Description: Factorial program using recursion in c with while loop.In this program once the
execution reaches the function return statement it will not go back to the function call. Instead,it
executes the function repeatedly. can anybody please tell me what's wrong in this program.

Algorithm :
step 1. Start
step 2. Read the number n
step 3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1
step 7. Print fact
step 8. Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
clrscr( );
printf("Enter any number : ");
scanf("%d", &n);
for(i=1; i<=n; i++)
fact = fact * i;
printf("\nFactorial value of %d = %d",n,fact);
getch( );
}
OUTPUT:
Enter any number : 5
Factorial value of 5 = 120

PROGRAM 7: Write a program to check whether the number is prime or not.


AIM: write a program to check whether the number is prime or not.
Description:
A positive integer which is only divisible by 1 and iself is known as prime number.
A program in the C language can be used to check if an integer is a prime number. Some
knowledge of programming concepts and languages like C is required to write a program code in C.
Basic concepts such as looping, including for loops, while do loops, if else loops, functions, etc, are
necessary to write programs. A program to check if an integer is a prime number in C can be

N.VENKATASIVA REDDY GCET, KADAPA Page 51 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
written by using nested for loops. Nested for loops contain one for loop inside another. Some
knowledge of C functions such as scanf and printf will also prove to be helpful when programming
in C.
Algorithm:
STEP1: Take input from user.
STEP2: Check whether the number has any divisor other than 1 and the number itself.
STEP3: If there is any divisor other than 1 or that number itself, then
STEP3.1:Consider the number as NOT PRIME
STEP3.2: Else consider the number as a PRIME NUMBER.
PROGRAM:

#include<stdio.h>

#include<conio.h>

void main( )

int num,i,count=0;

clrscr( );

printf("Enter a number: ");

scanf("%d",&num);

for(i=2; i<=num/2; i++)

if(num% i==0)

count++; //count=count+1

break;

if(count==0 && num!=1)

printf("%d is a prime number",num);

else

printf("%d is not a prime number",num);

getch( );

}
N.VENKATASIVA REDDY GCET, KADAPA Page 52 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
OUTPUT:
1. Enter a number: 1

1 is not a prime number

2. Enter a number: 5

5 is a prime number

N.VENKATASIVA REDDY GCET, KADAPA Page 53 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

PROGRAM: 8. Write a program to find the series of prime numbers in the given range.

AIM: To print a series of prime numbers in a given range


Description:

Prime number is a number which is exactly divisible by one and itself only. In this program
the range up to which prime numbers are printed is read. Before printing prime numbers, each and
every number between the ranges is checked. If the number is prime ,it is printed otherwise next
number is verified.

Ex: 2, 3,5,7,………;

Algorithm:

Step1: start
Step2: read n value
Step3: for i=1 i<=n
Step4:repeat a b c d e
a)factorial equal to 0
b) for i=1,j<=1 repeat c,d
c)if i percentage j equal to zero
d) fact equal to factorial added with one
e) if factorial equal to2print as prime number
step5: display the prime no till nth num
6: stop
Program:

#include<stdio.h>
#include<conio.h>
void main( )
{
int n,m=1,i,j;
clrscr( );
printf("Enter n value ::");
scanf("%d",&n);
printf("\nThe prime numbers are ::");
for(i=1;i<n;i++)
{
for(j=2;j<i;j++)
{
if(i%j= =0)
m++;
}

N.VENKATASIVA REDDY GCET, KADAPA Page 54 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
if(m= =0)
printf("%2d", i);
m=0;
}
getch( );
}
OUTPUT:
Enter n value :: 8

The prime numbers are :: 2 3 5 7

N.VENKATASIVA REDDY GCET, KADAPA Page 55 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 9: Write a program to generate Fibonacci numbers in the given range.
AIM: Write a program to generate Fibonacci numbers in the given range. To print the Fibonacci
series for 1 to n value
Description: A series of numbers in which each sequent number is sum of its two previous numbers
is known as Fibonacci series and each numbers are called Fibonacci numbers

A fibonacci series is defined as follows

The first term in the sequence is 0

The second term in the sequence is 1

The sub sequent terms 1 found by adding the preceding two terms in the sequence

Formula: let t1,t2,…………tn be terms in fibinacci sequence

t1=0, t2=1

tn=tn-2+tn-1……where n>2

Algorithm:

Step1: start

Step2: read I,x,f,f1,f2

Step3: f=0,f1=1,f2=1

Step4: do

I++

F1=f2

F2=f

F=f1+f2

While (i<=n)

Step5: print f

Step6: stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c,n,i;
clrscr( );
a=0;
N.VENKATASIVA REDDY GCET, KADAPA Page 56 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
b=1;
printf("Enter n value ::");
scanf("%d",&n);
printf("%d\t%d\t",a,b);
i=2;
while(i<n)
{
c=a+b;
printf("%d\t",c);
a=b;
b=c;
i=i+1;
}
getch( );
}
OUTPUT:
Enter n value ::6
0 1 1 2 3 5

N.VENKATASIVA REDDY GCET, KADAPA Page 57 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
E XPERIMENT 10: Write a program to find the maximum of set of numbers
Aim: write a program to find the maximum of set of numbers
Description: As a number are to be consider all these elements are read into an array and then the
biggest or maximum. Then this maximum is compared with elements starting from the second
location i.e., starting from the second location a[1],a[2],----a[n-1] one by one. At end value of
biggest element will be available in maximum.
Algorithm:
step1 : start
step 2: read I,a[i],big
step 3: for(i=0;i<10;i++)
step 4:big=a[i]
step 5: for(i=0;i<10;i++)
step 6: if(big<a[i])
step 7: big=a[i];
step 8: stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max;
clrscr( );
printf("Enter the array size ::");
scanf("%d",&n);
printf("Enter the elements of array ::");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
printf("Maximum value is:%d\n",max);
getch( );
}
OUTPUT:
Enter the array size ::5
Enter the elements of array ::52
84
15
69
24
Maximum value is:84

N.VENKATASIVA REDDY GCET, KADAPA Page 58 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 11: Write a program to reverse the digits of a number.
AIM :Write a program to reverse the digit of a given integer.
Description:This program reverse the number entered by the user and then prints the reversed
number on the screen. For example if user enter 123 as input then 321 is printed as output. In our
program we use modulus(%) operator to obtain the digits of a number. To invert number look at it
and write it from opposite direction or the output of code is a number obtained by writing original
number from right to left.

Algorithm:
step1 : start
step 2: read num,r
step 3: while(num>0)
step 4: r=num%10;
step 5: reverse=reverse*10+r;
step 6: num=num/10;
step 7: stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int r,reverse,n;
clrscr( );
printf("Enter a positive integer:");
scanf("%d",&n);
reverse=0;
while(n>0)
{
r=n%10;
reverse=reverse*10+r;
n=n/10;
}
printf("The reverse of the given number is %d",reverse);
getch();
}
OUTPUT:
Enter a positive integer:563
The reverse of the given number is 365
PROGRAM 12. Write a program to find the sum of the digits of a number.
Aim: To find the sum of individual digits of a given number
Description:

In this ,initially sum is assigned to zero using a while loop this number is divided into individual
digits. for each iteration of while loop atleast significant digit of the positive integer are added to
sum using the following statements,

sum-sum+n%10;

N.VENKATASIVA REDDY GCET, KADAPA Page 59 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
n=n/10;

Ex: 123 sum of digits is 1+2+3=6

Algorithm:

Step 1: start

Step 2: sum0

Step 3: read a positive integer,’num’

Step 4: while num>0 goto step 5 otherwise goto step7

Step 5: sumsum+num%10;

Step 6: numnum/10;

Step 7: print sum of individual digits,’sum’

Step 8:stop

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum;
clrscr();
sum=0;
printf("Enter a positive integer:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("Sum of individual digits of a number=%d",sum);
getch();
}
OUTPUT:
Enter a positive integer:563
Sum of individual digits of a number=14

N.VENKATASIVA REDDY GCET, KADAPA Page 60 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
EXPERIEMT 13: write program to find the sum of positive and negative numbers in the
given set of numbers
Aim: write program to find the sum of positive and negative numbers in the given set of numbers
Description: After programming as an array are read in starting from the first element each element
is taken one by one tested to determine positive and negative. All positive numbers numbers are
added to a variable.
Algorithm:
Step1: start
Step2: read sum=0,total=0,a[i],i
Step3: for(i=0;i<10;i++0
Step4: sum=sum+a[i]
Step5: if(a[i]<0)
Step6: else
step7: total=total+a[i]
Step8: stop
PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,nsum,psum;
int a[10]={2, -4, 8, 9, -12, 7, -1, 9};
clrscr( );
nsum=psum=0;
for(i=0;i<10; i++)
{
if(a[i]<0)
{
nsum=nsum+a[i];
}
else
{
psum=psum+a[i];
}
}
printf("\n Sum of Negative numbers in the list : %d",nsum);
printf("\n Sum of Positive numbers in the list : %d",psum);
getch();
}
OUTPUT:
Sum of Negative numbers in the list : -17
Sum of Positive numbers in the list : 35

N.VENKATASIVA REDDY GCET, KADAPA Page 61 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 14: Write a program to check for given number palindrome.
AIM: To check whether the string is palindrome or not
Description: String is group of characters where character may a number,alphabet or special
symbol.A palindrome string means A string should be alike even though if it is reversed.here
standard library functions are used to perform the given task and we include string.h header file to
use those functions.
Algorithm:

Step 1 :start
Step 2:Read string s1
Step 3:copy the contents of s1 to s2
Step 4:Reverse the string s2
Step 5:if strcmp (s1,s2)==0
Step 6: print string s1 is a palindrome
Step 7:else
Step 8:print string s1 is not a palindrome
Step 9:end of if in step 5
Step 10:Stop

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int r,rev,n,temp;
clrscr( );
printf("Enter a positive integer:");
scanf("%d",&n);
rev=0;
temp=n;
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
if(rev= =temp)
printf("Given number is palindrome");
else
printf("Given number is not palindrome");
getch( );
}
OUTPUT:
Enter a positive integer: 1221
Given number is palindrome

N.VENKATASIVA REDDY GCET, KADAPA Page 62 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

PROGRAM 15: Write a program to evaluate the sum of the following series up to ‘n’ terms e
x=1+x+x2/2!+x3/3!+x4/4!+--------
AIM: To evaluate the sum of the following series up to n terms e x=1+X+X2/2!+X3/3!+X4/4!
+------------
Description:The series contains the factorial and powers.we use math.h header file to calculate the
powers.Here the powers follow the sequence 2,4,6… Using appropriate loops we will calculate the
given sum of the series.
Algorithm:

Step 1 :start
Step 2:Read exponential (y) and base values(x) , assign s<-1,sum=0.0
Step 3:for i=0 upto exponent value (y) increment i by 2
Step 4:fact=1
Step 5:for j=i upto j!=0 decrement by 1
Step 6:fact*=j
Step 7:end of for loop in step5
Step 8:sum=sum+s*pow(x,i)/fact
Step 9: s=-s
End of for loop in step 3
Step 10:print sum
Step 11:stop
Program:
#include<stdio.h>
#include<math.h>
void main()
{
int i=0,j,n,x,fact;
float term=0.0,sum=1.0;
clrscr( );
printf("Enter x value ::");
scanf("%d",&x);
printf("Enter number of terms ::");
scanf("%d",&n);
for(i=1;i<n;i++)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
term=pow(x,i);
sum=sum+(term/fact);
}
printf("\nsum of series = %f",sum);
getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 63 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}
OUTPUT:
Enter x value ::2
Enter number of terms ::4
sum of series = 6.333333

N.VENKATASIVA REDDY GCET, KADAPA Page 64 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 16: Write a program to generate Pascal Triangle.
AIM: To Generate a PASCAL TRIANGLE

Description:In pascal’s trianglenumbersare formed as triangle.At the top 1 will be there.Each


number is formed by adding preceeding and succeeding number in the above row.We need to enter
the number of rows to bedisplayed

Alogrithm:

Step 1: Start

Step 2: Initialize m=0

Step 3: Read n

Step 4: If m<n goto step 5.if not goto step 12

Step 5: initialize i=40-m

Step 6: If i>0 is true do as follows. If not goto step 7

i. print white space


ii. decrement i
iii. goto Step 6
Step 7: Initialize j=0

Step 8: If j=m do as follows. If not goto Step 10

i) if(j==0||m==0)
ii) Initialize b=1 if not b=b*(m-j+1)/j
iii) Print white space, b .
iv) Goto Step 9
Step 9: increment j, goto Step 8

Step 10: print new line control

Step 11: increment m, goto step 4

Step 12: Stop

N.VENKATASIVA REDDY GCET, KADAPA Page 65 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Program:
#include<stdio.h>
void main( )
{
int i,j,k,n,bn=1;
clrscr( );
printf("Enter n value ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(k=0;k<=n-i;k++)
{
printf(" ");
}
for(j=0;j<=i;j++)
{
if(i= =0||j= =0)
bn=1;
else
bn=(bn*(i-j+1))/j;
printf("%2d",bn);
}
printf("\n");
}
getch( );
}
OUTPUT:
Enter n value ::5
1
11

121

1331

14641

N.VENKATASIVA REDDY GCET, KADAPA Page 66 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 17. Write a program to read two matrices and print their sum and product in the
matrix form

Aim: To Write a program to read two matrices and print their sum and product in the matrix form

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,k,row1,col1,row2,col2;
int mat1[10][10],mat2[10][10],prodmat[10][10],matsum[10][10];
clrscr();
printf("enter the order of matrix1\n");
scanf("%d%d",&row1,&col1);
printf("enter the order of matrix2\n");
scanf("%d%d",&row2,&col2);
if(col1= =row2)
{
printf("enter the elements of matrix1\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("enter the elements of matrix2\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
prodmat[i][j]=0;
for(k=0;k<row2;k++)
{
prodmat[i][j]=prodmat[i][j]+(mat1[i][k]*mat2[k][j]);
}
}
}

N.VENKATASIVA REDDY GCET, KADAPA Page 67 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
//FOR PRODUCT OF 2 MATRICES
printf("product matrix is...\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("%3d",prodmat[i][j]);
}
printf("\n");
}
}
else
{
printf("multiplication is not possible...\n");
}
//FOR SUM OF 2 MATRICES
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
matsum[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("\nsum matrix is...\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
printf("%3d",matsum[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT:
enter the order of matrix1
2
3
enter the order of matrix2
3
2
enter the elements of matrix1
5
6
8
4
N.VENKATASIVA REDDY GCET, KADAPA Page 68 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
7
1
enter the elements of matrix2
2
5
3
6
5
4
product matrix is...
68 93
34 66

sum matrix is...

7 11 8

7 13 1

N.VENKATASIVA REDDY GCET, KADAPA Page 69 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
PROGRAM 18. Write a program to read matrix and perform the following operations.
i. Find the sum of Diagonal Elements of a matrix.
ii. Print Transpose of a matrix.
iii. Print sum of even and odd numbers in a given matrix
Aim: To read matrix and perform the following opearations.
i. Find the sum of the diagonal elements of a matrix
ii. Print the transpose of a matrix
iii. Print sum of even and odd numbers in a given matrix

Description: By the definition trace of matrix is given by the sum of all the elements on its
principle diagonal obviously the matrix has to be a square matrix
trace=a00+a11+a22+-------+an-1
. n-1
. . trace=∑ a11, statement is used to obtain the sum
i+0
i. Sum of diagonal elements of a matrix in c

Algorithm:
Step 1: start
step 2: input m and n dimensions of matrix
step 3: if(m!=n)
step 4: input all the elements of matrix
step 5: trace=0
step 6: for(i=0;i<n;i++)
step 7: trace=trace+a;
step 8: output trace
step 9: stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j,m,n;
int mat[10][10],sumdiag=0;
clrscr();
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
if(m==n)
{
printf("Enter the elements of matrix ::\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<m;i++)
{

N.VENKATASIVA REDDY GCET, KADAPA Page 70 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
for(j=0;j<n;j++)
{
if(i==j)
sumdiag=sumdiag+mat[i][j];
}
}
printf("\nThe sum of Diagonal Elements of a matrix is %d",sumdiag);
}
else
{
printf("\nYou cann't sum for this order of a matix");
}
getch( );
}
OUTPUT:
Enter the order of matrix

Enter the elements of matrix ::

The sum of Diagonal Elements of a matrix is 9

N.VENKATASIVA REDDY GCET, KADAPA Page 71 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

ii .AIM: Print the transpose of a matrix


Description: Let A be the given matrix of size mXn,B be the transpose of the given matrix.
The transpose of matrix is obtained by the interchanging its row elements and column elements.
Algorithm:
Step1: start
step2: input the values of m and n
step 3: input the matrix A
step 4: for(i=0;i<n;i++)
step 5: for(j=o;j<m;j++)
step 6: b[i][j]=a[i][j]
step 7: output value,b // transpose matrix
step 8: Stop

Program:
#include<stdio.h>

#include<conio.h>

void main( )

int i,j,row,col;

int mat[10][10];

clrscr( );

printf("Enter the order of matrix ::");

scanf("%d%d",&row,&col);

printf("Enter the elements of matrix ::\n");

for(i=0;i<row;i++)

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

scanf("%d",&mat[i][j]);

printf("\nMatrix before Transpose ::\n");

for(i=0;i<row;i++)

N.VENKATASIVA REDDY GCET, KADAPA Page 72 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{

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

printf("%3d",mat[i][j]);

printf("\n");

printf("\nMatrix after Transpose ::\n");

for(i=0;i<col;i++)

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

printf("%3d",mat[j][i]);

printf("\n");

getch( );

OUTPUT:

Enter the order of matrix ::2


3
Enter the elements of matrix ::
5
6
9
5
8
4

Matrix before Transpose ::


5 6 9
5 8 4

N.VENKATASIVA REDDY GCET, KADAPA Page 73 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Matrix after Transpose ::
5 5
6 8
9 4

iii Print sum of even and odd numbers in a given matrix


C Program to Print the Number of Odd & Even Numbers in an Array
#include<stdio.h>

#include<conio.h>

void main( )

int i,j,m,n;

int mat[10][10],seven,sodd;

clrscr( );

printf("Enter the order of matrix\n");

scanf("%d%d",&m,&n);

printf("Enter the elements of matrix ::\n");

for(i=0;i<m;i++)

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

scanf("%d",&mat[i][j]);

seven=sodd=0;

for(i=0;i<m;i++)

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

if(mat[i][j]%2= =0)

N.VENKATASIVA REDDY GCET, KADAPA Page 74 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
seven=seven+mat[i][j];

else

sodd=sodd+mat[i][j];

printf("\n Sum of even numbers in a given matrix :: %d",seven);

printf("\n Sum of odd numbers in a given matrix :: %d",sodd);

getch();

OUTPUT:

Enter the order of matrix

Enter the elements of matrix ::

Sum of even numbers in a given matrix :: 4

Sum of odd numbers in a given matrix :: 9

PROGRAM 19: Write a program to accept a line of characters and print the count of the
number of Vowels, Consonants, blank spaces, digits and special characters.

N.VENKATASIVA REDDY GCET, KADAPA Page 75 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

Aim: To implement a program to accept a line of characters and print the count of number of
vowels,consonants,blankspaces,digits and special characters
Algorithm:
step1: start
step2: declare str[50],intr=0,c=0,w=0,sc=0,d=0
step3: gets(str)
step4: for(i=0;str[i]==’\0’||str[i]!=’/n’;i++)
step5: if(str[i]=’a’||str[i]=’e’||str[i]=’i’||str[i]=’o’||str[i]=’u’)
step6: v++
step7: else if(str[i]>’a’ && str[i]<=’z’)
step8: c++
step9: else if(str[i]=’0’|| str[i]=’1’|| str[i]=’2’|| str[i]=’3’|| str[i]=’4’|| str[i]=’5’|| str[i]=’6’||
str[i]=’7’|| str[i]=’8’|| str[i]=’9’)
step10: d++
step11: else if(str[i]==’ ‘||str[i]=’/t’)
step12: w++;
step13: else
step14: sc++
step15: print the vowels
step16: print the consonants
step17: print the digits
step18: print the special characters
step19: print the words
step20: print the number of characters

Program:
#include<stdio.h>

void main( )

char line[150];

int i,v,c,d,spc,s;

clrscr( );

v=c=d=spc=s=0;

printf("Enter a line of string: ");

gets(line);

for(i=0;line[i]!='\0';++i)

{
N.VENKATASIVA REDDY GCET, KADAPA Page 76 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E'
||

line[i]=='I' || line[i]=='O' || line[i]=='U')

++v;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))

++c;

else if(line[i]>='0'&&line[i]<='9')

++d;

else if (line[i]==' ')

++spc;

else

++s;

printf("\nVowels: %d",v);

printf("\n\nConsonants: %d",c);

printf("\n\nDigits: %d",d);

printf("\n\nWhite spaces: %d",spc);

printf("\n\nSpecial Characters : %d",s);

getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 77 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}

OUTPUT:

Enter a line of string: hi hel6lo i am?*

Vowels: 5

Consonants: 5

Digits: 1

White spaces: 3

Special Characters : 2

PROGRAM 20: Write a program to insert a substring in to a given string and delete few
characters from the string. Don’t use library functions related to strings

Aim: A C program to insert a sub string into the main string from a given position.
Description: String is group of characters where character may a number, alphabet or special
symbol.
Here two strings are considered first one is main and second one is substring.sub string is
inserted into main string from a particular position and the resultant string is displayed.
ALGORITHM:
Step 1 :start
Step 2:Read main string m
Step 3:Read sub string sb
Step 4:Read the position to be inserted p-
Step 5:for i=0 upto p increment i by 1
Step 6:x[i]=m[i]
Step 7:end of for loop in step 5
Step 8:for i=pand j=0 upto sb[j]!=’\0’ increment i,j by 1
Step 9:x[i]=sb[j]
Step 10:end of for loop in step 8
Step 11:x[i]=’\0’
Step 12:l=strlen(x)
Step 13:for i=l and j=p upto m[j]!=’\0’ increment i ,j by 1
Step 14:x[i]=m[j]
Step 15:end of for loop in step 13
Step 16:x[i]=’\0’
Step 17:Print resultant string x
Step 18:Stop

PROGRAM:
#include <stdio.h>
N.VENKATASIVA REDDY GCET, KADAPA Page 78 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
#include <conio.h>

#include <string.h>

void main()

char a[20], b[20], c[50];

int p,r,i=0;

int t=0;

int x,g,s,n,z;

clrscr( );

puts("Enter First String:");

gets(a);

puts("Enter Second String:");

gets(b);

printf("Enter the position where the item has to be inserted: ");

scanf("%d",&p);

r = strlen(a);

n = strlen(b);

i=0;

/* Copying the input string into another array*/

while(i <= r)

c[i]=a[i];

i++;

s = n+r;

z = p+n;

/* Adding the sub-string*/

for(i=p;i<s;i++)

N.VENKATASIVA REDDY GCET, KADAPA Page 79 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{

x = c[i];

if(t<n)

a[i] = b[t];

t=t+1;

a[z]=x;

z=z+1;

printf("String after insertion : %s", a);

getch( );

OUTPUT:

Enter First String:

hiiam

Enter Second String:

fine

Enter the position where the item has to be inserted: 2

String after insertion : hifineiam

N.VENKATASIVA REDDY GCET, KADAPA Page 80 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

20(b)Write a program to delete few characters from the string (Don’t use library functions
related to strings)

Aim: To Write a program to delete few characters from the string (Don’t use library functions
related to strings)

Program:

#include<stdio.h>

#include<conio.h>

void main( )

char str[15];

int pos,i,j,n;

clrscr();

printf("Enter string:\n");

gets(str);

printf("Enter position in string from where to delete ::");

scanf("%d", &pos);

printf("Enter no of char to be deleted ::");

scanf("%d",&n);

i=pos;

for(j=pos+n;str[j]!='\0';j++)

str[i]=str[j];

i++;

N.VENKATASIVA REDDY GCET, KADAPA Page 81 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
str[i]='\0';

printf("\n string after deletion:: %s",str);

getch( );

OUTPUT:

Enter string:

hi aec students

Enter position in string from where to delete:: 3

Enter no of char to be deleted:: 4

string after deletion :: hi students

PROGRAM 21: write a program to perform the operations addition, subtraction,


multiplication of complex numbers
Aim: A C program to perform arithmetic operations on two complex numbers.
Description: Complex number takes the form a+ib where i2=-1.General arithmetic operations are
addition, subtraction ,multiplication. These are performed on two complex numbers.Here complex
number is represented using structure.
Algorithm:
Algorithm for main function:
Step 1 :start
Step 2:Declare structure
Step 3:struct complex x,y
Step 4:Read first complex number x.real,x.img
Step 5:Read second complex number y.real,y.img
Step 6:Print 1.print 2.addition 3.subtraction 4.multiplication 5.division
Step 7:Read ch
Step 8:switch(ch)
Step 9: case 1:call function cmpprint(x.real.x.img,y.rea,y.img)
Step 10: case 2:call function cmpadd(x.real.x.img,y.rea,y.img)
Step 11: case 3:call function cmpsub (x.real.x.img,y.rea,y.img)
Step 12: case 4:call function cmpmul(x.real.x.img,y.rea,y.img)
Step 13: case 5 :call function cmpdiv(x.real.x.img,y.rea,y.img)
Step 14:end of switch
Step 15:Stop

Algorithm for subfunction cmpprint(float a,float b,float c,float d)


Step 1 :start
Step 2:Print first complex number a,b
Step 3:Print second complex number c,d

N.VENKATASIVA REDDY GCET, KADAPA Page 82 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Step 4:Stop
Algorithm for subfunction cmpadd(float a,float b,float c,float d)
Step 1 :start
Step 2:Print addition of complex numbers (a+c),(b+d)
Step 3:Stop
Algorithm for subfunction cmpsub(float a,float b,float c,float d)
Step 1 :start
Step 2:Print subtraction of complex numbers (a-c),(b-d)
Step 3:Stop
Algorithm for subfunction cmpmul(float a,float b,float c,float d)
Step 1 :start
Step 2:Print multiplication of complex numbers (a*c-b*d),(a*d+b*c)
Step 3:Stop
PROGRAM:
#include<stdio.h>

#include<conio.h>

struct complex

double real;

double img;

};

void main()

int ch;

struct complex cn,cn1,cn2;

clrscr( );

printf("\n Enter two Complex Numbers (x+iy):\n Real Part of First Number:");

scanf("%lf",&cn1.real);

printf("\n Imaginary Part of First Number:");

scanf("%lf",&cn1.img);

printf("\n Real Part of Second Number:");

scanf("%lf",&cn2.real);

printf("\n Imaginary Part of Second Number:");

scanf("%lf",&cn2.img);
N.VENKATASIVA REDDY GCET, KADAPA Page 83 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf(" Select your option:\n\n1 : ADD\n2 : SUBTRACTION \n3 : MULTIPLY\n4 :
Exit\n\n");

printf("enter ur choice:");

scanf("%d",&ch);

switch(ch)

case 1:

cn.real =(cn1.real+cn2.real);

cn.img =(cn1.img+cn2.img);

if(cn.img>0)

printf("\n addition = %lf+%lfi",cn.real,cn.img);

else

printf("\n addition = %lf%lfi",cn.real,cn.img);

break;

case 2:

cn.real =(cn1.real-cn2.real);

cn.img =(cn1.img-cn2.img);

if(cn.img>0)

printf("\n Subtraction = %lf+%lfi",cn.real,cn.img);

else

printf("\n Subtraction = %lf%lfi",cn.real,cn.img);

break;

case 3:

cn.real=(cn1.real*cn2.real)-(cn1.img*cn2.img);

cn.img=(cn1.real*cn2.img)+(cn1.img*cn2.real);

if(cn.img>0)

printf("\nmultiplication = %lf+%lfi",cn.real,cn.img);
N.VENKATASIVA REDDY GCET, KADAPA Page 84 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
else

printf("\nmultiplication = %lf%lfi",cn.real,cn.img);

break;

default:

printf("Invalid option");

getch( );

OUTPUT:

Enter two Complex Numbers (x+iy):

Real Part of First Number:8

Imaginary Part of First Number:5

Real Part of Second Number:7

Imaginary Part of Second Number:4

Select your option:

1 : ADD

2 : SUBTRACTION

3 : MULTIPLY

4 : Exit

enter ur choice:1

addition = 15.000000+9.000000i

Task 22:
Write a program to split a file into Two files, say File1 And File2.Read Lines into the file from
standard input.File1 should consist of odd numbered lines and file2 should consists of even
numbered lines .
Program:
#include<stdio.h>

#include<conio.h>

N.VENKATASIVA REDDY GCET, KADAPA Page 85 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
void main()

FILE *fp1,*fp2,*fp3;

char c;

clrscr( );

fp1=fopen("file.txt","r");

fp2=fopen("file1.txt","w");

fp3=fopen("file2.txt","w");

while((c=fgetc(fp1))!=EOF)

while(c!='\n')

fputc(c,fp2);

c=fgetc(fp1);

c=fgetc(fp1);

while(c!='\n')

fputc(c,fp3);

c=fgetc(fp1);

OUTPUT:

Before executing a this program do the following:

Step 1:

Create a file called file.txt with content

1:hi hello hru?

N.VENKATASIVA REDDY GCET, KADAPA Page 86 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
2:fine

3:what abt. u?

4:me also fine

5:good bye

6:ok bye

Step 2:

Compile and run(execute) this C-program then it automatically creates 2 files called file1.txt
and file2.txt

has an ouput shown below

Output:

file1.txt file2.txt

1:hi hello hru? 3:what abt. u? 5:good bye 2:fine 4:me also fine 6:ok bye

Task 23:
Write a program to merge two files
Aim: Write a program to merge two files
#include<stdio.h>

main()

FILE *fp1,*fp2,*fp3;

char c;

clrscr();

fp1=fopen("1.txt","r");

fp2=fopen("2.txt","r");

fp3=fopen("3.txt","a");

if(fp1==NULL||fp2==NULL)

printf("File cannot be opened");

exit( );

N.VENKATASIVA REDDY GCET, KADAPA Page 87 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}

c=fgetc(fp1);

while(c!=EOF)

fputc(c,fp3);

c=fgetc(fp1);

c=fgetc(fp2);

while(c!=EOF)

fputc(c,fp3);

c=fgetc(fp2);

fcloseall( );

OUTPUT:

Procedure before see the output

Step: 1Create a file called 1.txt has

hi

Step: 2Create another file called 2.txt has

students

Step:3 ->Compile and execute this program then it automatically creates a file called 3.txt that
it has

hi students

Task 24:

write a program to implement numerical methods Lagrange’s interpolation, Trapezoidal rule.

N.VENKATASIVA REDDY GCET, KADAPA Page 88 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Aim: write a program to implement numerical methods Lagrange’s interpolation, Trapezoidal
rule.

Output 1:

Enter an expression: 1/x


Enter x0, xn and number of subintervals
0.5 1 5
Value of the integral is 0.696

Output 2:

Enter an expression: x
Enter x0, xn and number of subintervals
016
Value of the integral is 0.500
24(b) Write a program to implement numerical methods Lagrange’s interpolation.

Aim: To Write a program to implement numerical methods Lagrange’s interpolation.

lagrange’s trapezoidal rule


#include<stdio.h>

#include<conio.h>

#define MaxN 90

void main( )

float arr_x[MaxN+1], arr_y[MaxN+1], numerator, denominator, x, y=0;

int i, j, n;

clrscr();

printf("Enter the value of n: \n");

scanf("%d", &n);

printf("Enter the values of x and y: \n");

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

scanf("%f%f", &arr_x[i], &arr_y[i]);

printf("Enter the value of x at which value of y is to be calculated: ");

scanf("%f", &x);

N.VENKATASIVA REDDY GCET, KADAPA Page 89 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
for (i=0; i<=n; i++)

numerator=1;

denominator=1;

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

if(j!=i)

numerator *= x-arr_x[j];

denominator *= arr_x[i]-arr_x[j];

y+=(numerator/denominator)*arr_y[i];

printf("When x=%4.1f y=%7.1f\n",x,y);

getch( );

OUTPUT:

Enter the value of n:


3
Enter the values of x and y:
300 2.4771
304 2.4829
305 2.4843
306 2.4945
Enter the value of x at which value of y is to be calculated: 307
When x=307.0 y= 2.5

PROGRAM 25: Write a program to read a set of strings and sort them in alphabetical order
AIM: Program to read five cities and sort them and print sorted list of citied in alphabetical
order
ALGORITHM:
step1:start
Step2:enter 5 city names
Step3:take I and j loop variables

N.VENKATASIVA REDDY GCET, KADAPA Page 90 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
For(i=65;i<122;i++)
{
for(j=0;j<5;j++)
{
if(city[j][0]==i)
printf(”\n%s”,city[j]);
}
}
Step4:stop
PROGRAM:
#include<stdio.h>

#include<string.h>

void main()

char s[5][20],t[20];

int i,j,n;

clrscr( );

printf("Enter number of strings ::");

scanf("%d",&n);

printf("Enter any strings ::\n");

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

scanf("%s",s[i]);

for(i=1;i<n;i++)

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

if(strcmp(s[j-1],s[j])>0)

strcpy(t,s[j-1]);
N.VENKATASIVA REDDY GCET, KADAPA Page 91 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
strcpy(s[j-1],s[j]);

strcpy(s[j],t);

printf("Strings in sorted order are : ");

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

printf("\n%s",s[i]);

getch( );

OUTPUT:

Task 31: Write a program to read two strings and perform the following operations without
using built in string Library functions and by using your own implementation of functions.
1 String Length Determination
2 Compare two Strings
3. Concatenate them, if they are not equal
4. String Reverse
Program
#include<stdio.h>

#include<conio.h>

int slength(char [ ]);

int scompare(char [ ],char [ ]);

void sconcate(char [ ],char [ ]);

void sreverse(char [ ]);

char s1[10],s2[10];

void main()

int ch,l;

clrscr( );

N.VENKATASIVA REDDY GCET, KADAPA Page 92 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf("Enter a String 1 ::");

gets(s1);

printf("\nEnter a String 2 ::");

gets(s2);

printf("\n \n1.String length determination\n2.Compare 2 Strings\n3.Concatenate Strings, if they are


not equal\n4.String reversing\n\nEnter UR choice ::");

scanf("%d",&ch);

switch(ch)

case 1: l=slength(s1);

printf("\nFirst String length is ::%d",l);

l=slength(s2);

printf("\nSecond String length is ::%d",l);

break;

case 2:

scompare(s1,s2);

break;

case 3:

sconcate(s1,s2);

break;

case 4:

printf("The Reversed String 1 is ::");

sreverse(s1);

printf("\nThe Reversed String 2 is ::");

sreverse(s2);

break;

default:

printf("\nWrong entry");

getch( );
N.VENKATASIVA REDDY GCET, KADAPA Page 93 of 84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
exit();

getch( );

int slength(char s1[])

int i;

for(i=0;s1[i]!='\0';i++);

return i;

void sreverse(char s1[])

char s2[10];

int i,j,len;

len=slength(s1);

for(i=len-1,j=0;i>=0;i--,j++)

s2[j]=s1[i];

s2[j]='\0';

puts(s2);

int scompare(char s1[],char s2[])

int i,j,l,m,s=0;

N.VENKATASIVA REDDY GCET, KADAPA Page 94 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
l=slength(s1);

m=slength(s2);

if(l!=m)

printf("\nTwo strings are not equal\n");

return 1;

else

for(i=0,j=0;i<l&&j<m;i++,j++)

if(s1[i]!=s2[j])

s=1;

if(s= =1)

printf("\nString s1 and s2 are not equal");

break;

else

continue;

if(s= =0)

printf("\nString s1 is equal to string s2");

return 0;

N.VENKATASIVA REDDY GCET, KADAPA Page 95 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

void sconcate(char s1[],char s2[])

int i,j,l,m;

if(scompare(s1,s2)==1)

l=slength(s1);

m=slength(s2);

for(i=l,j=0;j<m;i++,j++)

s1[i]=s2[j];

s1[i]='\0';

printf("\nThe resultant concatenated string is :: %s",s1);

Output 1:
Enter a String 1 ::aec

Enter a String 2 ::college

1.String length determination


2.Compare 2 Strings
3.Concatenate Strings, if they are not equal
4.String reversing

Enter UR choice :: 3

Two strings are not equal

The resultant concatenated string is :: aeccollege

Output 2:

Enter a String 1 ::aec

Enter a String 2 ::college

N.VENKATASIVA REDDY GCET, KADAPA Page 96 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

1.String length determination


2.Compare 2 Strings
3.Concatenate Strings, if they are not equal
4.String reversing

Enter UR choice ::2

Two strings are not equal


Output 3:
Enter a String 1 ::aec

Enter a String 2 ::college

1.String length determination


2.Compare 2 Strings
3.Concatenate Strings, if they are not equal
4.String reversing

Enter UR choice ::4


The Reversed String 1 is ::cea

The Reversed String 2 is ::egelloc


Output 4:
Enter a String 1 ::aec

Enter a String 2 ::college


1.String length determination
2.Compare 2 Strings
3.Concatenate Strings, if they are not equal
4.String reversing

Enter UR choice ::1

First String length is ::3


Second String length is ::7

N.VENKATASIVA REDDY GCET, KADAPA Page 97 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Task 32: write programs using recursion for factorial of a number, GCD, LCM, Towers of
Hanoi.
i. Programs that use recursive function to find the factorial of a given integer.
Description:
A function that calls itself is called recursive function else it may be called as non recursion
function.Here we ud value for finding the factorial.Here we call recursion and non Recursion
functions.Here we used switch statement for selecting recursion
Algorithm: main program
Step 1: start
Step 2: read n
Step 3: call sub program as f=fact(n)
Step 4: print f value
Step 5: stop
Sub program:
Step 1: initialize the f
Step 2: if n= = 0 or n == 1 return 1 to main program if not goto step 3
Step 3: return n*fact(n-1) to main program

Program:
#include<stdio.h>

#include<conio.h>

void main()

int n;

long int f1;

long int recfactorial(int);

clrscr( );

printf("Enter n number :");

scanf("%d",&n);

f1=recfactorial(n);

printf("\nFactorial of a given number using Recursion is : %ld",f1);

getch( );

long int recfactorial(int n)

if(n==0)

return 1;

N.VENKATASIVA REDDY GCET, KADAPA Page 98 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
else

return (n*recfactorial(n-1));

Enter n number :5

Factorial of a given number using Recursion is : 120

ii. To find the GCD (greatest common divisor) of two given integers using recursive function.
Description: Let x and y be two numbers. GCD (Greatest Common Divisor) of x and y is the
largest integer that divides both the numbers. Let r be the remainder when x is divided by y. if r is 0
then y is gcd. Otherwise set x=y, y=r and repeat the same process.

Algorithm: main program

Step 1: start
Step 2: read a,b
Step 3: call the sub program GCD(a,b) for print the value
Step 4: stop

Sub program:

Step 1: if n>m return GCD(n,m)


Step 2: if n==0 return m else goto step 3
Step 3: return GCD (n,m%n)
Step 4: return to main program

PROGRAM:

#include <stdio.h>

void Lcm_rec(int);

int num1,num2;

main()

int max;

clrscr( );

printf("Enter two positive integers: ");

scanf("%d %d", &num1, &num2);

N.VENKATASIVA REDDY GCET, KADAPA Page 99 of 84


Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
max=(num1>num2) ? num1 : num2;

Lcm_rec(max);

getch();

void Lcm_rec(int max)

if(max%num1= =0 && max%num2= =0)

printf("LCM of %d and %d is %d",num1,num2,max);

return;

else

Lcm_rec(max+1); //This is recursive Function Call

Enter two positive integers: 5 9

LCM of 5 and 9 is 45

iii. To find the LCM of two given integers using recursive function.
#include<stdio.h>
int main()
{
int n1,n2,temp1,temp2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
temp1=n1;
temp2=n2;
while(temp1!=temp2)
{
if(temp1>temp2)
temp1-=temp2;
else
temp2-=temp1;
}
printf("LCM of two numbers %d and %d is %d", n1, n2, (n1*n2)/temp1);
return 0;
N.VENKATASIVA REDDY GCET, KADAPA Page 100 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
}
Output:

Enter two positive numbers: 15


9
LCM of two numbers 15 and 9 is 45

32(iii) AIM: Write programs using recursion for GCD of Numbers.


Program:

#include<stdio.h>

#include<conio.h>

void main()

int m,n,g;

int recgcd(int,int);

clrscr();

printf("Enter 2 values:");

scanf("%d%d",&m,&n);

g=recgcd(m,n);

printf("\n GCD of 2 numbers using recursion :: %d",g);

getch();

/*Recursive function of GCD*/

int recgcd(int m,int n)

if(n= =0)

return m;

else

return recgcd(n, m%n);

N.VENKATASIVA REDDY GCET, KADAPA Page 101 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Enter 2 values:4 5

GCD of 2 numbers using recursion :: 1

N.VENKATASIVA REDDY GCET, KADAPA Page 102 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
iv. To solve the towers of Hanoi problem by using the recursive function
Description
Towers of Hanoi problem means we have three towers

Source intermediate destination

Here source ,intermediate and destination are the three towers. We have to transfer all
the disks from source to destination towers. Here the restriction is not to place a big disk on
smaller one . for this we use intermediate tower. Finally the arrangements in the destination
tower must be as same as the disks in the source tower at first.

Algorithm: main program


Step 1: start
Step 2: initialize the source=a, intermediate=c, destination = d
Step 3: read n
Step 4: call the sub program Hanoi recursion (n value,a ,b, c)
Step 5: stop
Sub program:
Step 1: if n== 1 call the sub program Hanoi recursion (num-1, a, c, b)
Step 2: print the output from a to b
Step 3: call the sub program Hanoi recursion(num-1, b, c, a)
Step 4: return to main program
Source intermediate destination 30
Program:
#include<stdio.h>

#include<conio.h>

void main()

void towers(int,char,char,char);

int n;

clrscr();

printf("Enter the no. of disk to be transferred:");

N.VENKATASIVA REDDY GCET, KADAPA Page 103 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
scanf("%d",&n);

towers(n,'A','C','B');

getch();

void towers(int n,char fromtower,char totower,char auxtower)

if(n= =1)

printf("\nMove disk 1 from %c to %c",fromtower,totower);

return;

else

towers(n-1,fromtower,auxtower,totower);

printf("\nMove disc %d from %c to %c",n,fromtower,totower);

towers(n-1,auxtower,totower,fromtower);

return;

OUTPUT:

Enter the no. of disk to be transferred:3

Move disk 1 from A to C

Move disc 2 from A to B

Move disk 1 from C to B

Move disc 3 from A to C

Move disk 1 from B to A

N.VENKATASIVA REDDY GCET, KADAPA Page 104 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Move disc 2 from B to C

Move disk 1 from A to C

PROGRAM 34: Write a program to exchange two numbers using pointers.


Aim: To exchange two numbers by using a pointers.
Description
This program interchange of values of two variable using functions and sending addresses.
Algorithm
Step 1 : start
Step 2 : read a,b
Step 3 : display “before calling function a,b are” a,b
Step 4 : call exchange
Step 5: display “after calling function a,b are “,a,b
Step 6 : stop
Algorithm for exchange :
Step 1 : start
Step 2 : assign t = *x;
Step 3 : assign *x =*y
Step 4 : assign *y = t
Step 5 : display “in the function a,b “ x,y
Step 6: stop
PROGRAM
#include<stdio.h>

void main()

int *a,*b,temp;

clrscr();

printf("Enter 2 Numbers ::");

scanf("%d%d",a,b);

printf("\n Values before Exchange ::");

printf("%d %d",*a,*b);

temp=*a;

*a=*b;

*b=temp;

printf("\n Values after Exchange ::");

N.VENKATASIVA REDDY GCET, KADAPA Page 105 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf("%d %d",*a,*b);

getch();

OUTPUT:

Enter 2 Numbers ::

Values before Exchange ::5 6

Values after Exchange ::6 5

37. Aim: To Write a program to read student records into a file. Record consists of rollno, name and
marks of a student in six subjects and class. Class field is empty initially. Compute the class of a
student. The calculation of the class is as per JNTUA rules. Write the first class, second class, third
class and failed students lists separately to another file.

Program:

#include<stdio.h>

#define NULL 0

struct record

char nam;

int rno;

int s1,s2,s3,s4,s5,s6;

};

void main()

FILE *fp,*fp1;

struct record it;

N.VENKATASIVA REDDY GCET, KADAPA Page 106 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
int n;

fp=fopen("file1.txt","r");

fp1=fopen("file2.txt","w");

if(fp==NULL)

printf("File does not exists");

exit();

else

while(getc(fp)!=EOF)

fscanf(fp,"%c %d %d %d %d %d %d
%d",&it.nam,&it.rno,&it.s1,&it.s2,&it.s3,&it.s4,&it.s5,&it.s6);

n=it.s1+it.s2+it.s3+it.s4+it.s5+it.s6;

n=(n/6);

if(n>70&&n<100)

fprintf(fp1,"distinction");

else if(n>60&&n<70)

fprintf(fp1,"first class");

else if(n>50&&n<60)

fprintf(fp1,"second class");

else if(n>40&&n<50)

fprintf(fp1,"third class");

else

fprintf(fp1,"fail");

N.VENKATASIVA REDDY GCET, KADAPA Page 107 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

fcloseall();

Output :

Content in file1.txt

a 409 60 65 67 79 94 96

 Output content in file2.txt

distinction

38. Aim:A file consists of information about employee salary with fields employeeid, name, Basic,
HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employeeid, name, and basic
have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is 20% of the
basic, other deductions is user specified. Compute the Gross and Net salary of the employee and
update the file.

Program:

#include<stdio.h>

#include<conio.h>

struct employee

int id;

char name[22];

double bsal;

};

void main()

struct employee emp;

N.VENKATASIVA REDDY GCET, KADAPA Page 108 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
double net_sal,gross_sal,da,hra,it,pf;

FILE *fp;

clrscr();

fp=fopen("sal.txt","r");

fscanf(fp,"%d",&emp.id);

fscanf(fp,"%s",&emp.name);

fscanf(fp,"%u",&emp.bsal);

da=((emp.bsal)*10)/100;

hra=((emp.bsal)*80)/100;

it=((emp.bsal)*20)/100;

pf= ((emp.bsal)*8)/100;

gross_sal=emp.bsal+da+hra;

net_sal=gross_sal-it-pf;

fclose(fp);

fp=fopen("sal.txt","a");

fprintf(fp,"\nEmployee Details");

fprintf(fp,"\n****************");

fprintf(fp,"\nID= %d",emp.id);

fprintf(fp,"\nNAME= %s",emp.name);

fprintf(fp,"\nBASIC SALARY= %u",emp.bsal);

fprintf(fp,"\nDA= %u",da);

fprintf(fp,"\nHRA= %u",hra);

fprintf(fp,"\nPF= %u",pf);

fprintf(fp,"\nGROSS SALARY= %u",gross_sal);

fprintf(fp,"\nNET SALARY= %u",net_sal);

fclose(fp);

getch();

}
N.VENKATASIVA REDDY GCET, KADAPA Page 109 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
File sal.txt contains:

4567

RAMESH

5600

Output:

The same file sal.txt updated with:

Employee Details

****************

ID= 4567

NAME= RAMESH

BASIC SALARY= 5600

DA= 17587

HRA= 17587

PF= 40284

GROSS SALARY= 57749

NET SALARY= 20265

Task 39: program to convert decimal to any base(decimal,octal,hexadecimal,etc)*/


#include <stdio.h>

void main(void)

char base_digits[16] =

{'0', '1', '2', '3', '4', '5', '6', '7',

'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

N.VENKATASIVA REDDY GCET, KADAPA Page 110 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
int converted_number[64];

long int number_to_convert;

int next_digit, base, index=0;

/* get the number and base */

printf("Enter number and desired base: ");

scanf("%ld %i", &number_to_convert, &base);

/* convert to the indicated base */

while (number_to_convert != 0)

converted_number[index] = number_to_convert % base;

number_to_convert = number_to_convert / base;

++index;

/* now print the result in reverse order */

--index; /* back up to last entry in the array */

printf("\n\nConverted Number = ");

for( ; index>=0; index--) /* go backward through array */

printf("%c", base_digits[converted_number[index]]);

printf("\n");

getch();

Output:

Enter number and desired base: 263 16


Converted Number = 107
Enter number and desired base: 263 8
Converted Number = 407
Enter number and desired base: 263 10

N.VENKATASIVA REDDY GCET, KADAPA Page 111 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
Converted Number = 263

Task 40:
write a program to find the square root of a number without using built-in library function.
Aim: write a program to find the square root of a number without using built-in library
function
#include<stdio.h>

#define MAX_NUMBER 5000

int find_sqrt(int number)

int i,product = 0;

for(i=0;i<MAX_NUMBER;i++)

product = i*i;

if(product==number)

return i;

else if(product>number)

break;

return 0;

int main( )

int n=0,result=0;

clrscr( );

printf("Enter the number to find the perfect square root ::");

scanf("%d",&n);

if(n<0)

N.VENKATASIVA REDDY GCET, KADAPA Page 112 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf("enter only +ve integer value");

return 0;

result = find_sqrt(n);

if(result)

printf("sqrt of %d is %d\n",n,result);

else

printf("not a proper value for finding the sqrt\n");

getch( );

Output:

Enter the number to find the perfect square root ::25

sqrt of 25 is 5

Task 41:
Write a program to convert from string to number
#include <stdio.h>

int toString(char []);

void main()

char a[100];

int n;

printf("Input a valid string to convert to integer\n");

scanf("%s", a);

n = toString(a);

printf("String = %s\nInteger = %d\n", a, n);

getch();

int toString(char a[ ]) {

N.VENKATASIVA REDDY GCET, KADAPA Page 113 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
int c, sign, offset, n;

if (a[0] == '-') {

sign = -1;

if (sign == -1) {

offset = 1;

else {

offset = 0;

n = 0;

for (c = offset; a[c] != '\0'; c++) {

n = n * 10 + a[c] - '0';

if (sign == -1)

n = -n;

return n;

Output:

Input a valid string to convert to integer: -5632

String = -5632

Integer = -5632

Task 42:

N.VENKATASIVA REDDY GCET, KADAPA Page 114 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
This program generate pseudo random-number generator with the time, then displays 10 random
integers.
Aim: to generate pseudo random generator

Usage of rand( ):

int rand (void);


Parameters:

The function rand( ) returns a pseudo-random integral number.


This number will be in the range 0 to RAND_MAX. The algorithm of rand( ) uses a seed to
generate the series of numbers, this is why srand must be used to initialize the seed to some
distinctive value.
The constant RAND_MAX is defined in standard library (stdlib).
The random numbers are delivered from a predetermined range.
Return value:

Will return an integer value between 0 and RAND_MAX.

Source code example of rand( ):


Program:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void main( )
{
int number, input;
clrscr();
/* initialize random seed: */
srand ( time(NULL) );
/* Generate a random number: */
number = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&input);
if (input>number)
printf ("The number is higher\n");
else
printf("The number is lower\n");
}while (number!=input);
printf ("That is correct!\n");
getch( );
}

Output:

Guess the number (1 to 10): 6

The number is higher

Guess the number (1 to 10): 4


N.VENKATASIVA REDDY GCET, KADAPA Page 115 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
The number is higher

Guess the number (1 to 10): 2

The number is lower

Guess the number (1 to 10): 3

The number is lower

That is correct!

Task 47: write a program to generate multiplication tables from 11 to 20.


Aim: to generate multiplication tables from 11 to 20.
#include<stdio.h>

void main( )

int i,j;

clrscr();

for(i=1;i<=10;i++)

for(j=11;j<=20;j++)

printf("%d*%d=%d",j,i,j*i);

printf("\n");

getch();

Output:
Multiplication table from 11 to 20
11*1=11 12*1=12 13*1=13 14*1=14 15*1=15 16*1=16 17*1=17 18*1=18 19*1=19
20*1=20

11*2=22 12*2=24 13*2=26 14*2=28 15*2=30 16*2=32 17*2=34 18*2=36 19*2=38


20*2=40

N.VENKATASIVA REDDY GCET, KADAPA Page 116 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
11*3=33 12*3=36 13*3=39 14*3=42 15*3=45 16*3=48 17*3=51 18*3=54 19*3=57
20*3=60

11*4=44 12*4=48 13*4=52 14*4=56 15*4=60 16*4=64 17*4=68 18*4=72 19*4=76


20*4=80

11*5=55 12*5=60 13*5=65 14*5=70 15*5=75 16*5=80 17*5=85 18*5=90 19*5=95


20*5=100

11*6=66 12*6=72 13*6=78 14*6=84 15*6=90 16*6=96 17*6=102 18*6=108


19*6=114 20*6=120

11*7=77 12*7=84 13*7=91 14*7=98 15*7=105 16*7=112 17*7=119 18*7=126


19*7=133 20*7=140

11*8=88 12*8=96 13*8=104 14*8=112 15*8=120 16*8=128 17*8=136 18*8=144


19*8=152 20*8=160

11*9=99 12*9=108 13*9=117 14*9=126 15*9=135 16*9=144 17*9=153 18*9=162


19*9=171 20*9=180

11*10=110 12*10=120 13*10=130 14*10=140 15*10=150 16*10=160 17*10=170 18*10=180


19*10=190 20*10=200

Task 48: write a program to express a four digit number in words. For example 1546 should
be written as one thousand five hundred and forty six.

Aim: to express a four digit number in words. For example 1546 should be written as one
thousand five hundred and forty six.

#include<stdio.h>

#include<conio.h>

char a[10][12]={"one","two","three","four","five","six","seven",eight","nine"};

char b[10][15]= {"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",

"eighteen","ninteen"};

char tens[10][15]={twenty","thirty","fourtey","fiftey","sixty","seventy","eighty",

"ninty"};

int check(long int num)

N.VENKATASIVA REDDY GCET, KADAPA Page 117 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{

if(num>10000000)return 5;

if(num>100000)return 4;

else if(num>1000)return 1;

else if(num>100)return 2;

else if(num>10)return 3;

else

return 0;

void prnt(long int num,char *s)

int n;

if(num<10)

printf(" %s %s",a[num-1],s);

else if(num>10 && num<20)

printf(" %s %s",b[(num-10)-1],s);

else if(num>20)

printf(" %s ",tens[(num-20)/10]);

n=num%10;

printf(" %s %s",a[n-1],s);

void main()
N.VENKATASIVA REDDY GCET, KADAPA Page 118 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{

long int num,n;

int ch=1;

clrscr( );

printf("enter no\n");

scanf("%ld",&num);

while( ch!=0)

ch=check(num);

switch(ch)

case 1: n=num/1000;

prnt(n," thousand");

num=num-n*1000;

break;

case 2:

n=num/100;

prnt(n," hundred ");

num=num-n*100;

break;

case 3:

printf(" %s",tens[(num-20)/10]);

num=num%10;

break;

case 4:

n=num/100000;

prnt(n,"lacks");

num=num-n*100000;
N.VENKATASIVA REDDY GCET, KADAPA Page 119 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
break;

case 5:

n=num/10000000;

prnt(n,"crores");

num=num-n*10000000;

break;

printf(" %s",a[num-1]);

getch( );

Output:

enter no: 1526

one thousand five hundred twenty six

49. Aim: Write a program to generate a telephone bill. The contents of it and the rate calculation etc
should be as per BSNL rules. Student is expected to gather the required information through the
BSNL website.

Program:

/*Let take a BSNL Tariff plan for customers

Rent : Rs. 250/-


Tariff plan
Plus Rs. 80 for each UNIT

The Structure Object fields are:

Customer name::

Telephone number::

Units to be billed::

Calculate Bill Amount from the given input amount of each customer and prepare the Bill and print
it.*/

Program:

void main()

N.VENKATASIVA REDDY GCET, KADAPA Page 120 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
{

int n,i;

struct bill

char name[20];

int num;

int units;

}a[50];

clrscr();

printf("\nEnter the no of customers :: ");

scanf("%d",&n);

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

printf("\nEnter the %d customer's name :: ",i+1);

scanf("%s",&a[i].name);

printf("\nEnter the customer's number :: ");

scanf("%d",&a[i].num);

printf("\nEnter the no of units :: ");

scanf("%d",&a[i].units);

printf("\n\n");

clrscr();

printf(" THE PRINTED BILL WILL BE\n");

printf("*************************\n\n");

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

printf("\nNAME :: %s",a[i].name);

printf("\nTEL. NUMBER :: %d",a[i].num);


N.VENKATASIVA REDDY GCET, KADAPA Page 121 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
printf("\nBILL AMOUNT is Rs :: %f",((a[i].units)*0.8)+250);

getch();

Output:

Enter the no of customers:: 2

Enter the 1 customer's name :: abc

Enter the customer's number :: 236589

Enter the no of units :: 25

Enter the 2 customer's name :: efg

Enter the customer's number :: 236541

Enter the no of units :: 41

THE PRINTED BILL WILL BE

*************************

NAME :: abc

TEL. NUMBER :: -25555

BILL AMOUNT is Rs :: 270.000000

NAME :: efg

TEL. NUMBER :: -25603

BILL AMOUNT is Rs :: 282.800000


N.VENKATASIVA REDDY GCET, KADAPA Page 122 of
84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

51. Aim:Write a program to find the execution time of a program.

Program:

#include<stdio.h>

#include<time.h>

void main( )

double begin, end;

double time_spent;

int sum,a,b;

clrscr();

begin = clock();

/*Processing time starts here*/

a=9;

b=90;

sum=a+b;

printf("sum=%d",sum);

/*Processing time ends here*/

end = clock();

time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

printf("\n Time spent for execution of sum of 2 numbers :: %e",time_spent);

getch();

Output:
sum=99
Time spent for execution of sum of 2 numbers :: 0.000000e+00

N.VENKATASIVA REDDY GCET, KADAPA Page 123 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE

52. Aim:Design a file format to store a person's name, address, and other information. Write a
program to read this file and produce a set of mailing labels

Program:

#include<stdio.h>

void main()

struct details

char name[20];

char add[100];

char tel[20];

}d;

FILE *fp;

clrscr();

fp=fopen("label.txt","rw");

printf("By Reading label.txt file ::");

printf("\n\nPerson's details are :: ");

printf("\n***********************");

printf("\n\nPerson's name :: ");

fscanf(fp,"%s",&d.name);

printf("%s",d.name);

printf("\nAddress :: ");

fscanf(fp,"%s",&d.add);

printf("%s",d.add);

printf("\nPerson's tel. no. :: ");

fscanf(fp,"%s",&d.tel);

printf("%s",d.tel);

N.VENKATASIVA REDDY GCET, KADAPA Page 124 of


84
Computer Programming LAB MANUAL B. Tech I/I Sem. Dept. of CSE
getch();

clrscr();

printf(" THE MAILING LABEL IS :\n");

printf("*************************\n\n");

printf("\n%s",d.name);

printf("\n%s",d.add);

printf("\nTel NO:%s",d.tel);

getch();

Output:

By Reading label.txt file ::

Person's details are ::

***********************

Person's name :: PRAKESH

Address :: DOORNO:2-3-567,NELLOREPALEM,ATMAKUR,S.P.S.R.NELLORE(AP)

Person's tel. no. :: 955689

THE MAILING LABEL IS :

*************************

PRAKESH

DOORNO:2-3-567,NELLOREPALEM,ATMAKUR,S.P.S.R.NELLORE(AP)

Tel NO:955689

N.VENKATASIVA REDDY GCET, KADAPA Page 125 of


84

Das könnte Ihnen auch gefallen