Sei sulla pagina 1di 123

SRIRAM ENGINEERING COLLEGE

PERUMALPATTU - 602 024.

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


GE6263- COMPUTER PROGRAMMING LABORATORY

NAME

REG NO :

SRIRAM ENGINEERING COLLEGE


PERUMALPATTU - 602 024.
DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING

BONAFIDE CERTIFICATE

REGISTER.NO:

NAME OF THE LAB: GE6263- Computer Programming Laboratory


YEAR/SEMESTER

I YEAR/ II SEM

This is to certify that this is a bonafide record of work done by


________________________Of the Department of Electrical and Electronics Engineering
in the Computer Programming Laboratory during the academic year 2014-15.

SIGNATURE OF LAB IN CHARGE

SIGNATURE OF HEAD OF DEPT.

Submitted for the Practical Examination held on

INTERNAL EXAMINER

EXTERNAL EXAMINER

TABLE OF CONTENTS
CHAPTER
NO

EXERCISE
NO

DATE

LAB
EXPERIMENT/CHAPTER
NAME

BASIC UNIX COMMANDS


I-1
I-2

STUDY OF UNIX
OPERATING SYSTEM
BASIC SHELL COMMANDS
PRACTICE-I
PRACTICE-II
PRACTICE-III
PRACTICE-IV

I-3
II

PRACTICE-V
PRACTICE-VI
UNIX EDITORS

SHELL PROGRAMMING
II-1

SEQUENTIAL LOGIC

II-1.1

AREA AND
CIRCUMFERENCE OF A
CIRCLE
SIMPLE INTEREST

II-1.2
II-1.3

II-2

FARENHEIT TO
CENTIGRADE CONVERSION
SWAPPING VALUES OF
TWO VARIABLES
DECISION LOGIC

II-2.1

ODD/EVEN

II-2.2

II-3

CHECK POSITIVE OR
NEGATIVE NUMBER
BIGGEST OF THREE
NUMBERS
STUDENT GRADE
DETERMINATION
CASE LOGIC

II-3.1

VOWEL/CONSONANT

II-3.2

SIMPLE CALCULATOR
SIMULATION

II-1.4

II-2.3
II-2.4

PAGE
NO

SIGN

II-4

LOOPING LOGIC

II-4.1

MULTIPLICATION TABLE

II-4.2

ARMSTRONG NUMBER

II-4.3

FIBONACCI SERIES

II-4.4

PRIME NUMBER

II-4.5

FACTORIAL OF A GIVEN
NUMBER

II-4.6

SUM AND AVERAGE OF N


NUMBERS

III

C PROGRAMMING IN UNIX
III-1

FUNCTIONS

III-1.1

XY COMPUTATION

III-1.2

FACTORIAL [RECURSION]

III-1.3

III-2

STRING CONCATENATION
WITHOUT USING STRCAT
FUNCTION
STRING COPY WITHOUT
USING STRCPY FUNCTION
POINTERS

III-2.1

CALL BY REFERENCE

III-3

FILE HANIDLING

III-3.1

COUNT THE NUMBER OF


LINES & CHARACTERS FOR
A GIVEN FILE
FILE COPY

III-1.4

III-3.2
III-4
III-4.1
III-4.2
III-4.3

DYNAMIC MEMORY
ALLOCATION
STRING REVERSE USING
DMA
STUDENT AGGREGATE
USING DMA
SORTING USING DMA

STAFF-IN-CHARGE

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

CHAPTER-1 BASIC UNIX COMMANDS


Exercise: I-1 STUDY OF UNIX OPERATING SYSTEM
AIM
To introduce the concept of UNIX Operating System

Operating System-Definition:
An Operating System is a set of programs that:
that controls and manages the operations of computer.
acts as an intermediate between hardware and user.

Functions of Os:
Resource management.
Task management.
Scheduling.
Fault Tolerance.
File management.

OS Types:

1. Single UserThe system will have its own hard disk, memory, CPU and other resources all
dedicated to a single user. Eg. MS-DOS

2. Multi UserThe users having access to a multi-user system will have just a terminal and a
keyboard. The other resources such as hard disk, printers are centrally located. The user is
expected to simply hook onto his account, perform the work, disconnect and leave quietly. Eg.
UNIX

UNIX History:
The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson
and Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information and

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Computing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in
1973 in C principally authored by Ritchie.

UNIX Features:

1. Multi-user systemMulti-user capability of UNIX allows several users to use the same
computer to perform their tasks. Several terminals [Keyboards and Monitors] are connected to a
single powerful computer [UNIX server] and each user can workwith their terminals.

2. Multi-tasking systemMultitasking is the capability of the operating system to perform


various task simultaneously, i.e. a user can run multiple tasks concurrently.

3. Programming FacilityUNIX is highly programmable, the UNIX shell has all the necessary
ingredients like conditional and control structures, etc.

4. SecurityUNIX allows sharing of data; every user must have a single login name and
password. So, accessing another users data is impossible without his permission.

5. PortabilityUNIX is portable because it is written in a high level language. So, UNIX can be
run on different computers.

6. CommunicationUNIX supports communication between different terminals of the same


server as well as between terminals on different servers.

Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and
Libraries and enhanced GUI (X Window).

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Organization of UNIX:
The UNIX system is functionally organized at three levels and are:
1. The kernel, which schedules tasks and manages storage;
2. The shell, which connects and interprets users' commands, calls programs from memory, and
executes them; and
3. The tools and applications that offer additional functionality to the OS

UNIX Structure:

The kernel is the heart of the system, a collection of programs written in C that directly
communicate with the hardware. There is only one kernel for any system. It's that part of UNIX
system that is loaded into memory when the system is booted. It manages the system resources,
allocates time between user and processes, decides process priorities, and performs all other
tasks. The kernel, in traditional parlance, is often called the Operating system. The shell, on the
other hand, is the "sleeping beauty" of UNIX. It is actually the interface between the user and the
kernel. The shell is the agency which takes care of the features of redirection and has a

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

programming capability of its own. The Tools and Applications consist of Application Software,
Compilers, Database Package, Internet tools, UNIX commands, etc.

File System:
A file in UNIX is nothing but a storehouse of information and everything is treated as a
file by UNIX. The files can be broadly classified as follows:

Ordinary filesContains stream of data. All data, text, source programs, object and
executable code, commands fall into this category.

