computer pratices lab ii (ge 27)

Upload: royal-jenish

Post on 08-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    1/46

    COMPUTER PRATICES LAB II 201

    0

    STUDY ON UNIX

    Ex No: 1

    AIM: To perform a study on UNIX

    An operating system is the software component of the computer system that is responsible for

    the management and coordination of activities and the sharing the limited resources effectively. The

    figure 1 shows the layered structure of the system and where the operating system is located in it.

    Fig 1. Layered Structure

    Operating systems offer a number of services to application programs and users. Users may also

    interact with the operating system with some kind of software user interface (UI) like typingcommands by using command line interface (CLI) or using a graphical user interface (GUI). For

    hand-held and desktop computers, the user interface is generally considered part of the operating

    system. On large multi-user systems like UNIX and Unix-like systems, the user interface is generally

    implemented as an application program that runs outside the operating system.

    There are basically two types of operating system.

    1. Single user operating system

    2. Multi user operating system

    1

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    2/46

    COMPUTER PRATICES LAB II 201

    0

    In single user operating system only one person can use the system at the same time. The

    examples are DOS, Windows 95 and Windows 98.In multi-user operating system more than one

    person can use the system at the same time. The examples are UNIX, LINUX and WINDOWS NTetc.

    The UNIX operating system is made up of two major parts, the kernel and the shell.

    a) The kernel

    The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs andhandles the file store and communications in response to system calls. As an illustration of the waythat the shell and the kernel work together, suppose a user types rm myfile (which has the effect ofremoving the file myfile). The shell searches the filestore for the file containing the program rm, and

    then requests the kernel, through system calls, to execute the program rm on myfile. When the processrm myfile has finished running, the shell then returns the UNIX prompt $ to the user, indicating that itis waiting for further commands.

    b) The shell

    The shell acts as an interface between the user and the kernel. When a user logs in, the login programchecks the username and password, and then starts another program called the shell. The shell is acommand line interpreter (CLI). It interprets the commands the user types in and arranges for them to

    be carried out.

    History - The shell keeps a list of the commands you have typed in. If you need to repeat a command,use the cursor keys to scroll up and down the list or type history for a list of previous commands.

    THE DIRECTORY STRUCTURE

    A file is a collection of information that is assigned a name that is used to identify the file. Files are

    grouped under directory to avoid cluttering of files. A directory can have one or more directories in it

    called subdirectories. In UNIX files and directories are arranged in a hierarchical manner. The top of

    the hierarchy is traditionally called root.

    2

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    3/46

    COMPUTER PRATICES LAB II 201

    0

    LOGGING IN AND LOGGING OUT

    These are the security for the system with many users.

    Logging into a UNIX system requires two information. They are

    1. User name2. Password

    Logging out is done if we want to quit. The command used for this is exit.

    ADVANTAGES OF UNIX OPERATING SYSTEM

    UNIX is more flexible and can be installed on many different types of machines,

    including mainframe computers, supercomputers and microcomputers. UNIX is more stable and does not go down as often as Windows does, thereforerequires less administration and maintenance.

    UNIX has greater built-in security and permissions features than Windows.

    UNIX possesses much greater processing power than Windows.

    RESULT:

    Thus basic of UNIX was studied.

    Ex.No:2 BASIC UNIX COMMANDS

    AIM: To study the BASIC UNIX Commands.

    1. Date command

    The date command tells us the current date and time

    Format: $date Eg:$date

    The date command can also be used with the following format specification.

    $date +%m : To display only month

    3

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    4/46

    COMPUTER PRATICES LAB II 201

    0

    $date +%h : To display month name

    $date +%y : To display last two digits of the year

    $date +%H : To display Hours

    $date +%M : To display Minutes

    $date +%S : To display Seconds

    2.who command

    This command gives us the details of who all have logged into the UNIX system currently.

    Format:$who Example: $who am I

    This tells us to when we had logged in and the systems name for connection being used.

    3.man command

    This command prints manual page.

    Format :$man Example:$man who

    4.pwd command

    It tells us the full path for the current directory

    Format:$pwd

    5.ls command

    The ls command displays the list of files in the current directory.

    Format :$ls

    Various options for ls command

    ls -l :List files in login format. The files are displayed along with their mode,

    number of links, owner of files, file size, modification date &time and

    file name.

    ls -t : Lists in order of last modification time

    ls a : List all entries, including hidden files.

    ls d : Lists directory files instead of contents.

    ls p : puts a slash after each directory.

    ls u : Lists in order of last access time

    6.mkdir command

    This command helps us to make a directory.

    4

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    5/46

    COMPUTER PRATICES LAB II 201

    0

    Format :$mkdir

    Example:$mkdir abc

    7.rmdir command

    This command is used to remove a directory from the disk.

    Format :$rmdir

    Example:$rmdir abc

    8.cd command

    This command is used to move from one directory to another.

    Format:$cd

    Example:$cd abc

    9.cat command

    This command is used to create a file.

    Format:$cat[path]filename

    Example :$cat xyz

    $cat>abc

    Have a nice day

    Ctrl d

    10.cp command

    This command helps us to create duplicate copies of ordinary files.

    Format:$cp[path]source filename [path]destination filename

    Example:$cp abc def

    11.ln command

    This command is used to establish an additional file name for the same ordinary file.

    Format:$ln oldfilename newfilename

    Example:$ln abc def

    12.mv command

    This command move a file from one place to another place.

    Format :$mv source destination

    5

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    6/46

    COMPUTER PRATICES LAB II 201

    0

    Example: $mv abc def

    13.rm command

    This command is used to remove one or more files from a directory. This can be used todelete all files as well as the directory.

    Format: $rm[path]file

    rm i asks the user if he wants to delete the files mentioned.

    rm r recursively delete the entire contents of directory as well as the

    directory itself

    14.echo command

    This command is used to display whatever message we want to display on the screen.

    Format:$echomessage

    Example:$echo learning UNIX is easy

    15.grep command

    The grep utility searches one or more files to see if any contain a specified string ofcharacters.

    Format: grepstringfilename

    Example:$grep lily flower

    16.diff command

    The diff utility compares two files and displays a list of the difference between them. Itdisplays the list of actions to be taken to convert one file into another.

    Format: $diff filename1 filename2

    Example:$diff flower1 flower2

    17.read command

    This command is used in shell scripts.this command waits for the user to input the value ofthe variable.

    Format: $read variablename

    18. clear/tput clear commands

    The clear/tput clear utility clears the screen.

    Format:$clear

    $tput clear

    6

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    7/46

    COMPUTER PRATICES LAB II 201

    0

    19.exit command

    Press(ctrl+D) in response to the shell prompt to logout.

    Format:$exit

    Exercises:

    1.Create the following directory structure in your home directory.

    Oos

    File1 file2 file3 File5

    2..From the directory OS change to the directory to win95.

    3.Display the content of this directory in various formats.

    4.Copy the file1 to the folder LINUX.

    5.Rename the file1 present in the directory LINUX to file4.

    6.Copy the content of file4 to file5 in the same directory.

    7.Set the permission of the file3 to read write execute for user,read execute for

    group and read only for others.

    8.Now clear the computer screen.

    9.Then show the directory where you are.

    10.Display the calendar for the year 2009.

    7

    OS

    MUOSSUOS

    DOS Win9 UNIX LINU

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    8/46

    COMPUTER PRATICES LAB II 201

    0

    11.Check the similarity between file1 and file3.

    12.Change your password and again re-change to the original one.

    13.Remove the whole directory structure.

    RESULT:

    Thus basic of UNIX Commands was studied.

    Ex No:3 SHELL PROGRAMMING

    A Linux shell is a command language interpreter, the primary purpose of which is to translate the

    command lines typed at the terminal into system actions. The shell itself is a program, through which

    other programs are invoked

    What is a shell script ?

    A shell script is a file containing a list of commands to be executed by the Linux shell. shellscript provides the ability to create your own customized Linux commands

    Linux shell have sophisticated programming capabilities which makes shell script powerfulLinux tools

    How to work with shell ?

    Step1:

    In the dollar prompt type

    8

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    9/46

    COMPUTER PRATICES LAB II 201

    0

    $ vi < file name>

    Where vi is the editor ,it will open a new window in which you can type the program you want

    Step2:

    After typing the program press ESC and : together then at the bottom of the vi screen you can see i.e.

    prompt .In that type as wq which means write and quit i.e. the content what is typed will be written

    and saved into that file that has been created

    Step3:

    Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you have to do the

    following

    $ sh < file name >

    Sh command is used to run the shell program

    - is the name of the file for which the output is to be got

    Basically to print a text in the your shell programs echo command is used

    SYNTAX FOR LOOPING STATEMENTS

    IF THEN-ELSE CONSTRUCT

    if [ condition]

    then

    else

    statements

    fi (end of if)

    WHILE

    while

    do

    9

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    10/46

    COMPUTER PRATICES LAB II 201

    0

    Done

    CASE

    Case $ in

    1) ;;2) ;;3) ..4).

    *) ;;

    esac

    For loop

    For(( intitialization;condition;incremetation/decrementation))

    10

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    11/46

    COMPUTER PRATICES LAB II 201

    0

    Ex No 3.a Displaying wishes:

    Aim: To write a shell program to display the wishes based on the time.

    Algorithm:

    1. Find the time2. Based on the time display the wishes as either good morning or good afternoon or good

    evening or good night3. Display both time and wishes

    4. Terminate the processProgram:

    d=`date +%H`

    echo $d

    [ $d -gt 00 -a $d -lt 12 ] && echo "Good Morning"

    [ $d -lt 16 -a $d -gt 12 ] && echo "Good Afternoon"

    [ $d -gt 19 -a $d -lt 19 ] && echo "Good Evening"

    [ $d -gt 19 -a $d -lt 23 ] && echo "Good Night"

    Result:

    Thus the time was found and a wish was displayed using the shell program.

    11

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    12/46

    COMPUTER PRATICES LAB II 201

    0

    Ex no: 3b Biggest of two numbers:

    Aim: To write a shell program to find the bigger of two numbers.

    Algorithm:

    Start the program

    Read the 2 numbers a & b

    Check whether a is greater than b. If true, display a is greater

    Or display b is greater.

    TerminateProgram:

    echo enter the first no

    read a

    echo enter the second no

    read b

    if [ $a -gt $b ]

    then echo the biggest no is $a

    else echo the biggest no is $b

    fi

    Result:

    Thus the bigger of 2 numbers was found using the shell program

    ExNo3.c Biggest of three numbers

    12

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    13/46

    COMPUTER PRATICES LAB II 201

    0

    Aim:

    To write a shell program to find the biggest of three numbers.

    Algorithm:

    Start the program

    Read the three numbers a, b, c

    Check if a > b and a > c

    If true, display a is greater

    Or check if b > c

    If true, display b is greater

    Or display c is greater

    TerminateProgram:

    echo Enter the first number:

    read a

    echo Enter the second number:

    read b

    echo Enter the third number:

    read cif [ $a -gt $b -a $a -gt $c ]

    then

    echo "$a is greater."

    elif [ $b -gt $c ]

    then

    echo " $b is greater. "

    else

    echo "$c is greater."

    fi

    Result:Thus the biggest of 3 numbers was found using the shell program.

    Ex No.3d String Comparison

    Aim:

    13

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    14/46

    COMPUTER PRATICES LAB II 201

    0

    To write a shell program for performing string comparison

    Algorithm:

    Start the program

    Read the two strings

    Check if they are equal

    If true, display the strings are equal

    Or display the strings are not equal

    TerminateProgram;

    echo enter string 1

    read s1

    echo enter string2

    read s2

    if [ $s1 == $s2 ]

    then

    echo the given string are equal

    else

    echo The given strings are not equal

    fi

    Result:

    Thus two strings were compared using the shell program

    Ex no 3e Arithmetic Operations

    Aim: To write a shell program to perform arithmetic operations using switch statement

    Algorithm:

    14

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    15/46

    COMPUTER PRATICES LAB II 201

    0

    1. Enter the input2. Enter the choice

    3. Perform corresponding arithmetic operation on the inputs4. Display the resultProgram:

    echo "enter the first no:"

    read a

    echo "enter the second no:"

    read b

    echo "enter ur choice"

    read n

    case $n in

    1) echo "addition" ;

    c=`expr $a + $b `;

    echo "The sum is $c." ;

    exit ;;

    2) echo "subtraction" ;

    c=`expr $a - $b `;

    echo "The difference is $c." ;

    exit ;;

    3) echo "multiplication" ;

    c=`expr $a \* $b `;

    echo "The product is $c." ;

    exit ;;

    4) echo "division" ;

    c=`expr $a / $b `;

    echo "The quotient is $c." ;

    exit ;;

    *) echo "Invalid" ;

    esac;;

    15

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    16/46

    COMPUTER PRATICES LAB II 201

    0

    Result:

    Thus the arithmetic operations were performed using the shell program.

    Ex No: 3f Sum of n even numbers

    Aim:

    To write a shell program for calculating the sum of n even numbers

    Algorithm:

    1. Read the value of n 2. Initialize the variables sum and i as zero3. Using while loop, increment the value if i by 2

    4. Calculate the value of sum5. Display the result6. Terminate

    Program:

    echo -----------------------

    echo Sum of 'n' even numbers

    echo -----------------------

    echo enter the value of n

    read n

    sum=0

    i=2

    while [ $i -le $n ]

    do

    sum=`expr $sum + $i`

    i=`expr $i + 2`

    done

    echo The sum of even numbers upto $n is $sum

    Result:Thus the sum of even numbers upto n was found using the shell program.

    Ex No:3g SUM OF n NATURAL NUMBERS

    Aim:

    To write a shell program for calculating the sum of n natural numbers

    16

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    17/46

    COMPUTER PRATICES LAB II 201

    0

    Algorithm:

    Read the value of n Initialize the variables sum and i as zero

    Using while loop, increment the value if i

    Calculate the value of sum

    Display the result

    TerminateProgram:

    echo --------------------------

    echo Sum of 'n' natural numbers

    echo --------------------------

    echo Enter the value of n

    read n

    sum=0

    i=0

    while [ $i -le $n ]

    do

    sum=`expr $sum + $i`

    i=`expr $i + 1`

    done

    echo The sum of first $n natural numbers is $sum

    Result:

    Thus the sum of n natural numbers was found using the shell program

    Ex No: 3h Generation of Fibonacci Series

    Aim: To write a shell program to generate Fibonacci series

    Algorithm:

    1. Initialize a and b with 0 and 1

    2. Get the limit and initialize i with 0

    17

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    18/46

    COMPUTER PRATICES LAB II 201

    0

    3. Initialize i4. Add a and b and assign to c

    5. Print c6. Assign the value of b to a and the value of c to b7. Increment i by 18. Repeat the above steps until i is less than n

    Program:

    echo Gneration of fibonaaci series

    a=0

    b=1

    c=0

    echo "Enter the limit:"

    read n

    i=3

    echo "FIBONACCI SERIES"

    echo $a

    echo $b

    for((i=0;$i

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    19/46

    COMPUTER PRATICES LAB II 201

    0

    There are three basic modes of operations in VI.

    a) Command modeb) Insertion modec) Last Line mode

    A) Command Mode:

    The command mode is one which user is able to enter commands. The command

    mode allows the entry of commands to manipulate text. These commands are usually one or two

    characters long, and can be entered with few keystrokes.

    B) Insertion Mode:

    The insertion mode is one in which, the user can enter the data or edit the data. The

    insert mode puts anything typed on the keyboard into the current file.

    C) Last Line Mode:

    The Last line mode is one in which user is able to enter special commands.

    STARTING VI EDITOR:

    To start using vi, at the UNIX prompt type vi followed by a file name.

    $vi newname

    at the Unix $ prompt, where newname is the name you wish to give the new file. On the screen youwill see blank lines, each with a tilde at the left, and a line at the bottom giving the name and status of

    the file:

    ~

    ~

    "testvi" [New file]

    Use vi to open an already existing file by typing vi filename where filename is the name of the

    existing file. If the file is not in your current directory, you must use the full pathname.

    ENTERING TEXT:

    vi has two modes: command mode and insert mode. In command mode, the letters of the

    keyboard perform editing functions (like moving the cursor, deleting text, and so on). In insert mode,

    the letters you type form words and sentences. Unlike word processors, vi starts up in command

    mode. To begin entering text in an empty file, you must change from command mode to insert mode.

    To do this, type the letter i. You may see INSERT MODE at the bottom right of the screen, or nothing

    may appear to change, but you are now in insert mode and can begin typing text. If you make a

    19

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    20/46

    COMPUTER PRATICES LAB II 201

    0

    mistake, pressing the Backspace or Delete key may or may not remove the error, depending on the

    configuration of the software you are using to connect to the Login Service.

    ENDING THE EDIT SESSION:

    While editing, VI keeps the edited text in an area called work buffer. When editing is

    finished, the user must write out the contents of the work buffer to disk file.

    Keeping VI in command mode,

    1. The ZZ (upper case) command can be used to write the newly entered text to the disk andthen end the editing session and returns the control to the shell.

    2. To exit without saving the work, use :q! command

    3. To quit after writing change to the disk file :wq command is used

    4. To quit after replacing the old copy of the file with the new one, :x command is used.

    COMMANDS:

    a) Getting out

    When we want to get out of the editor, switch to command mode(press ESC) if necessary,

    then

    :q Quit vi

    :q! Quit vi without saving changes

    :w Save and continue working in vi

    :wq Save the changes and exit from vi

    :x Save and exit from vi

    ZZ Save the changes and exit from vi

    20

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    21/46

    COMPUTER PRATICES LAB II 201

    0

    b) Inserting Text

    From command mode, these keystrokes switch you into insert mode with new text beinginserted.

    i Invokes insert mode inserts before character

    I Same as i but insertion is at beginning of line

    o Opens blank line before current line

    O Same as o but puts blank line after current line

    a Same as i but appends after cursor

    A Same as a but appends at end of line

    c) Deleting Text

    The following commands allow you to delete text

    x Deletes one character at the cursor position

    n x Delete the n ext n characters at the cursor position

    dw Deletes one word at the cursor position

    n dw Deletes n words at the cursor position

    d0 Deletes from the cursor position till the beginning of the line

    d$ Deletes from the cursor position till the end of the line

    dd Deletes one line at the cursor position

    n dd Deletes the next n lines from the cursor position

    21

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    22/46

    COMPUTER PRATICES LAB II 201

    0

    d) Moving Around

    When in command mode we can use the arrow keys to move the cursor up,down,left,right. Inaddition, these keystrokes will move the cursor:

    k Same as the up arrow key

    h Same as the left arrow key

    l Same as the right arrow key

    j Same as the down arrow key

    w Moves forward by a word

    nw Moves forward by n number of words

    e Moves to the last character of this word or that of the next

    ne Moves to the last character of n the next word

    b Takes the user back by a word

    n b Takes the user back by n number of words

    0(zero) or

    ^

    Takes the user to the beginning of the line

    $ Takes the user to the end of the line

    n G Takes the user to the n the line

    L Takes the user to the last line

    Cutting, Copying, Pasting:

    From command mode, use these keystroke (or keystroke-combination) commands for the

    described cut/copy/paste function:

    yy Copy a line into temporary storage

    nyy Copy n number of lines into temporary storage

    22

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    23/46

    COMPUTER PRATICES LAB II 201

    0

    dd Move a line into temporary storage

    ndd Move n lines into temporary storage

    p Move the text from temporary storage into the current position of cursor

    Searching for text:

    Instead of using the moving around commands above, we can go directly forward or

    backward to specified text using / and ?

    /g Search for a pattern g forwards

    ?g Search for a pattern g backwards

    / Repeat the last search forward

    ? Repeat the last search backward

    Replacing Text:

    This amounts to combining two steps; deleting, then inserting text.

    r Replace a single character at the current cursor position

    R Invoke insert mode and go on replacing till is pressed

    s Deletes the current character and inserts character until is pressed

    S Removes all characters on the current line and allows the user to enter data

    Undoing your changes:

    u Undoing the previous changes

    Screen Manipulation:

    The following commands allow the vi editor to move up and down several lines and to be

    refreshed

    Ctrl-f Scrolls screen forward

    23

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    24/46

    COMPUTER PRATICES LAB II 201

    0

    Ctrl-b Scrolls screen backward

    Ctrl-u Scrolls half a screen backward

    Ctrl-d Scrolls half a screen forward

    Ctrl-L Refreshes the screen

    Exercises

    1. Create a file under the name vifile and enter the following text

    An operating system is the software component of the computer system that is responsible for

    the management and coordination of activities and the sharing the limited resources effectively.

    2. Save the file

    3. Append the following line at the bottom of current file

    Operating system offers a number of services to application programs and users.

    4. Move the cursor to the top of screen, bottom of screen and middle of screen

    5. Search for the word system and enter the following lines below it.

    24

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    25/46

    COMPUTER PRATICES LAB II 201

    0

    The kernel of UNIX is the hub of the operating system: it allocates time and memory to

    programs and handles the file store and communications in response to system calls.

    6. Search for the word software and replace it with hardware.

    7. Go to the 3rd line

    8. Delete the line

    9. Undo the deletion

    10. Copy the first three lines and paste it as 6 to 9 th line

    11. Move the lines 2 to 4 to the bottom of the file

    12. Search for the word is forward and in reverse direction.

    RESULT:

    Thus we study and work in Vi Editor

    C Programming on UNIX

    Ex No: 5: Functions in C

    Function:

    A function is a complete and independent program, which is used (or invoked) by the mainprogram or other subprograms. A subprogram receives values called arguments from a calling

    program, performs calculations and returns the results to the calling program.Advantages of using functions:

    There are many advantages in using functions in a program they are:

    1. It facilitates top down modular programming. In this programming style, thehigh level logic of the overall problem is solved first while the details of each lower level

    functions is addressed later.

    2. The length of the source program can be reduced by using functions at appropriateplaces. This factor is critical with microcomputers where memory space is limited.3. It is easy to locate and isolate a faulty function for further investigation.4. A function may be used by many other programs this means that a c programmer can

    build on what others have already done, instead of starting over from scratch.

    25

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    26/46

    COMPUTER PRATICES LAB II 201

    0

    5. A program can be used to avoid rewriting the same sequence of code at two or morelocations in a program. This is especially useful if the code involved is long or

    complicated.6. Programming teams does a large percentage of programming. If the program isdivided into subprograms, each subprogram can be written by one or two team membersof the team rather than having the whole team to work on the complex program

    C supports the use of library functions and use defined functions. The library functions are used to

    carry out a number of commonly used operations or calculations. The user-defined functions are

    written by the programmer to carry out various individual tasks.

    Function Definition:

    Datatype functionname (argument list);

    argument declaration;

    {local variable declarations;statements;[return expression];

    }Example:

    mul(int a,int b){

    int y;y=a*b;

    return y;}

    Types of functions:

    A function may belong to any one of the following categories:1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.

    1. Functions with no arguments and no return values.

    When a function has no arguments it does not receive any data from the calling function.Similarly when it does not return value the calling function does not receive any data from the calledfunction. A function that does not return any value cannot be used in an expression it can be used onlyas independent statement.2. Functions with arguments but no return values:

    The nature of data communication between the calling function and the arguments to thecalled function and the called function does not return any values to the calling function.3. Functions with arguments and return values:

    The function of the type Arguments with return values will send arguments from the callingfunction to the called function and expects the result to be returned back from the called function backto the calling function.Return value data type of function:

    A C function returns a value of type int as the default data type when no other type isspecified explicitly. For example if function does all the calculations by using float values and if thereturn statement such as return (sum); returns only the integer part of the sum. This is since we have

    not specified any return type for the sum. There is the necessity in some cases it is important to

    26

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    27/46

    COMPUTER PRATICES LAB II 201

    0

    receive float or character or double data type. To enable a calling function to receive a non-integervalue from a called function we can do the two things:

    1. The explicit type specifier corresponding to the data type required must be mentioned in thefunction header. The general form of the function definition isType_specifier function_name (argument list)

    Argumentdeclaration;

    {

    functionstatement;

    }

    The type specifier tells the compiler, the type of data the function is to return.2. The called function must be declared at the start of the body in the calling function, like anyother variable. This is to tell the calling function the type of data the function is actuallyreturning. The program given below illustrates the transfer of a floating-point value betweenfunctions done in a multiple function program.

    Void functions:The functions that do not return any values can be explicitly defined as void. This prevents

    any accidental use of these functions in expressions.

    Ex No: 5a Sorting numbers

    Aim: To write a C program to sort n numbers.

    Algorithm:

    1. Get the number of elements to be sorted.2. Get the array elements to be sorted.3. Sort array of elements by calling the function sort (a, n).4. Print the sorted array of elements.

    Program:

    #include

    void sort(int a[],int n)

    {

    int i,t,j;

    for(i=0;i

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    28/46

    COMPUTER PRATICES LAB II 201

    0

    if(a[i]>a[j])

    {

    t=a[i];

    a[i]=a[j];

    a[j]=t;

    }

    }

    }

    }

    printf("The sorted values are :");

    for(i=0;i

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    29/46

    COMPUTER PRATICES LAB II 201

    0

    Result: Thus the program to sort n numbers was executed and sorted array of elements was

    obtained.

    Ex.No: 5b Palindrome Checking Using Functions

    Aim

    To write a C program to find whether the given string is a palindrome or not.

    Algorithm

    Read a string

    Find the length of the string read. Reverse the string.

    Compare and check whether the given strings are equal.

    Set a flag value

    If the flag=1 then the given string is a palindrome.

    Otherwise, the given string is not a palindrome.

    29

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    30/46

    COMPUTER PRATICES LAB II 201

    0

    Program

    #includechar str[50];int len=0,i=0,j,flag=1;main(){

    printf("Enter a String:");scanf("%s",str);palindrome();

    }

    palindrome(){

    while(str[i++]!='\0')len++;

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

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    31/46

    COMPUTER PRATICES LAB II 201

    0

    The syntax is as shown below. You start by specifying the type of data stored in the locationidentified by the pointer. The asterisk tells the compiler that you are creating a pointer variable.

    Finally you give the name of the variable.Syntax:datatype *variablename;

    Example:

    int *ptr;

    float *string;

    Address operator:

    Once we declare a pointer variable we must point it to something we can do this by assigningto the pointer the address of the variable you want to point as in the following example:ptr=&num;

    This places the address where num is stores into the variable ptr. If num is stored in memory21260 addresses then the variable ptr has the value 21260.Pointer expressions & pointer arithmetic:

    Like other variables pointer variables can be used in expressions. For example if p1 and p2are properly declared and initialized pointers, then the following statements are valid.

    y=*p1**p2;sum=sum+*p1;

    Pointers and function:

    The pointers are very much used in a function declaration. Sometimes only with a pointer a

    complex function can be easily represented and success. The usage of the pointers in a function

    definition may be classified into two groups.

    1. Call by reference

    2. Call by value

    Call by value: When a function is invoked there will be a link established between the formal and

    actual parameters. A temporary storage is created where the value of actual parameters is stored. The

    formal parameters picks up its value from storage area the mechanism of data transfer between actual

    and formal parameters allows the actual parameters mechanism of data transfer is referred as call byvalue. The corresponding formal parameter represents a local variable in the called function. The

    current value of corresponding actual parameter becomes the initial value of formal parameter. The

    value of formal parameter may be changed in the body of the actual parameter. The value of formal

    parameter may be changed in the body of the subprogram by assignment or input statements. This

    will not change the value of actual parameters.

    Call by Reference: When we pass address to a function the parameters receiving the address should

    be pointers. The process of calling a function by using pointers to pass the address of the variable is

    known as call by reference. The function, which is called by reference, can change the values of the

    variable used in the call.

    31

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    32/46

    COMPUTER PRATICES LAB II 201

    0

    Ex No: 6a Swapping two numbers:

    Aim: To write a C program to swap two numbers using pointers

    Algorithm:

    1. Enter the values of a and b2. Swap the numbers by calling the function interchange (&a, &b)3. Print the values of a and b after swapping

    Program:

    #include

    void swap(int *x,int *y)

    {

    int temp;

    32

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    33/46

    COMPUTER PRATICES LAB II 201

    0

    temp=*x;

    *x=*y;

    *y=temp;

    }

    main()

    {

    int a,b;

    printf("Enter the value of a and b:");

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

    swap(&a,&b);

    printf("The values of a and b after interchanging:\n");

    printf("a=%d\nb=%d",a,b);

    printf("\n");

    }

    Result:Thus the program was executed and the two numbers were swapped using pointers.

    Ex No: 6b Sum of n numbers:

    Aim: To write a C program to find out sum of n numbers.

    Algorithm:

    1. Read the value of n2. Get the values3. Perform the summation of given n numbers using pointers

    Program:

    #include

    main()

    {

    33

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    34/46

    COMPUTER PRATICES LAB II 201

    0

    int a[10];

    int n,i,*p,sum=0;

    p=a;

    printf("Enter the number of values\n");

    scanf("%d",&n);

    printf(" Enter the values\n");

    for(i=0;i

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    35/46

    COMPUTER PRATICES LAB II 201

    0

    calloc Allocates space for an array of elements initializes them to zero and returns a

    pointer to the memory

    free Frees previously allocated space

    realloc Modifies the size of previously allocated space.

    Allocating a block of memory:

    A block mf memory may be allocated using the function malloc. The malloc function reserves

    a block of memory of specified size and returns a pointer of type void. This means that we can assign

    it to any type of pointer. It takes the following form:

    ptr=(cast-type*)malloc(byte-size);

    where ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory

    with size byte-size.

    Example:

    x=(int*)malloc(100*sizeof(int));

    On successful execution of this statement a memory equivalent to 100 times the area of intbytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x oftype intAllocating multiple blocks of memory:

    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. The general form of calloc is

    ptr=(cast-type*) calloc(n,elem-size);

    The above statement allocates contiguous space for n blocks each size of elements size bytes.

    All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If

    there is not enough space a null pointer is returned.

    35

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    36/46

    COMPUTER PRATICES LAB II 201

    0

    Releasing the used space:

    Compile time storage of a variable is allocated and released by the system in accordance withits storage class. With the dynamic runtime allocation, it is our responsibility to release the spacewhen it is not required. The release of storage space becomes important when the storage is limited.When the data stored in a block of memory is not then the allocated block of memory for future usecan be released , using the free function.

    free(ptr);

    ptr is a pointer that has been created by using malloc or calloc.

    To alter the size of allocate memory:

    The memory allocated by using calloc or malloc might be insufficient or excess sometimes in

    both the situations we can change the memory size already allocated with the help of the functionrealloc. This process is called reallocation of memory. The general statement of reallocation ofmemory is:

    ptr=realloc(ptr,newsize);

    This function allocates new memory space of size newsize to the pointer variable ptr and returns a

    pointer to the first byte of the memory block. The allocated new block may be or may not be at the

    same region.

    Ex No: 7a Concatenation of two Strings

    Aim: To write C program to concatenate two strings

    Algorithm:

    1. Get two strings to concatenated2. Concatenate the two strings3. Display the concatenated string

    Program:

    #include

    #include

    #define s 40

    main()

    {

    char *s1,*s2,*s3,c;

    int i,j,k;

    36

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    37/46

    COMPUTER PRATICES LAB II 201

    0

    s1=(char*)malloc(s*sizeof(char));

    s2=(char*)malloc(s*sizeof(char));

    s3=(char*)malloc(2*s*sizeof(char));

    printf("Enter the stirng one:");

    scanf("%s",s1);

    printf("Enter the stirng two:");

    scanf("%s",s2);

    i=0;

    while((c=*(s1+i))!='\0')

    {

    *(s3+i)=c;

    i=i+1;

    }

    k=0;

    while((c=*(s2+k))!='\0')

    {

    s3[i+k]=c;

    k=k+1;

    }

    printf("Concatenated string is:\n");

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

    }

    Result:

    Thus the two was concatenated using the C program.

    37

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    38/46

    COMPUTER PRATICES LAB II 201

    0

    ExNo: 7b Altering the allocated memory

    Aim: To write a program to alter the allocated memory

    Algorithm:

    1. Allocate memory space for the character pointer2. Initialize the character pointer with the string MADRAS3. Reallocate memory for storing new string4. Reinitialize the character pointer with new string5. Print the reallocated string

    Program:

    #include

    #include

    main()

    {

    char *p;

    p=(char *)malloc(6);

    strcpy(p,"MADRAS");

    printf("Memory contains:%s\n",p);

    38

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    39/46

    COMPUTER PRATICES LAB II 201

    0

    p=(char *)realloc(p,7);

    strcpy(p,"CHENNAI");

    printf("Memory after altering:%s\n",p);

    free(p);

    }

    Result:

    Thus the program to alter the allocated memory was executed and the output was verified.

    Ex No: 8 Files in C

    Files:

    A file is a block of arbitrary information, or resource for storing information, which is

    available to a computer program and is usually based on some kind of durable storage. A file is

    durable in the sense that it remains available for programs to use after the current program has

    finished.

    File operations:

    C supports a number of functions that have the ability to perform basic file operations, which

    include:

    1. Naming a file2. Opening a file3. Reading from a file4. Writing data into a file5. Closing a file

    Real life situations involve large volume of data and in such cases, the console oriented I/Ooperations pose two major problems

    It becomes cumbersome and time consuming to handle large volumes of data throughterminals.

    The entire data is lost when either the program is terminated or computer is turned off

    therefore it is necessary to have more flexible approach where data can be stored on the disksand read whenever necessary, without destroying the data. This method employs the conceptof files to store data.

    File operation functions in C:

    Function Name Operation

    fopen() Creates a new file for use

    Opens a new existing file for use

    fclose Closes a file which has been opened for use

    39

    http://en.wikipedia.org/wiki/Computer_programhttp://en.wikipedia.org/wiki/Computer_programhttp://en.wikipedia.org/wiki/Computer_storagehttp://en.wikipedia.org/wiki/Computer_programhttp://en.wikipedia.org/wiki/Computer_storage
  • 8/6/2019 Computer Pratices Lab II (GE 27)

    40/46

    COMPUTER PRATICES LAB II 201

    0

    getc() Reads a character from a file

    putc() Writes a character to a file

    fprintf() Writes a set of data values to a file

    fscanf() Reads a set of data values from a file

    getw() Reads a integer from a file

    putw() Writes an integer to the file

    fseek() Sets the position to a desired point in the file

    ftell() Gives the current position in the file

    rewind() Sets the position to the begining of the file

    Defining and opening a file:

    In order to store data in a file into the secondary memory, certain things must be specified

    about the file to the operating system. They include the fielname, data structure, and purpose. The

    general format of the function used for opening a file is

    FILE *fp;

    fp=fopen(filename,mode);

    The first statement declares the variable fp as a pointer to the data type FILE. As stated

    earlier, File is a structure that is defined in the I/O Library. The second statement opens the file namedfilename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the

    40

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    41/46

    COMPUTER PRATICES LAB II 201

    0

    information about the file, is subsequently used as a communication link between the system and the

    program. The second statement also specifies the purpose of opening the file. The mode does this job.

    Ropen the file for read only.W opens the file for writing only.

    A open the file for appending data to it.

    Consider the following statements:

    FILE *p1, *p2;

    p1=fopen(data,r);

    p2=fopen(results,w);

    In these statements the p1 and p2 are created and assigned to open the files data and results

    respectively the file data is opened for reading and result is opened for writing. In case the results filealready exists, its contents are deleted and the files are opened as a new file. If data file does not existerror will occur.Closing a file:

    The input output library supports the function to close a file; it is in the following format.

    fclose(file_pointer);

    A file must be closed as soon as all operations on it have been completed. This would close

    the file associated with the file pointer.

    Observe the following program

    .

    FILE *p1 *p2;

    p1=fopen (Input,w);p2=fopen (Output,r);..

    ..

    fclose(p1);

    fclose(p2);

    The above program opens two files and closes them after all operations on them arecompleted, once a file is closed its file pointer can be reversed on other file.getc and putc functions:

    The getc and putc functions are analogous to getchar and putchar functions and handle one

    character at a time. The putc function writes the character contained in character variable c to the file

    associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from

    a file that has been open in read mode. c=getc(fp2).

    The getw and putw functions:

    41

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    42/46

    COMPUTER PRATICES LAB II 201

    0

    These are integer-oriented functions. They are similar to get c and putc functions and are used

    to read and write integer values. These functions would be usefull when we deal with only integer

    data. The general forms of getw and putw are:

    putw(integer,fp);

    getw(fp);

    The fprintf & fscanf functions:

    The fprintf and scanf functions are identical to printf and scanf functions except that theywork on files. The first argument of theses functions is a file pointer, which specifies the file to beused. The general form of fprintf is

    fprintf(fp,control string, list);

    Where fp id a file pointer associated with a file that has been opened for writing. The controlstring is file output specifications list may include variable, constant and string.

    fprintf(f1,%s%d%f,name,age,7.5);

    Here name is an array variable of type char and age is an int variable .The general format of

    fscanf is

    fscanf(fp,controlstring,list);

    This statement would cause the reading of items in the control string.

    Example:fscanf(f2,5s%d,item,&quantity);

    Like scanf, fscanf also returns the number of items that are successfully read.

    Random access to files:

    Sometimes it is required to access only a particular part of the and not the complete file. This

    can be accomplished by using the fseek function.

    fseek function:

    The general format of fseek function is a s follows:

    fseek(file pointer,offset, position);

    This function is used to move the file position to a desired location within the file. Fileptris a pointer to the file concerned. Offset is a number or variable of type long, and position in aninteger number. Offset specifies the number of positions (bytes) to be moved from the locationspecified bt the position. The position can take the 3 values.

    Value Meaning

    0 Beginning of the file

    1 Current file

    2 End of the file

    42

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    43/46

    COMPUTER PRATICES LAB II 201

    0

    Ex.No: 8a Display the Contents in a File

    Aim

    To write a C program to display the contents available in a file.

    Algorithm

    1. Read the file to be displayed.

    2. The file to be read is opened in read mode.

    3. Read the contents of the file character by character.

    4. Print the characters read.

    5. Close the file when all its contents are read.

    Program#include

    main()

    {

    FILE *fopen(),*fp;

    int c;

    fp=fopen("Read_File","r");

    c=getc(fp);while(c!=EOF)

    {

    putchar(c);

    c=getc(fp);

    }

    fclose(fp);

    }

    Result

    Thus the C program to read the contents available in a file was written successfully and the

    output was verified.

    43

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    44/46

    COMPUTER PRATICES LAB II 201

    0

    Ex.No: 8b Reversing a File

    Aim

    To write a C program to read the contents available in a file and to reverse it.

    Algorithm

    1. Read the file whose content is to be reversed in read mode.2. Open another file in write mode in to which the reversed information is to be written.

    3. Move the file pointer to the end of the file whose contents is to be reversed using the

    function fseek().

    4. Bring the position back to the last but one character in the file.

    5. The function getc() is used to read the next character and after reading, the file

    pointer is incremented to the next position.

    6. The output thus obtained is displayed in the screen.

    Program

    #include

    main()

    {

    char ch;

    FILE *fp1,*fp2;

    fp1=fopen("Input_File","r");

    fp2=fopen("Output_File","w");

    fseek(fp1,0,2);while(fseek(fp1,-2,1)==0)

    {

    ch=getc(fp1);

    44

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    45/46

    COMPUTER PRATICES LAB II 201

    0

    putchar(ch);

    putc(ch,fp2);

    }

    }

    Result

    Thus the C program to reverse the contents available in a file was written successfully and the

    output was verified.

    Ex.No: 8c Transpose Matrix

    Aim

    To write a C program to find the transpose of a matrix and to write into a file.

    Algorithm

    1. Initialize a matrix.

    2. Open a file write mode into which the transpose matrix is to be written.

    3. Perform transpose of a matrix and write the contents into the opened file.

    4. The transpose of the matrix is written into the file.

    Program

    #include

    main()

    {

    int i,j;

    int matrix[2][3]={{1,2,3},{4,5,6}};

    FILE *fp;

    fp=fopen("matrix","w");

    fprintf(fp,"\t \n Transpose of the given matrix \n");

    for(i=0;i

  • 8/6/2019 Computer Pratices Lab II (GE 27)

    46/46

    COMPUTER PRATICES LAB II 201

    0

    fprintf(fp,"\t%d\t",matrix[j][i]);

    fprintf(fp,"\n");

    }

    }

    Result

    Thus the C program to write the transpose of a matrix into a file was written successfully and

    the output was verified.