Directory filesContains no external data. It contains an entry, name of the file and
its inode (identification number) for each file and subdirectory under that directory.Directory
files are not created by the user but by the UNIX system itself.

Device filesEven physical devices are treated as files. These are special in the sensethat any
output directed to it will be reflected onto the respective device

UNIX File System:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

All files in UNIX are related to one another. The file system of UNIX resembles a tree
that grows from top to bottom as shown in the figure. The file system begins with a directory
called root (at the top). The root directory is denoted by a slash (\). Branching from root there are
several directories such as bin, lib, etc, tmp, dev. Each of these directories contains several subdirectories and files.

RESULT:
Thus the study of UNIX Operating System has been completed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: I-2

REGISTER NUMBER:

BASIC SHELL COMMANDS

AIM
To study and execute Unix commands.

Directory Commands:
Command
mkdir
rmdir
cd
cd ..

Usage
To create a directory
To delete a directory
To change the directory
To come back to previous
directory
To come back to home directory
directly
Lists the contents of directory
To print current working
directory
To delete the nonempty
directories

Syntax
mkdir <directoryname>
rmdir <directoryname>
cd <directoryname>
cd ..

Commands

Usage

Syntax

cat

Used to create file, display the


file, concatenate the files

cat >filename
cat <filename>
cat <file1> < file2>

cp

To copy the contents of file to


another file
To the contents of file to another
file
To create and edit a file
Arrange the elements in
ascending order.
To extract the line containing
particular information from a
file/directory
To remove a file
Prints the first 10 lines by default

cp <src> <dest>

cd ~
ls
pwd
rm r

cd ~
ls
pwd
rm r <directoryname>

File Commands:

mv
vi
sort
grep

rm
head

mv <src> <dest>
vi <filename>
sort <filename>
grep <word*> <filename>

rm <filename>
head <filename>, head [-n]

GE6263 COMPUTER PROGRAMMING LABORATORY


tail
wc
cmp
uniq
ln
nl

REGISTER NUMBER:

Prints the last 10 lines by default


Specifies the number of lines of
file
Compares the sorted files
To delete the duplicate lines
from sorted list
Move the contents of file to file
Displays the contents of file with
line number

tail <filename>m, tail [-n]


wc <filenme>

Usage
Lists who is on computers in the
lab
Print the present date
Print the present time.
To print the calendar of the
current month.
Lists commands you've done
recently
Checks the current user
To logout
To clear the window
Online help

Syntax
finger

cmp <file1> <file2>


uniq <filename>
ln [-s] oldname newname
nl <filename>

User Commands:

Commands
finger
date
time
cal
history
whoami
exit
clear
man

date
time
cal
cal <month_no> <year>
history
whoami
exit
clear
man

GE6263 COMPUTER PROGRAMMING LABORATORY

LAB PRACTICES:

Practice-I Write and execute the Unix Commands for the following:
i] Change your working directory.
ii] Return to home directory.
iii] Lists the contents of the home directory.
iv] Delete the created directory.

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

Practice-II Write and execute the Unix Commands for the following:
i] Create a file A and enter BE-CSE
ii] Create another file B and enter First year
iii] Copy the contents of file A to File B.
iv] Move the contents of file B to File A.

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Practice-III Write and execute the Unix Commands for the following:
i] Change your working directory as SREC within that create a file CSE.
ii] Remove the duplicate contents of the file and count the number of lines.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Practice-IV Write and execute the Unix Commands for the following:
i] Create two directories ABC and DEF.
ii] Inside ABC and DEF create files CBA and FED respectively.
iii] Display the first 3 lines in the file CBA.
iv] Move the contents of FED to CBA.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Practice-V Write and execute the Unix Commands for the following:
i] Change your working directory as ABACUS within that create a file CSE-B and enter the
theory and lab of current semester.
ii] Display the line containing the word Lab and its count.
iii] Display the line containing the word Theory.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Practice-VI Write and execute the Unix Commands for the following:
i] Display the current date time.
ii] Display the calendar of this month.
iii] Display the calendar of Oct 1987.
iv] Usage of bc command.

Result:
Thus various UNIX commands were studied and efficient practices were made
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: I-3

REGISTER NUMBER:

UNIX EDITORS

UNIX system starts a special version of a shell called an interactive shell, and shows a
shell prompt, usually in the form of a dollar sing ($), a percent sign( %), or a pound sign (#),
When we type a line of input at a shell prompt, the shett tries to interpret it. Input to a shell
prompt is sometimes called a command line.

Modes in vi Editor:
The UNIX vi editor is a full screen editor and has three modes of operation:
Command mode
This is the default when you enter vi. In command mode, most letters, or short sequences of
letters, that you type will be interpreted as commands, without explicitly pressing Enter. If you
press Esc when you're in command mode, your terminal will beep at you. This is a very good
way to tell when you're in command mode.
Insert mode
In insert mode, whatever you type is inserted in the file at the cursor position. Type a
(lowercase letter a, for append) to enter insert mode from command mode; press Esc to end
insert mode, and return to command mode.

Line mode
Use line mode to enter line oriented commands. To enter line mode from command mode,
type a colon . Your cursor moves to the bottom of the screen, by a colon prompt. Type a line
mode command, then press Enter. Any sensible command from the Unix line editor ex will
work, and a few are good to know about. These commands are indicated in this handout by a
colon in front of the command. Each time you use a line mode command, you must type a colon
to enter line mode, then type the command by the colon prompt at the bottom of the screen, then
press Enter when you finish typing the command.

GE6263 COMPUTER PROGRAMMING LABORATORY

Command
dw
d$
d0
yy
yw
p /P
?text/text

ZZ/ :wq
:q/:q!
U
U
x
dd
:n
$
:w_file1

REGISTER NUMBER:

Usage
delete the entire word
delete a line from cursor position to the end of the
line
Delete from the cursor position to the start of the
line
Copies (yanks) the entire line
Copies the entire word
Pastes the text
Locates the text in the file. If not found, the
message "Pattern not found" appears. Use n to
repeat the forward search and N for backward
search.
Save a file and exit vi
Quit without saving
Undo last command
Undo all commands used in the Unix prompt
Deletes the character positioned by cursor
Deletes the line currently positioned by the cursor
Goto line n
Move to end of line
Save to new file file1

Result:
Thus the vi editors was studied clearly and vastly.

GE6263 COMPUTER PROGRAMMING LABORATORY

CHAPTER-II

REGISTER NUMBER:

SHELL PROGRAMMING

The UNIX operating systems is flexible in a way that it is not tied to any particular
command interpreter. A programs high-level language statements are stored in a file called the
source file, which programmer creates using editors. In order to execute, high-level source files
must be converted into a low-level machine language file. A compiler is a program that converts
source files into executable machine-language files. The complier reads the lines of code the
programmer wrote in the source file and converts them to the appropriate machine language
instructions. If a source file contains syntax errors, it cannot be converted into an executable file.
A programmer must correct these errors before the program can be run. Unlike high-level
language programs, shell scripts do not have to be converted into machine language by a
compiler. The UNIX shell acts as an interpreter when reading script files. Interpreters read
statements in script files and immediately translate them into executable instructions and cause
them to run. Its collections of executables or commands placed in a file and executed. It
provides user an option to execute a command based on some condition.

Features of Shell:
Interactive.
Allows command execution.
Allows looping.
Allows file creation.

Types of Shell:
Bourne shell (sh) [not popular for interactive use].
C shell (csh) [similar to C adding own commands].
TC shell (tcsh) [edit your command line].
Korn shell (ksh) [inc all features of C and TC].
Bourne Again SHell (bash) [all interactive features of csh and ksh]

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Shell Operators:
Bash shell operators are in three groups:
Defining and Evaluating operators are used to set a variable to a value and to check
variable values. The equal sign (=) is an example.
Arithmetic operators are used to perform mathematical equations. The plus sign (+) is an
example
Redirecting and piping operators are used to specify input and output data specifications
The greater than sign (>) is an example

Shell Logic Structure:


Four basic logic structures needed for program development are:
Sequential logic.
Decision logic.
Looping logic.
Case logic.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise-II-1

REGISTER NUMBER:

SEQUENTIAL LOGIC

Sequential in the sense Programs will run command by command without


repetition/decision/case/loop.

Steps to run the shell scripts:


Type a program in vi editor and save it in <filename>.sh
To execute the program type sh <program_name>

Shell Variables:
Variables are used to store values used in the programs. No need to declare the data_type.
To assign a value to a variable:
$var_name=value

echo command:
Syntax: $echo <sentence>

not mandatory. Displays the output in the screen

Ex:1 $var=100
$echo $var
o/p: 100
Ex:2 $var=distinction
$echo Uve secured $var in BE[CSE]
o/p: Uve secured distinction in BE[CSE]

Ex:3 $var=12;$var1=25
echo $var $var1
o/p: 12 25

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

read command:
Syntax: $read var_name
Used to read the input from the user and assign this input to the variable.

Ex: $read name


Sarav
$echo $name
Sarav

expr command:
Syntax: $expr arg1 operator arg2
Used to evaluate an arithmetic expressions
Ex:1 c=expr a*b
echo $c
Ex:2 echo Enter the value of a and b
read a b
Sum=expr a+b
echo $Sum

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-I.1

REGISTER NUMBER:

AREA AND CIRCUMFERENCE OF A CIRCLE

AIM:
To create a Shell program for calculating the Area and Circumference of a Circle.

ALGORITHM:

Step 1 : Start
Step 2 : Define constant pi = 3.14
Step 3 : Read the value of radius
Step 4 : Calculate area using formulae: pi radius radius
Step 5 : Calculate circumference using formulae: 2 pi radius
Step 6 : Print area and circumference
Step 7 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:
clear
pi=`expr "scale=2; 22 / 7" | bc`
echo "Enter value for radius : "
read radius
area=`expr "scale=2; $pi * $radius * $radius" | bc`
circum=`expr "scale=2; 2 * $pi * $radius" | bc`
echo "Area : $area"
echo "Circumference : $circum"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost sequential]$ sh circle.sh


Enter value for radius : 12
Area : 452.16
Circumference : 75.36

RESULT:
Thus the Shell Script for Calculating the Area and Circumference of a Circle was created
and executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-I.2

REGISTER NUMBER:

SIMPLE INTEREST

AIM:
To create a Shell program for calculating the Simple Interest.

ALGORITHM:
Step 1 : Start
Step 2 : Read the values principal, rate and years
Step 3 : Compute Simple Interest using the formulae: (principal rate years) / 100
Step 4 : Print Simple Interest
Step 5 : Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Interest computation using bc


echo "Enter Principal amount : "
read p
echo "Enter number of years : "
read n
echo "Enter rate of interest : "
read r
si=`expr "scale=2; $p * $n *$r / 100" | bc`
echo "Simple Interest : $si"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost sequential]$ sh si.sh


Enter Principal amount : 1285
Enter number of years : 3
Enter rate of interest : 5
Simple Interest : 192.75

RESULT:
Thus the Shell Script for Calculating the Simple Interest was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-I.3

REGISTER NUMBER:

FARENHEIT TO CENTIGRADE CONVERSION

AIM:
To create a Shell program for Farenheit To Centigrade Conversion.

ALGORITHM:

Step 1 : Start
Step 2 : Read fahrenheit value
Step 3 : Convert fahrenheit to centigrade using the formulae: (fahrenheit 32) 5/9
Step 4 : Print centigrade
Step 5 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Degree conversion
echo "Enter Fahrenheit : "
read f
c=`expr \( $f - 32 \) \* 5 / 9`
echo "Centigrade is : $c"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost sequential]$ sh degconv.sh

Enter Fahrenheit : 213


Centigrade is : 100

RESULT:
Thus the Shell Script for Farenheit To Centigrade Conversion was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise:II-I.4

REGISTER NUMBER:

SWAPPING VALUES OF TWO VARIABLES

AIM:
To create a Shell program for Swapping values of two Variables.

.
ALGORITHM:

Step 1 : Start
Step 2 : Read the values of a and b
Step 3 : Interchange the values of a and b using another variable t as follows:
t=a
a=b
b=t
Step 4 : Print a and b
Step 5 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:
# Swapping values
echo "Enter value for A : "
read a
echo "Enter value for B : "
read b
t=$a
a=$b
b=$t
echo "Values after Swapping"
echo "A Value is $a"
echo "B Value is $b"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost sequential]$ sh swap.sh

Enter value for A : 12


Enter value for B : 23
Values after Swapping::
A Value is 23
B Value is 12

RESULT:
Thus the Shell Script for Swapping values of two variables was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-2

REGISTER NUMBER:

DECISION LOGIC

Shell supports decision-logic using if statement. The if statement like its counterpart in
programming languages has the following formats. The first construct executes the statements
when the condition is true. The second construct adds an optional else to the first one that has
different set of statements to be executed depending on whether the condition is true or false.
The last one is an elif ladder, in which conditions are tested in sequence, but only one set of
statements is executed.

Syntax: ifthen
if [ condition ]
then
statements
fi
Syntax: ifthenelse

if [ condition ]
then
statements
else
statements
fi
Syntax: ifelifelse

if [condition ]
then
statements
elif [ condition ]

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

then
statements
.. .
else
statements
fi
The set of relational and logical operators used in conditional expression is given below.
The numeric comparison in the shell is confined to integer values only.

Numerical Comparators:
Operator
-eq
-ne
-gt
-lt
-ge
-le

Meaning
Equal
Not equal
Greater than
Less than
Greater than or equal to
Less than or equal to

Logical Operators:
Operator
-a
-o
-!

Meaning
AND
OR
Negation

Arithmetic Operators:
Operators
+
\*
/

Meaning
Addition
Subtraction
Multiplication
Division

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-2.1

REGISTER NUMBER:

ODD/EVEN

AIM:
To create a Shell program to check whether the given number is Odd/Even.

ALGORITHM:
Step 1 : Start
Step 2 : Read number
Step 3 : If number divisible by 2 then
Print "Number is Even"
Step 3.1 : else
Print "Number is Odd"
Step 4 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Odd or even using if-else


echo "Enter a non-zero number : "
read num
rem=`expr $num % 2`
if [ $rem -eq 0 ]
then
echo "$num is Even"
else
echo "$num is Odd"
fi

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost decision]$ sh oddeven.sh

Enter a non-zero number: 12


12 is Even

RESULT:
Thus the Shell Script for checking Odd/Even number was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-2.2

REGISTER NUMBER:

CHECK POSITIVE OR NEGATIVE NUMBER

AIM:
To write a shell program to check the given number is positive or negative.

ALGORITHM:

1. Start the program.


2. Get the number n from the user.
3. C heck if n <0 then print negative number.
If n > 0 then print positive number otherwise print zero.
4. Stop the program.

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

clear
echo Enter a number
read n
if [ $n gt 0 ]
then
echo $n is a Positive number
elif [ $n -lt 0 ]
then
echo $n is a Negative number
else
echo $n is a zero
fi

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT :

[Secd52@localhost decision]$ sh posneg.sh

Enter the number:72


72 is a positive number

RESULT:
Thus the shell script was written and executed for checking the given number positive or
Negative.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-2.3

REGISTER NUMBER:

BIGGEST OF THREE NUMBERS

AIM:
To create a Shell program for determining the biggest among three numbers.

ALGORITHM:

Step 1 : Start
Step 2 : Read values of a, b and c
Step 3 : If a > b and a > c then
Print "A is the biggest"
Step 3.1 : else if b > c then
Print "B is the biggest "
Step 3.2 : else
Print "C is the biggest"
Step 4 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Biggest using logical expression


echo "Give value for A B and C: "
read a b c
if [ $a -gt $b -a $a -gt $c ]
then
echo "$a is the Biggest number"
elif [ $b -gt $c ]
then
echo "$b is the Biggest number"
else
echo "$c is the Biggest number"
fi

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost decision]$ sh max.sh

Give value for A B and C: 4 3 9


9 is the Biggest number

RESULT:
Thus the Shell Script for checking the largest among three numbers was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-2.4

STUDENT GRADE DETERMINATION

AIM:
To create a Shell program for Student Grade Determination.

ALGORITHM:

Step 1 : Start
Step 2 : Read mark
Step 3 : If mark > 90 then
Print "S grade"
Step 3.1 : else if mark > 80 then
Print "A grade"
Step 3.2 : else if mark > 70 then
Print "B grade"
Step 3.3 : else if mark > 60 then
Print "C grade"
Step 3.4 : else if mark > 55 then
Print "D grade"
Step 3.5 : else if mark 50 then
Print "E grade"
Step 3.6 : else
Print "U grade"
Step 4 : Stop

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:
clear
echo "Enter the mark : "
read mark
if [ $mark -gt 90 ]
then
echo "S Grade"
elif [ $mark -gt 80 ]
then
echo "A Grade"
elif [ $mark -gt 70 ]
then
echo "B Grade"
elif [ $mark -gt 60 ]
then
echo "C Grade"
elif [ $mark -gt 55 ]
then
echo "D Grade"
elif [ $mark -ge 50 ]
then
echo "E Grade"
else
echo "U Grade"
fi

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost decision]$ sh grade.sh

Enter the mark : 65


C Grade

RESULT:
Thus the Shell Script for Student Grade Determination was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-3

REGISTER NUMBER:

CASE LOGIC

The case logic is used to compare a variables value against a set of constants integer,
character, string, range). If it matches a constant, then the set of statements followed after) is
executed till a ;; is encountered. The optional default block is indicated by *. Multiple constants
can be specified in a single pattern separated by |.

Syntax: Case logic

case variable in
constant1)
statements ;;
constant2)
statements ;;
...
constantN)
statements ;;
*)
statements
esac

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-3.1

REGISTER NUMBER:

VOWEL/CONSONANT

AIM:
To create a Shell program to check whether entered characters is vowel / consonant.

ALGORITHM:
Step 1 : Start
Step 2 : Read char
Step 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then
Print "It's a vowel"
Step 3.1 : else
Print "It's a consonant"
Step 4 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Vowel with multiple values in a pattern


clear
echo "Key in a lower case character : "
read choice
case $choice in
a|e|i|o|u) echo "It's a Vowel";;
*) echo "It's a Consonant"
esac

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost case]$$ sh vowel.c

Key in a lower case character : e


It's a Vowel

RESULT:
Thus the Shell Script for checking vowel/consonant using case logic was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-3.2

SIMPLE CALCULATOR SIMULATION

AIM:
To create a Shell program for Simple Calculator Simulation.
.

ALGORITHM:

Step 1 : Start
Step 2 : Read operands a and b
Step 3 : Display operation menu
Step 4 : Read option
Step 5 : If option = 1 then
Calculate c = a + b
Step 5.1 : else if option = 2 then
Calculate c = a b
Step 5.2 : else if option = 3 then
Calculate c = a * b
Step 5.3 : else if option = 4 then
Calculate c = a / b
Step 5.4 : else if option = 5 then
Calculate c = a % b
Step 5.5 : else
Print "Invalid option"
Step 6 : Print c
Step 7 : Stop

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Arithmetic operations--multiple statements in a block


echo "Enter the two numbers : "
read a b
echo " 1. Addition"
echo " 2. Subtraction"
echo " 3. Multiplication"
echo " 4. Division"
echo " 5. Modulo Division"
echo "Enter the option : "
read option

case $option in
1) c=`expr $a + $b`
echo "$a + $b = $c";;
2) c=`expr $a - $b`
echo "$a - $b = $c";;
3) c=`expr $a \* $b`
echo "$a * $b = $c";;
4) c=`expr $a / $b`
echo "$a / $b = $c";;
5) c=`expr $a % $b`
echo "$a % $b = $c";;
*) echo "Invalid Option"
esac

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[Secd52@localhost case]$ sh calc.sh

Enter the two numbers: 2 4


1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulo Division
Enter the option : 1
2+4=6

RESULT:
Thus the Shell Script for Simple Calculator Simulation using case logic was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4

REGISTER NUMBER:

LOOPING LOGIC

Shell supports a set of loops such as for, while and until to execute a set of statements
repeatedly. The body of the loop is contained between do and done statement.

The for loop doesn't test a condition, but uses a list instead.

Syntax:
for variable in list
do
statements
done

The while loop executes the statements as long as the condition remains true.

Syntax:
while [ condition ]
do
statements
done

The until loop complements the while construct in the sense that the statements are executed
as long as the condition remains false.

Syntax:
until [ condition ]
do
statements
done

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.1

MULTIPLICATION TABLE

AIM:
To create a Shell program for generating Multiplication Table.

ALGORITHM:

Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize 1 to i
Step 4 : Print n, i, ni
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5 until i 10
Step 7 : Stop

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

clear
# Multiplication table using for loop
clear
echo "Which multiplication table? : "
read n
for x in 1 2 3 4 5 6 7 8 9 10
do
p=`expr $x \* $n`
echo "$n X $x = $p"
done

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost loop]$ sh multable.sh

Which multiplication table? : 6


6X1=6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30
6 X 6 = 36
6 X 7 = 42
6 X 8 = 48
6 X 9 = 54
6 X 10= 60

RESULT:
Thus the Shell Script for generating Multiplication Table was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.2

REGISTER NUMBER:

ARMSTRONG NUMBER

AIM:
To create a Shell program for checking whether the given number is an Armstrong
number or not.

ALGORITHM:

Step 1 : Start
Step 2 : Read number
Step 3 : Initialize 0 to sum and number to num
Step 4 : Extract lastdigit by computing number modulo 10
Step 5 : Cube the lastdigit and add it to sum
Step 6 : Divide number by 10
Step 7: Repeat steps 46 until number > 0
Step 8 : If sum = number then
Print Armstrong number
Step 8.1 : else
Print Not an Armstrong number
Step 9 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Armstrong number using while loop


clear
echo "Enter a number : "
read n
a=$n
s=0
while [ $n -gt 0 ]
do
r=`expr $n % 10`
s=`expr $s + $r \* $r \* $r`
n=`expr $n / 10`
done
if [ $a -eq $s ]
then
echo " $n is an Armstrong Number"
else
echo " $n is not an Armstrong number"
fi

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd52@localhost loops]$ sh armstrong.sh

Enter a number: 253


253 Armstrong Number

RESULT:
Thus the Shell Script for checking whether the given number is an Armstrong number or
not was created and executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.3

FIBONACCI SERIES

AIM:
To create a Shell program for generating Fibonacci Series.

ALGORITHM:

Step 1 : Start
Step 2 : Read number of terms as n
Step 3 : Initialize 0 to f1, 1 to f2 and 2 to i
Step 4 : Print initial fibonacci terms f1, f2
Step 5 : Generate next term using the formula f3 = f1 + f2
Step 6 : Print f3
Step 7 : Increment i by 1
Step 8 : Assign f2 to f1
Step 9 : Assign f3 to f2
Step 10 : Repeat steps 59 until i n
Step 11 : Stop

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Fibonacci series using while loop


clear
echo "Enter number of terms : "
read n
echo "Fibonacci Series"
f1=0
f2=1
echo "$f1 "
echo " $f2 "
i=2
while [ $i -lt $n ]
do
f3=`expr $f1 + $f2`
echo -n " $f3 "
f1=$f2
f2=$f3
i=`expr $i + 1`
done

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost loops]$ sh fibo.sh

Enter number of terms: 8


Fibonacci Series
0 1 1 2 3 5 8 13

RESULT:
Thus the Shell Script for generating Fibonacci Series was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.4

REGISTER NUMBER:

PRIME/NOT

AIM:
To create a Shell program for checking whether the given number is Prime/not.

ALGORITHM:

Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize i to 2
Step 4 : If n is divisible by i then
Print Not Prime and Stop
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5 until i n/2
Step 7 : Print "Prime"
Step 8 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Prime number using exit


echo "Enter the number : "
read n
i=2
m=`expr $n / 2`
until [ $i -gt $m ]
do
q=`expr $n % $i`
if [ $q -eq 0 ]
then
echo "Not a Prime number"
exit
fi
i=`expr $i + 1`
done
echo "Prime number"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost loops]$ sh prime.sh

Enter the number:17


Prime number

RESULT:
Thus the Shell Script for checking whether the given number is Prime/not was created
and executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.5

REGISTER NUMBER:

FACTORIAL OF A GIVEN NUMBER

AIM:
To create a Shell program for calculating the Factorial of a given number.

ALGORITHM:

Step 1 : Start
Step 2 : Read number
Step 3 : Initialize 1 to fact and number to i
Step 4 : fact = fact * i
Step 5 : Decrement i by 1
Step 6: Repeat steps 46 until i > 0
Step 7 : Print fact
Step 8 : Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:

# Factorial value using until


clear
echo "Enter a positive number : "
read n
f=1
until [ $n -lt 1 ]
do
f=`expr $f \* $n`
n=`expr $n - 1`
done
echo "Factorial value : $f"

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost loops]$ sh fact.sh

Enter a positive number : 5


Factorial value: 120

RESULT:
Thus the Shell Script for Calculating the Factorial of given number was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-4.6

REGISTER NUMBER:

SUM AND AVERAGE OF N NUMBERS

AIM:
To write a program to find the Sum and Average of n numbers.

ALGORITHM:
Step1: Start the program.
Step2: Read a number n, which is the limit.
Step3: Initialize i as one and sum as zero.
Step4: Check if i is lesser than or equal to n if it fails goto step7.
Step5: Calculate sum equals to the addition of i with one.
Step6: Calculate i which is the addition of i with one.
Step7:Print sum.
Step8: Calculate the average=sum/n
Step8: Stop the program

GE6263 COMPUTER PROGRAMMING LABORATORY

SHELL SCRIPT:
clear
echo "----------------sum of n numbers-----------------"
echo "enter the value for the limit"
read n
i=1
sum=0
while [ $i -le $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo $sum
avg=`expr $sum / n`
echo $avg

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[Secd52@localhost sequential]$ sh sumofnnumbers.sh
----------------sum of n numbers----------------Enter the value for the limit: 5
15
3

RESULT:
Thus the Shell Script for Computing the Sum and Average of n Numbers was
successfully executed.

GE6263 COMPUTER PROGRAMMING LABORATORY

CHAPTER-III

C PROGRAMMING IN UNIX

C program basically consists of:


Preprocessor commands

[#include<stdio.h>]

Functions

[UDF, printf(), scanf()]

Variables

REGISTER NUMBER:

[Local, Global, Constant]

Statements and Expressions [fn call, assignment, E=(v,c)]


Comments[/*.*/]

Steps to Run a C Program in UNIX:


Create a program using vi editor as vi <prog_name>.c
To compile a program use cc <prog_name>.c
To run a program ./prog_name [or] ./a.out
make <prog_name> [used for quick compilation]
To check the error:
lint <prog_name>.c

Advantages of using C in UNIX:


Portability [UNIX is avail in many m\c].
Pipe [o/p of one program can be made input of another].
Multi-user [can be shared].
UNIX utilities.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-1

REGISTER NUMBER:

FUNCTIONS

A function is a block of code that has a name and it has a property that it is reusable i.e. it
can be executed from as many different points in a C Program as required. Functions are created
when the same process or an algorithm to be repeated several times in various places in the
program. Functions are two types:
1. Built-in / Library function
ex:) printf, scanf etc.
2. User defined function.

User-Defined Functions
Functions defined by the users according to their requirements are called user-defined
functions. These functions are used to break down a large program into a small functions.

Advantage of User defined function:


1. Reduce the source code
2. Easy to maintain and modify
3. It can be called any where in the program.

Body of user defined function:


return_type f_name (argument1,argument 2)
{
local variables;
statements;
return_type;
}

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

The body of user-defined shows that an user-defined functions has following


characteristics:
1. Return type
2. Function name
3. Parameter list of arguments
4. Local variables
5. Statements
6. Return value

Note: The function with return value must be the data type, that is return type and return value
must be of same data type.

User defined function has three parts:


1. Declaration part
ret_type f_name (arguments)
2. Calling part
f_name(arguments);
3. Definition part

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Function Parameters:
Parameters provide the data communication between calling function and called function.
Two types:

Actual parameters:
These are the parameters transferred from the calling function[main function] to the
called function[user defined function].

Formal parameters:
Passing the parameters from the called functions[user defined function] to the calling
functions[main function].

Return Statement:
It is used to return the information from the function to the calling portion of the
program.

Syntax:
return;
return();
return(constant);
return(variable);
return(exp);
return(condn_exp);
By default, all the functions return int data type.

Categories of User defined function/Function Prototypes:


A function prototype declaration consists of the functions return type, name and
arguments list. Always terminated with semicolon. The following are the function prototypes:
1. Function without return value and without argument.
2. Function without return value and with argument.
3. Function with return value and with argument.
4. Function with return value and without argument.
Note: Function with more than one return value will not have return type and return statement in
the function definition.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Function Call:
A function can be called by specifying the function_name in the source program with
parameters, if presence within the paranthesis.

Syntax:
Fn_name();
Fn_name(parameters);
Ret_value=Fn_name(parameters);

Recursion:
Recursion is calling function by itself again and again until some specified condition has
been satisfied.

Syntax:
int f_name (int x)
{
local variables;
f_name(y); // this is recursion
statements;
}

Call by Value:
When the value is passed directly to the function it is called call by value. In call by value
only a copy of the variable is only passed so any changes made to the variable does not reflects
in the calling function.

Call by reference:
When the address of the value is passed to the function it is called call by reference. In
call by reference since the address of the value is passed any changes made to the value reflects
in the calling function.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-1.1

REGISTER NUMBER:

XY COMPUTATION

AIM:
To create a C Program for computing the expression XY.

ALGORITHM:
Step-1: Start.
Step-2: Read the input c and d.
Step-3:Initialize the variable i=0 and assign z=1.
Step-4: Using for loop, Compute: z=z*x until condition becomes false.
Step-5: Print the result.
Step-6: Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:

#include<stdio.h>
void power(int x, int y);

//Function Declaration

void main()
{
int c,d; //Local Variable Declaration
printf("\n Enter the value of C:");
scanf("%d", &c);
printf("\n Enter the value of D:");
scanf("%d", &d);
power(c,d); //Function Call
}
void power(int x, int y)

//Function Definition

{
int i=0,z=1;
for(i=0;i<y;i++)
{
z=z*x;
}
printf(%d \n,z);

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd52@localhost functions]$ cc power.c
[secd52@localhost functions]$ ./a.out
Enter the value of C:5
Enter the value of D:3
The value of c^d is 125

RESULT:
Thus the C Program for computing xy using functions was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-1.2

REGISTER NUMBER:

FACTORIAL [RECURSION]

AIM:
To create a C Program for computing Factorial using Recursive function.

ALGORITHM:

Step-1: Start
Step-2: Read the input value n
Step-3: call and print function fact(n)
3.1 Initialize i=1 and f=1
3.2 Using while loop call the function f=s*fact(s-1) until the condition remains true.
Step-4: Print the value m
Step-5: Stop

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
int fact(int s); //Function Declaration
void main()
{
int n,m;
printf("\n Enter the value:");
scanf("%d", &n);
m=fact(n);

//Function Call

printf("The factorial of %d is %d\n",n,m);


}
int fact(int s)
{
int i=1;
int f=1;
while(i<=s)
{
f=s*fact(s-1);
i=i+1;
}
return f;
}

//Function Definition

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost functions]$ cc fact.c


[secd52@localhost functions]$ ./a.out
Enter the value:5
The factorial of 5 is 120

RESULT:
Thus the C Program for computing Factorial using Recursive functions was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Exercise: III-1.3 STRING CONCATENATION WITHOUT USING STRCAT FUNCTION

AIM:
To create a C Program to Concatenate two Strings using Function.

ALGORITHM:

Step-1: Start
Step-2: Read two strings as input values.
Step-3: Using while loop, append the characters present in string2 to string1 until string becomes
NULL.
Step-4: Print String2.
Step-5: Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
void stringconcat(char[],char[]);
int main()
{
char str1[100],str2[100];
printf("Enter first string:");
scanf("%s",str1);
printf("Enter second string:");
scanf("%s",str2);
stringconcat(str1,str2);
printf("String after concatenation:%s",str1);
return 0;
}
void stringconcat(char str1[],char str2[])
{
int i=0,j=0;
while(str1[i]!='\0')
{
i++;
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd11@localhost ~]$ cc strngconc.c
[secd11@localhost ~]$ ./a.out
Enter first string:SREC
Enter second string:A U
String after concatenation:SRECAU

RESULT:
Thus the C Program to concatenate two strings using function was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-1.4

REGISTER NUMBER:

STRING COPY WITHOUT USING STRCPY FUNCTION

AIM:
To create a C Program for String Copy without using strcpy function.

ALGORITHM:

Step-1: Start.
Step-2: Read String1 value.
Step-3: Using while loop, copy the contents of string1 character by character to String2.
Step-4: Print the String2 value.
Step-5: Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
void stringcopy(char[],char[]);
int main()
{
char str1[40],str2[40];
printf("Enter any string:");
scanf("%s",str1);
stringcopy(str1,str2);
printf("After copying string2=%s",str2);
printf("\n string1=%s",str1);
return 0;
}
void stringcopy(char str1[],char str2[])
{
int i=0;
while(str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

str2[i]='\0';
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd11@localhost ~]$ cc strngcopy.c
[secd11@localhost ~]$ ./a.out
Enter any string:CSE
After copying string2=CSE
string1=CSE

RESULT:
Thus the C Program for String Copy without using strcpy function was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-2

REGISTER NUMBER:

POINTERS

Data for a variable is stored at some memory location. Address and Data are two sides an
variable. For instance x = 10 is represented as:

The address of a variable can be obtained using & operator known as reference operator.
The variable's value can be obtained using the dereference operator *.

Pointer Variable:
A Pointer variable or a pointer is a special variable that holds the address of another
variable. Pointer variable are distinguished from other variables by having an asterik (*) prefixed
in the declaration statement.
int x, *iptr;

A pointer variable is a derived data type based on either standard, derived or user-defined
data type. A pointer variable can be made to point any variable of its base type by assigning the
variable's address to the pointer. For instance, an integer pointer can point to an integer variable
only. A pointer variable is allocated 2 bytes irrespective of the data type it points.
ptr = &x; /* Assigning address X to pointer */

Value of the variable pointed to can be accessed by applying the dereference operator
printf("Value of the variable pointed to %d",*ptr);

A pointer of type void is referred to as generic pointer i.e. it can point to any data type.
Since pointer variables hold address, integers could be added or subtracted to yield another
address. A pointer that holds the address of another pointer variable is known as pointer-topointer.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-2.1

CALL BY REFERENCE

AIM:
To create a C Program for Call by Reference.

ALGORITHM:

Step-1: Start the program.


Step-2: Interchange two values using temporary variables.
Step-3: The values after swapping are displayed.
Step-4: Stop the program.
.

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
void swap(int *a, int *b); //Function Declaration
void main()
{
int x,y;
printf("\n Enter the value of x:");
scanf("%d", &x);
printf("\n Enter the value of y:");
scanf("%d", &y);
printf("\n The value of x & y before swapping: %d %d\n",x,y);
swap(&x,&y); //Function Call
printf("\n The value of x & y after swapping is %d %d:\n",x,y);
}
void swap(int *a, int *b) //Function Definition
{
int t;
t=*a;
*a=*b;
*b=t;
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd52@localhost functions]$ cc swap_ref.c
[secd52@localhost functions]$ ./a.out
Enter the value of x:7
Enter the value of y:12
The value of x & y before swapping: 7 12
The value of x & y after swapping is 12 7:

RESULT:
Thus the C Program for Call by Reference was created and executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-3

REGISTER NUMBER:

FILE HANIDLING

File is a collection of related data. Files are used to store information permanently and
retrieve it. We need to learn how to write information to a file and how to read information from
a file.
Why we in need of Files?
Some programs expect the same set of data to be fed as input every time it is run.

Better if the data are kept in a file, and the program reads from the file.

C supports these basic operations:


Naming a file.
Opening a file.
Reading a file.
Writing a file.
Closing a file.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

Opening a File:
A file must be opened before it can be used.
FILE *fp;
fp = fopen (filename, mode);

fp is declared as a pointer to the data type FILE.

filename is a string - specifies the name of the file.

fopen returns a pointer to the file which is used in all subsequent file operations.

mode is a string which specifies the purpose of opening the file:

r :: open the file for reading only


w :: open the file for writing only
a :: open the file for appending data to it

Closing a File:
After all operations on a file have been completed, it must be closed.

Ensures that all file data stored in memory buffers are properly written to the file.

General format: fclose (file_pointer) ;


FILE *xyz ;
xyz = fopen (test, w) ;
.
fclose (xyz) ;

I/O Function in Files:


The simplest file input-output (I/O) function are getc and putc.

getc is used to read a character from a file and return it.


char ch; FILE *fp;
ch = getc (fp) ;

getc will return an end-of-file marker EOF, when the end of the file has been
reached.

putc is used to write a character to a file.

char ch; FILE *fp;


putc (c, fp) ;

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: II-3.1

REGISTER NUMBER:

COUNT THE NUMBER OF LINES & CHRACTERS FOR A


GIVEN FILE

AIM:
To create a C Program for counting the number of lines and characters for a given file.

ALGORITHM:
Step-1: Start.
Step-2: Read the file name.
Step-3: Declare the fopen() in reading mode.
Step-4: The lines and Characters are counted when each line of input from a file or keyboard
will be terminated by the newline character \n.
Step-5: Display the line count and character count.
Step-6: Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp;
int ch,nc,nline;
char filename[40];
nline=0;
nc=0;
printf("Enter filename:");
gets(filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
printf("Cannot open %s for reading \n ",filename);
exit(1);
}
ch=getc(fp);
while(ch!=EOF)
{

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

if(ch=='\n')
nline++;
nc++;
ch=getc(fp);
}
Printf(There are %d of characters and %d lines in %s,nc,nline,filename);
Return 0;
}

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd52@localhost file]$ cc countfile.c
[secd52@localhost file]$ ./a.out
Enter filename:file.txt
There are 35 characters and 3 lines in file.txt

RESULT:
Thus the C Program for counting the number of lines and characters for a given file was
created and executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-3.2

REGISTER NUMBER:

FILE COPY

AIM:
To create a C Program for copying the contents of old file to new file.

ALGORITHM:

Step-1: Start the program.


Step-2: Open the source file in read and write mode.
Step-3: Create the new file and open with new file name.
Step-4: Read each character from the source file and write the character into the destination
file until end of the character.
Step-5: Stop the program.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
int ch;
fp1=fopen("prog.txt","r");
fp2=fopen("prog_old.txt","w");
if((fp1==NULL) || (fp2==NULL))
{
printf("Cannot open for reading \n");
exit(1);
}
else
{
ch=getc(fp1);
while(ch!=EOF)
{
putc(ch,fp2);
ch=getc(fp1);
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

}
fclose(fp1);
fclose(fp2);
printf("\n The files are successfully copied");
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost file]$ cc filecopy.c


[secd11@localhost file]$ ./a.out
The files are successfully copied
[secd11@localhost file]$ cat CP.txt
Shell

RESULT:
Thus the C Program for copying the contents of old file to new file was created and
executed successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-4

REGISTER NUMBER:

DYNAMIC MEMORY ALLOCATION

Memory allocated using arrays is insufficient or abundant, thereby inefficient. To


overcome this, memory could be allocated at run-time instead at compile time. The process of
allocating memory at run time is known as dynamic memory allocation. C inherently does not
have this facility but supports with memory management functions malloc, calloc and realloc,
which can be used to allocate and free memory using free during the program execution. The
memory space located between program and local variable is available known as heap for
dynamic allocation during the execution of the program. The size of heap keeps changing when
program is executed due to creation and death of variables. Therefore it is possible to encounter
memory overflow during dynamic allocation process. In such situations, the memory allocation
functions will return a null pointer.

malloc()
Used to allocate a single block of memory
ptr = (cast-type*) malloc(bytesize);

calloc()
calloc is another memory allocation function that is normally used to request multiple blocks of
storage each of the same size and then sets all bytes to zero.
ptr =(casttype*) calloc(blockcount, blocksize);

free()
Compile time storage of a variable is allocated and released by the system in accordance with
its storage class.
ree(ptr);

realloc()

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

The memory allocated by using calloc or malloc might be insufficient or excess sometimes. In
both the situations the memory size already allocated could be changed with the help of function
realloc. This process is called reallocation of memory. ptr = realloc(ptr, newsize);

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-4.1

STRING REVERSE USING DMA

AIM:
To create a C Program for String Reverse using DMA.

ALGORITHM:
Step-1: Start the program.
Step 2: Declare the pointer variable s.
Step 3: Allocate the memory space using malloc.
Step 4: If s = = NULL, allocation is not done. Else done successfully.
Step 5: Get the string from the user
Step 6: Read the string from backward and print the result.
Step 7: Stop the program.

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(void)
{
char *s;
register int i;
s = malloc(80);

if(!s)
{
printf("Memory request failed.\n");
exit(1);
}
printf("Enter the string:");
gets(s);

printf("\n The Resultant is:\n");


for(i = strlen(s) - 1; i >= 0; i--)

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

putchar(s[ i ]);
printf("\n");
free(s);
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:
[secd52@localhost DMA]$ ./a.out
Enter the string: program
The Resultant is:
margorp

RESULT:
Thus the C Program for String Reverse using DMA was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-4.2

REGISTER NUMBER:

STUDENT AGGREGATE

AIM:
To create a C Program for calculating the Aggregate for a student for n subjects.

ALGORITHM:

Step-1: Start.
Step-2: Read the number of Subjects.
Step-3: Allocate the memory space using malloc().
Step-4: Using for loop, Calculate the average of subjects.
Step-5: Print the Average value.
Step-6: Stop.

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
main()
{
int n, i, *a;
float avg, sum=0;
printf("Enter the No. of subjects : ");
scanf("%d", &n);
a = (int*) malloc(n * sizeof(int));
if (a == NULL)
{
printf("\n memory allocations not possible");
exit(-1);
}
printf("Enter %d marks : ", n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

}
for(i=0; i<n; i++)
sum += a[i];
avg = sum / n;
printf("Average mark : %.2f\n",avg);
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost DMA]$ cc studavg.c


[secd52@localhost DMA]$ ./a.out
Enter the No. of subjects : 5
Enter 5 marks : 100
98
90
79
80
Average mark : 89.40

RESULT:
Thus the C Program for calculating the Aggregate for a student was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

Exercise: III-4.3

SORTING

AIM:
To create a C Program for Sorting the given set of numbers.

ALGORITHM:

Step-1: Start.
Step-2: Allocate the memory space using malloc().
Step-3: Using for loop Read the input values.
Step-4: Using for loop, Sort the input value:
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Step-5: Print the sorted order.
Step-6: Stop.

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

PROGRAM:

/*to sort the given number in ascending order using arrays*/


#include<stdio.h>
#include<stdlib.h>
main()
{
int i,j,n,*a,temp;
printf("Enter total number of items--->");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
printf("\nEnter the elements one by one:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

for(i=0;i<n;i++)
printf("%d\t",a[i]);
}

REGISTER NUMBER:

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

OUTPUT:

[secd52@localhost DMA]$ cc sort.c


[secd52@localhost DMA]$ ./a.out
Enter the Element one by one:
34
12
89
2
07
Elements in Sorted order:
2
07
12
34
89

RESULT:
Thus the C Program for Sorting the given set of numbers was created and executed
successfully.

GE6263 COMPUTER PROGRAMMING LABORATORY

REGISTER NUMBER:

CHECK-LIST:

Sl.No:

Completion Details

1.

Observation Completion

2.

Assignment Completion

3.

Mini-Project Completion

4.

Attendance Percentage

Status

Signature

Potrebbero piacerti anche