0% found this document useful (0 votes)
111 views55 pages

Programming in C Lab Manual (2019-20)

Uploaded by

Bindu Thomas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views55 pages

Programming in C Lab Manual (2019-20)

Uploaded by

Bindu Thomas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

EDUCATION IS DEDICATION

(Approved by AICTE, New Delhi & Affiliated to KTU)


P.B.No - 17,Kodakara Post, Thrissur District, Kerala – 680 684.

____________________________________________________________________
VISION: “Evolve as a leading technology institute to create high caliber leaders
and innovators of global standing with strong ethical values to serve the industry
and society.”.

MISSION: “Provide quality technical education that transforms students to be


knowledgeable, skilled, innovative and entrepreneurial professionals.
Collaborate with academia and industry around the globe, to strengthen the
education and research ecosystem.
Practice and promote high standards of professional ethics, good discipline, high
integrity and social accountability with a passion for holistic excellence.”.
Department of Computer Science and
Engineering

Subject Name: EST102 Programming in C


Department of Students: CSE, CE
Semester: II

PreparedBy: ApprovedBy:

Livya George Dr. M. Rajeswari


Asst. Professor HOD
CSE Dept. CSE Dept.

3
PEO's and PSO's

PEO1
Apply the acquired knowledge and skills in Civil Engineering to become
successful and competent professions, capable of contributing effectively to
the domain of civil Engineering and to cater to the needs of the society.

PEO2
Demonstrate leadership qualities in the execution and management of Civil
Engineering projects, upholding professional ethics and sustainability
concepts.

PEO3
Engage in lifelong learning with a quest to keep abreast with the latest
developments in Civil Engineering practice.

PSO1
Apply knowledge in technical areas appropriate to Civil Engineering,
including but not limited to structural, Geotechnical, Transportation, Geo-
informatics, Environmental, and Water Resources Engineering.

PSO2
Design a system, component, or process to meet desired needs within realistic
constraints such as economic, environmental, social, political, ethical, health
and safety, manufacturability, and sustainability.

PSO3
Familiarise with various facets of construction and its planning like project
scheduling, resource and material management, understand the impact of
engineering solutions in a global, economic, environmental, and societal
contexts.

5
Experiment List

Ex
Page
p Experiment Name
No.
No.
1 Familiarization of Hardware Components of a Computer 2
2 Familiarization of Linux environment – How to do Programming in C with Linux
Familiarization of console I/O and operators in C
i) Display “Hello World”
3 ii) Read two numbers, add them and display theirsum
iii) Read the radius of a circle, calculate its area and display it
iv)Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g)) and display its solution
4 Read the values of the variables from the user through console
5 Read 3 integer values and find the largest amoung them
6 Read a Natural Number and check whether the number is prime or not 6
7 Read a Natural Number and check whether the number is Armstrong or not 7
8 Read n integers, store them in an array and find their sum and average 8
Read n integers, store them in an array and search for an element in the array using an
9
algorithm for Linear Search
Read n integers, store them in an array and sort the elements in the array using Bubble Sort
10
algorithm
11 Read a string (word), store it in an array and check whether it is a palindrome word or not
Read two strings (each one ending with a $ symbol), store them in arrays and concatenate
12
them without using library functions
Read a string (ending with a $ symbol), store it in an array and count the number of
13
vowels, consonants and spaces in it
Read two input each representing the distances between two points in the Euclidean space,
14
store these in structure variables and add the two distance values
15 Using structure, read and print data of n employees (Name, Employee Id and Salary)
Declare a union containing 5 string variables (Name, House Name, City Name, State and
16 Pin code) each with a length of C_SIZE (user defined constant), Then, read and display the
address of a person using a variable of the union
17 Find the factorial of a given Natural Number n usingrecursive and non recursive functions
Read a string (word), store it in an array and obtain its reverse by using a user defined
18
function
Write a menu driven program for performing matrix addition, multiplication and finding
19 the transpose Use functions to (i) read a matrix, (ii) find the sum of two matrices, (iii) find
the product of two matrices, (i) find the transpose of a matrix and (v) display a matrix
Do the following using pointers i)add two numbers ii)swap two numbers using a user
20
defined function
21 Input and Print the elements of an array using pointers 21
22 Compute sum of the elements stored in an array using pointers and user defined function
Create a file and perform the following iii)Write data to the file iv)Read the data in a given
23
file & display the file content on console v)append new data and display on console
Open a text input file and count number of characters, words and lines in it; and store the
24
results in an output file

7
9
11
EXPERIMENT # 1
FAMILIARIZATION OF HARDWARE COMPONENTS OF A COMPUTER
AIM : Familiarization of Hardware Components of a Computer

THEORY :

Components of Computer Hardware


The computer system hardware comprises of three main components —
1. Input/Output (I/O) Unit,
2. Central Processing Unit (CPU), and
3. Memory Unit.
The I/O unit consists of the input unit and the output unit. CPU performs calculations and
processing on the input data, to generate the output. The memory unit is used to store the data,
the instructions and the output information. Figure 1.14 illustrates the typical interaction among
the different components of the computer.

Figure 1.14 The computer system interaction

Input/Output Unit : The user interacts with the computer via the I/O unit. The Input unit accepts
data from the user and the Output unit provides the processed data i.e. the information to the user.
The Input unit converts the data that it accepts from the user, into a form that is understandable by
the computer. Similarly, the Output unit provides the output in a form that is understandable by the
user. The input is provided to the computer using input devices like keyboard, trackball and
mouse. Some of the commonly used output devices are monitor and printer.

13
Central Processing Unit : CPU controls, coordinates and supervises the operations of the
computer. It is responsible for processing of the input data. CPU consists of Arithmetic Logic Unit
(ALU) and Control Unit (CU).
o ALU performs all the arithmetic and logic operations on the input data.
o CU controls the overall operations of the computer i.e. it checks the sequence of execution of
instructions, and, controls and coordinates the overall functioning of the units of computer.
Additionally, CPU also has a set of registers for temporary storage of data, instructions, addresses
and intermediate results of calculation.

Memory Unit: Memory unit stores the data, instructions, intermediate results and output,
temporarily, during the processing of data. This memory is also called the main memory or primary
memory of the computer. The input data that is to be processed is brought into the main memory
before processing. The instructions required for processing of data and any intermediate results are
also stored in the main memory. The output is stored in memory before being transferred to the
output device. CPU can work with the information stored in the main memory. Another kind of
storage unit is also referred to as the secondary memory of the computer. The data, the programs
and the output are stored permanently in the storage unit of the computer. Magnetic disks, optical
disks and magnetic tapes are examples of secondary memory.

EXPECTED OUTPUT : studied the components of Computer

15
EXPERIMENT # 2
FAMILIARIZATION OF LINUX ENVIRONMENT – HOW TO DO
PROGRAMMING IN C WITH LINUX

AIM : Familiarization of Linux environment – How to do Programming in C with Linux

THEORY :
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or more
text
files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to
write your C program into a file.
Basic concepts of a c program
Before we study basic building blocks of the C programming language, let us look a bare
minimum C program structure so that we can take it as a reference in upcoming chapters.
C Hello World Example
A C program basically consists of the following parts:
 Preprocessor Commands Preprocessor Commands
 Preprocessor Commands Functions
 Preprocessor Commands Variables
 Preprocessor Commands Statements & Expressions
 Preprocessor Commands Comments
Let us look at a simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us look various parts of the above program:
1. The first line of the program #include <stdio.h> is a preprocessor command, which tells a C
compiler to
include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in
the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates main()function and returns the value 0.

17
Compile & Execute C Program:
Lets look at how to save the source code in a file, and how to compile and run it. Following are the
simple steps:
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you saved the file.
4. Type gcc hello.c and press enter to compile your code.5. If there are no errors in your code the
command prompt will take you to the next line and would generate
a.out executable file.
6. Now, type a.out to execute your program.
7. You will be able to see "Hello World" printed on the screen.

EXPECTED OUTPUT : studied and understood the procedure for compiling and executing C
program.

19
EXPERIMENT # 3
FAMILIARIZATION OF CONSOLE I/O AND OPERATORS IN C

AIM : Familiarization of console I/O and operators in C


i) Display “Hello World”
ii) Read two numbers, add them and display theirsum
iii) Read the radius of a circle, calculate its area and display it
iv)Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g)) and display its
solution.Read the values of the variables from the user through console.

THEORY :

C - Input & Output


When we are saying Input that means to feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in functions to
read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer
screen
as well as you can save that data in text or binary files.

The scanf() and printf() functions


The int scanf(const char *format, ...) function reads input from the standard input stream stdin and
scans that input according to format provided. The int printf(const char *format, ...) function
writes output to the standard output stream stdout and produces output according to a format
provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to
print or read strings, integer, character or float respectively. There are many other formatting
options available
which can be used based on requirements. For a complete detail you can refer to a man page for
these function. For now let us proceed with a simple example which makes things clear:
#include <stdio.h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text when you enter
a
text and press enter then program proceeds and reads the input and displays it as follows:

21
$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expect input in the same format as you provided %s and %d,
which means you have to provide valid input like "string integer", if you provide "string string" or
"integer integer" then it will be assumed as wrong input. Second, while reading a string scanf()
stops
reading as soon as it encounters a space so "this is test" are three strings for scanf().

Expressions
An expression in a programming language is a combination of explicit values, constants, variables,
operators, and functions that are interpreted according to the particular rules of precedence and of
association for a particular programming language, which computes and then produces (returns, in
a stateful environment) another value.This process, like for mathematical expressions, is called
evaluation. The value can be of various types, such as numerical, string, and logical.
For example, 2+3 is an arithmetic and programming expression which evaluates to 5. A variable is
an expression because it denotes a value in memory, so y+6 is an expression. An example of a
relational expression is 4≠4, which evaluates to false.
In C and most C-derived languages, a call to a function with a void return type is a valid
expression, of type void. Values of type void cannot be used, so the value of such an expression is
always thrown away.

Operators
Arithmetic Operators
Arithmetic operators are shown in the following table. Arithmetic operators are used to perform
arithmetic operations in c programming.

Relational Operators
 Preprocessor Commands The relational operators are binary operators -- they work between two values
 Preprocessor Commands The relational operators and their meanings:
== equal to
> greater than
>= greater than or equal
< less than
<= less than or equal
!= not equal to

Use of the Relational Operators


 Preprocessor Commands A relational operator tests data values against one another
 Preprocessor Commands You can only compare similar data types. (It makes no sense to compare a char to a float.)
 Preprocessor Commands All relational operators return either a 1 (meaning true) or a 0 (false.)
 Preprocessor Commands You will use the relational operators to test whether a condition is true or false and act
accordingly.Some Examples
Given the following C declarations:
23
int a =1, b = 2, c = 3, d = 1;
 Preprocessor Commands a == d is true
 Preprocessor Commands c > b is true
 Preprocessor Commands c >= b is true
 Preprocessor Commands a >= c is false
 Preprocessor Commands a != d is false
 Preprocessor Commands a <= d is true

Logical Operators
 Preprocessor Commands You can combine relational operators using logical operators
 Preprocessor Commands C’s logical operators are:
 Preprocessor Commands && (AND) returns true if and only if both operands are true
 Preprocessor Commands || (OR) returns true if one or both operands are true
 Preprocessor Commands ! (NOT) returns true if operand is false and false if operand is true

Assignment Operators
There are following assignment operators supported by C language:

=, +=, -=, *=, /=, %=

Example :
A+=2 is equivalent to A=A+2

The Conditional Operator in C


The conditional operator in C is also known as ternary operator. It is called ternary operator
because it takes three arguments. The conditional operator evaluates an expression returning a
value
if that expression is true and different one if the expression is evaluated as false.
condition ? result1 : result2;10==5 ? 11: 12; // returns 12, since 10 not equal to 5.
10!=5 ? 4 : 3; // returns 4, since 10 not equal to 5.
12>8 ? a : b; // returns the value of a, since 12 is greater than 8.
/*Conditional operator*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b = 11;
int c;
c = (a < b)? a : b;
printf(“%d”, c);
}

25
Precedence and order of evaluation in c
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Example
Try the following example to understand the operator precedence available in C programming
language:
#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
When you compile and execute the above program it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

ALGORITHM :

i) Display “Hello World”

Step 1: Start
step 2: display “Hello World”
Step 3: stop

27
ii) Read two numbers, add them and display their sum
Step 1 : Start
Step2 : read a,b
Step 3 : c= a+b
step 4 : display c
step 5 : stop

iii) Read the radius of a circle, calculate its area and display it
Step 1 : Start
Step2 : read r
step 3: A=3.14* r*r
step 4: display A
step 5 : stop

iv)Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g)) and display its solution.Read the
values of the variables from the user through console.
Step 1 : Start
Step2 : read a,b,c,d,e,f,g
step 3: A=((a -b / c * d + e) * (f +g))
step 4: display A
step 5 : stop

EXPECTED OUTPUT :

i) Hello World
ii) 2
3
5
iii) 2
12.56
iv)1
1
1
1
1
1
1
2

29
EXPERIMENT # 4
IF : LARGEST

AIM : Read 3 integer values and find the largest amoung them

THEORY : There are simple linear or straight-line programs where the program flow was fairly
straight forward: Give the user directions, ask the user for data, perform a few calculations based
on those data and then print out appropriate results. The next level up in sophistication is the
concept of branching. That is, the execution path through the code can vary depending on certain
conditions. You might think of this as the program making decisions to do one thing or another.
The fundamental conditional operation is the if statement. It looks something like this:
if (conditional expression)
{
resulting statements to be executed;
}
The conditional expression is some manner of test, for example to see if one variable
is larger than another. The tests include = = (same as), != (not same as), >, <, >= and <=. The
logical directives 'and' and 'or' are also available. The resulting action is any legal block of C
code. It may be a single line or a multitude of lines. So, if the conditional expression is true,
the resulting action is performed. If the expression is not true, the action is skipped. In either
case, program execution picks up at the next line after the resulting action block.
As an example, suppose we’d like to test to see if variable A is larger than variable B.
If it is, we’d like to print out the message: “It’s bigger”. After this, we want to print out the
message “Done”, whether or not A waslarger.

if (A > B)
{
printf( “It’s bigger” );
}
printf( “Done” );

Because of the second print statement is not part of the block, it is always executed. A
common beginner’s syntax error is to forget the semicolon at the end of each statements.
If multiple conditions need to be met together, they may be handled with successive tests, as
in: if (conditional expression)
{
if (conditional expression 2)
{
statements to be executed;
}
}
31
This idea can be cascaded on and on. Failure to use the curly braces correctly, will
ruin the statement block hierarchy and lead to unpredictable code execution (or syntax
errors).
The easiest way around this is to make use of the logical operators && and ||. These
are used to make compound tests. The logical and operator is used to make test which
require all parts of the expression to be true while the or operator is used when at least one
part needs to be true.
Ex:
if ((A > B )&&( A < C))
{
printf( “It’s just right!” );
}

ALGORITHM :
Step 1: Start
Step 2: Read/input A,B and C
Step 3: If (A>=B) and (A>=C) then Print A go to step 7
Step 4: If (A>=B) and (A<C) then Print C go to step 7
Step 5: If (A<B) and (B>=C) then Print B go to step 7
Step 6 : If (A<B) and (B<C) then Print C go to step 7
Step 7 : stop
FLOWCHART ;

EXPECTED OUTPUT : If the user give three numbers, the largest one will be displayed.

33
EXPERIMENT # 5
LOOP : PRIME NUMBER

AIM : Read a Natural Number and check whether the number is prime or not

THEORY :
The ability to repeat a series of instructions with controlled variance is an extremely
powerful computing tool. There are a few different ways to do this in C, each with their own
strengths.
The first loop control structure is the while loop. At first glance this looks something
like an ifstatement:
while (controlexpression)
statementblock
The statement block, which might be many lines long, will be repeated as long as the
control expression is true. Like the if statement, this block must be indented. The control
expression is basically the same as those used in if statements: They tend to be simple
variable tests. Further, it is important that one or more of the variables used in the control
expression change during the looping process otherwise the loop will try to run forever.
For example:

x=1
while (x<10)
{
printf(“%d”, x );
}
The first time the while loop is entered, x is checked to see if it is less than 10, which it is.
Consequently, the print statement is executed and the value 1 is printed. This is the last statement
of the block so program flow loops back to the control expression. x is checked again to see if it’s
less than 10. It is, so the print statement will be executed again. Because x never changes, this
loop never stops. The result of this bit of code is the number 1 printed over and over and over, not
stopping until the program is aborted (if this happens accidentally, a loop may be aborted by
holding down the Ctrl key and pressing the C key).
Consider this change:

x=1
while (x<10)
{
print(
x )x=x
+1
}

35
Now x is incremented by 1 each time through the loop. On the tenth time starting the
loop the test will fail because x will no longer be less than 10 (it will equal 10). The loop
terminates and program flow picks up at the first line after the loop’s statement block. It is
also possible to use the and and or operators in order to check for multiple conditions.

A second technique to create a loop is through the for statement. The template looks
similar to the while structure:
for (intialization;conditional expr;increment/ decrement)
{
statement block;
}
Value list can be a simple listing of values such as:

for (x=1;x<5;x++)
{
printf(“%d”,x);
}
This loop will execute four times. The first time through x will take on the value 1,
the second time 2, the third time 3, and 4 for the final iteration. This is very convenient if a
variable needs to cycle through a set ofvalues.
ALGORITHM : FLOWCHART :
Step 1 : Start
Step2: [Read the number] read n
Step 3 : flag =0
Step 4 : for i= 2 to n/2 in step1
if((n/i)*i ==n)
display not prime
flag =1
Step 5: if flag is equal to 0 display prime
Step 6 : stop

EXPECTED OUTPUT :
$./a.out
13
13 is prime
$./a.out
4
4 is not prime

37
EXPERIMENT # 6
LOOP : ARMSTRONG NUMBER

AIM : Read a Natural Number and check whether the number is Armstrong or not

THEORY : Same as Experiment 5

ALGORITHM : FLOWCHART :
Step 1: Start
Step 2: Declare Variable sum, temp, num
Step 3: Read num from User
Step 4: Initialize Variable sum=0 and
temp=num
Step 5: Repeat Until num>=0
5.1 sum=sum + cube of last digit
i.e [(num%10)*(num%10)*(num%10)]
5.2 num=num/10
Step 6: IF sum==temp Print "Armstrong No."
ELSE Print "Not Armstrong No."
Step 7: Stop

EXPECTED OUTPUT :
$./a.out
153
153 is armstrong number
$./a.out
450
450 is not armstrong number

39
EXPERIMENT # 7
ARRAY : SUM

AIM : Read n integers, store them in an array and find their sum and average

THEORY :

ALGORITHM : FLOWCHART :
Step 1 : Start
Step 2 : Assign sum=0 and i=0
Step 3 : Read limit of number , n
Step 4 : Repeat steps 5 to 7 until i=n reached
Step 5 : Read num
Step 6 : Compute sum=sum+num
Step 7 : Compute i=i+1
Step 8 : Print sum
Step 9 : Stop

EXPECTED OUTPUT : Given n and n numbers


the sum and average are printed.

41
EXPERIMENT # 8
ARRAY : LINEAR SEARCH

AIM : Read n integers, store them in an array and search for an element in the array using an
algorithm for Linear Search

THEORY :

ALGORITHM : FLOWCHART ;
Step 1: Input Key
Step 2: Index = 0
Step 3: While (Index< SizeofArray)
If (Array[Index]== Key)
PrintKey Found at Location
goto Step6
Index++
Step 4: If (Index== SizeofArray)
Step 5: Print Key Not Found
Step 6: End

EXPECTED OUTPUT :
If the key is in the array then the position will be returned and if the key is not present in
the array then “print key not found”.

43
EXPERIMENT # 9
ARRAY : BUBBLE SORT

AIM : Read n integers, store them in an array and sort the elements in the array using Bubble Sort
algorithm

THEORY :Bubble sort

ALGORITHM :
Step 1: [Start]
Begin
Step 2: [Input the number of elements in the array] Read n
Step 3: [Input the n integer numbers]
For i =-1 in steps of 1
Read num[ i ]
End for
Step 4: [Display the original array]
For i = 0 through n-1 in steps of 1 Print num[ i]
End for
Step 5: [Repeat step 5 for i varies from 0 thru n-1]
For i=0 through n-1 in steps of 1
For j = 0 through n-i-1 in steps of 1
IF ( num[j] > num[j + 1] )
then temp= num[j]
num[j] = num[j + 1] num[j+1] = temp
Endif
End for
End for
Step 6: [Output the sorted array]
For i = 0 through n-1 in steps of 1
Print num[i]
End for
45
FLOWCHART :

EXPECTED OUTPUT :
Given an unsorted array, the sorted array gets printed.

47
EXPERIMENT # 10
STRING : PALINDROME
AIM : Read a string (word), store it in an array and check whether it is a palindrome word or not

THEORY :

a word or phrase the letters of which, when taken in reverse order, give the same word or
phrase, such as “able was I ere I saw Elba”

The word is taken in an array. The characters of first and last, next and last but one ,etc..
need to be checked until the middle of string. If whole comparison results in true then the string is
a palindrome else it is not a palindrome.

49
ALGORITHM :
Step 1: Input S (string)
Step 2: Len = 0 , Flag =0
Step 3: While (S[Len]!= NULL)
Len++
Step 4: I = 0 ,J = Len-1
Step 5: While ( I< (Len/2)+1 )
If ( S[I]== S[J] )
Flag=0
else
Flag=1
I++ , J–
Step 6: If ( Flag == 0 )
Print Key Is a Palindrome
else
Print Key Is Not a Palindrome
Step 7: End

FLOWCHART :

EXPECTED OUTPUT :
If the string is palindrome display “Palindrome” else display “Not a Palindrome”

51
EXPERIMENT # 11
STRING : CONCATENATE

AIM : Read two strings (each one ending with a $ symbol), store them in arrays and concatenate
them without using library functions

THEORY :

In C programming, a string is a sequence of characters terminated with a null character \0.


For example:
char c[] = "c string";

When the compiler encounters a sequence of characters enclosed in the double quotation marks, it
appends a null character \0 at the end by default.

How to declare a string?

Here's how you can declare strings:


char s[5];

Here, we have declared a string of 5 characters.


How to initialize strings?

You can initialize strings in a number of ways.


char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

53
Let's take another example:
char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5
characters. This is bad and you should never do this.
Read String from the user

You can use the scanf() function to read a string.


The scanf() function reads the sequence of characters until it encounters whitespace (space, newline,
tab etc.).
Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output
Enter name: Dennis Ritchie
Your name is Dennis.

Even though Dennis Ritchie was entered in the above program, only "Ritchie" was stored in the
name string. It's because there was a space after Dennis.
How to read a line of text?

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
Example 2: fgets() and puts()

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

55
Output
Enter name: Tom Hanks
Name: Tom Hanks

Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is
the size of the name string.
To print the string, we have used puts(name);.
Note: The gets() function can also be to take input from the user. However, it is removed from the C
standard. It's because gets() allows you to input any length of characters. Hence, there might be a
buffer overflow.

ALGORITHM : FLOWCHART :

Step 1 : Start
Step 2 : read str1 and str2
Step 3 : i=0
Step 4 : if str1[i]!=’\0’
i=i+1 go to step 4
Step 5 : j=0
Step 6 : if str2[j]!=’\0’
str1[i]=str2[j]
i=i+1
j=j+1
goto step 6
Step 7 : print str1
Step 8 : Stop

EXPECTED OUTPUT :
$./a.out
abcd$
efgh$
The concatenated string is abcd$efgh$

57
EXPERIMENT # 12
STRING : COUNTING VOWELS, CONSONANTS AND SPACES

AIM : Read a string (ending with a $ symbol), store it in an array and count the number of vowels,
consonants and spaces in it

THEORY : same as experiment 11

ALGORITHM :
Step 1 : start
Step 2 : read string str1
Step 3 : i=0,vcnt=0, ccnt=0,scnt=0
Step 4 : if str1[i]!=’\0’
Step 4.1 : if str1[i] = a or A or e or E or i or I or o or O or u or U
Step 4.1.1 : vcnt=vcnt+1 go to step 4.4
Step 4.2 : if str1[i]=” “
Step 4.2.1 : scnt = scnt+1 go to step 4.4
Step 4.3 : ccnt= ccnt+1
step 4.4 : i=i+1 go to step 4
Step 5 : print vcnt, ccnt, scnt
Step 6 : stop

FLOWCHART :

59
EXPECTED OUTPUT : $./a.out
Enter a String :i am a student
vcnt = 5 , ccnt =6 , scnt =3

61
EXPERIMENT # 13
STRUCTURES : EUCLIDEAN DISTANCE

AIM : Read two input each representing the distances between two points in the Euclidean space,
store these in structure variables and add the two distance values

THEORY :
Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly structure is another user defined data type available in C that allows to
combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book −

• Title
• Author
• Subject
• BookID

Defining a Structure

To define a structure, you must use thestructstatement. The struct statement defines a
new data type, with more than one member. The format of the struct statement is as follows −
struct [structure tag]
{ member
definition;
member
definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of the
structure's definition, before the final semicolon, you can specify one or more structure
variables but it is optional. Here is the way you would declare the Book structure :
struct Books
{ char
title[50];
charauthor[50]
;

63
char
subject[100]; int
book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and the
structure member that we wish to access. You would use the keywordstructto define variables
of structuretype.
Euclidean distance
Let us take two points which is stored in two structures. We will use the distance formula
derived from Pythagorean theorem. The formula for distance between two point (x1, y1) and (x2,
y2) is

Distance =

ALGORITHM : FLOWCHART :
Step 1 : start
Step 2: [declare a structure point] struct point having
two members x,y
Step 3 : create two points p1 and p2
step 4 : calculate the Euclidean distance using the above
formula (acess the x1 as p1.x, etc)
Step 5 : print Distance
Step 6 : Stop

EXPECTED OUTPUT :
Input : x1, y1 = (3, 4)
x2, y2 = (7, 7)
Output : 5

Input : x1, y1 = (3, 4)


x2, y2 = (4, 3)
Output : 1.41421

65
EXPERIMENT # 14
STRUCTURES : EMPLOYEE DATA

AIM : Using structure, read and print data of n employees (Name, Employee Id and Salary)

THEORY : same as experiment 13

ALGORITHM : FLOWCHART :

Step 1 : [declare a structure Employee]


struct Employee with Name,
Employee Id and Salary

Step 2 : Enter number of employees as n

Step 3 : create array of structure employee


st

Step 4 : for i =0 through n-1

Input data as st[i].Name,


st[i].eID and st[i].Salary

Step 5 : for i =0 through n-1

display data as st[i].Name,


st[i].eID and st[i].Salary found

Step 6 : Stop

EXPECTED OUTPUT :
The structure array accepts the employee details and then it is displayed

67
EXPERIMENT # 15
UNION

AIM : Declare a union containing 5 string variables (Name, House Name, City Name, State and
Pin code) each with a length of C_SIZE (user defined constant), Then, read and display the
address of a person using a variable of the union

THEORY :
A union is a special data type available in C that allows to store different data types in the
same memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows :
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the union's definition, before
the final semicolon, you can specify one or more union variables but it is optional. Here is the way
you would define a union type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in the above example, Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by a character string. The following
example displays the total memory size occupied by the above union :

69
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result :
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union member that
we wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program :

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}
When the above code is compiled and executed, it produces the following result :

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
71
Here, we can see that the values of i and f members of union got corrupted because the
final value assigned to the variable has occupied the memory location and this is the reason that
the value of str member is getting printed very well.

Now let's look into the same example once again where we will use one variable at a time
which is the main purpose of having unions −

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

return 0;
}

When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a
time.

73
ALGORITHM : FLOWCHART :
Step 1 : Start
Step 2 : define C_SIZE
Step 3 : [declare a union person] union
person with Name, House
Name, City Name, State and Pin
code of size C_SIZE
Step 4 : create union st

Step 5 : Input and display data as st.Name,


st.HouseName, st.CityName,
st.State and st.Pincode

Step 6 : Stop

EXPECTED OUTPUT :
Reads the person’s address and displays the same.

75
EXPERIMENT # 16
RECURSIVE FUNCTIONS : FACTORIAL

AIM : Find the factorial of a given Natural Number n usingrecursive and non recursive functions

THEORY : Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}

The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise
it will go into an infinite loop.Recursive functions are very useful to solve many mathematical
problems, such as calculating the factorial of a number, generating Fibonacci series, etc.
ALGORITHM : FLOWCHART ;

Step1. [Read integer n]


Step 2.[check if the number is
negative] if (n < 0)
output Negative integers are not
allowed return 0;
Step 3.[call the function
factorial] f =
factorial(n);
Step 4.Output factorial of n
i.e f Step 5.Stop
factorial(n)
Step 1.if (n =0)
return1;
Step 2.[call function recursively till base
condition] return(n * factorial(n-1));

EXPECTED OUTPUT :
Enter the value of n : 63
Factorial of 6 = 720

77
EXPERIMENT # 17
USER DEFINED FUNCTIONS

AIM : Read a string (word), store it in an array and obtain its reverse by using a user defined
function
THEORY :
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions.
Defining a Function
The general form of a function definition in C programming language is as follows :
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of afunction headerand afunctionbody.
Here are all the parts of a function :
• Return Type− A function may return a value. Thereturn_typeis the datatype of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keywordvoid.
• Function Name− This is the actual name of the function. The function nameand the parameter
list together constitute the functionsignature.
• Parameters− A parameter is like a placeholder. When a function is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional; that
is, a function may contain noparameters.
• Function Body− The function body contains a collection of statementsthat define what the
functiondoes.
Example
Given below is the source code for a function calledmax(). This function takes two
parameters num1 and num2 and returns the maximum value between the two :

/* function returning the max between two numbers */


int max(int num1, int num2) {
intresult; /* local variable declaration*/
if (num1 >num2)
result = num1;
else
result = num2; return result;
}

79
ALGORITHM :
reverse algorithm : main :
Step 1 : start Step 1 : start
Step 2 : accept string in array s Step 2 : read string in array s
Step 3 : set i=0, j =string length-1 Step 3 : call reverse(s)
Step 4 : repeat if i<j Step 4 : display s
Step 4.1 : t = s[i] Step 5 : Stop
Step 4.2 : s[i] = s[j]
Step 4.3 : s[j] = tf
Step 5 : return the s
Step 6 : stop

FLOWCHART :

EXPECTED OUTPUT :

i am a student
tnedust a ma i

81
EXPERIMENT # 18
2D ARRAY

AIM : Write a menu driven program for performing matrix addition, multiplication and finding
the transpose Use functions to
(i) read a matrix,
(ii) find the sum of two matrices,
(iii) find the product of two matrices,
(iv) find the transpose of a matrix and
(v) display a matrix
THEORY :
Think of the two-dimensional array as a matrix. A matrix can be thought of as a grid of
numbers, arranged in rows and columns. We might write the two-dimensional array out as follows
to illustrate this point:
int[][] myArray = { {0, 1, 2,3},
{3, 2, 1,0},
{3, 5, 6,1},
{3, 8, 3, 4} };

To access the elements of array we indexit using myArray[indexrow][indexcolumn].


Ex: myArray[1][2] refers to element at second row and thirdcolumn.
The matrix multiplication is done with the logic given below :

Matrix Addition
As long as the dimensions of two matrices are the same, we can add and subtract them much
like we add and subtract numbers.
Given A=[4 3 and B= [ 1 5
8 7] 0 2 ], let's find A+B.
We can find the sum simply by adding the corresponding entries in matrices A and B. This is shown
below.
A+B = [4 3 + [1 5 = [ 5 8
8 7] 0 2] 8 9]

83
ALGORITHM (matrix addition): FLOWCHART(matrix addition) :

Step 1.[input the no. of rows and columns of


matrix a] read m,n
Step 2.[input the no. of rows and columns
of matrix b] read p,q
Step 3.[check the compatibility for addition
of matrices a and b]
if(m!=p and n!=q)
output matrix addition
is not possible goto step 10
else goto step 4
end if
Step 4.input the elements of matrix a
Step 5.input the elements of matrix b
Step 6.[perform addition of matrices
a and b]
for i=0 to m-1 in step 1
for j=0 to n-1 in step 1 sum=0
c[i][j]=a[i][j]+b[i][j]
end for
end for
Step 7.[output the matrix a]
Step 8.[output the matrix b]
Step 9.[output the resultant matrix c]
Step 10.Stop

85
ALGORITHM (matrix multiplication): FLOWCHART(matrix multiplication) :

Step 1.[input the no. of rows and columns


of
matrix a] read m,n
Step 2.[input the no. of rows and columns
of matrix b] read p,q
Step 3.[check the compatibility for
multipli-
cation of matrices a and b]
if(n!=p)
output matrix
multiplication
is not possible goto step 10
else goto step 4
end if
Step 4.input the elements of matrix a
Step 5.input the elements of matrix b
Step 6.[perform multiplication of matrices
a and b]
for i=0 to m-1 in step 1
for j=0 to q-1 in step 1
sum=0
for k=0 to n-1 in step 1
sum=sum+a[i]
[k]*b[k][j]
end for
c[i][j]=sum
end for
end for
Step 7.[output the matrix a]
Step 8.[output the matrix b]
Step 9.[output the resultant matrix c]
Step 10.Stop

EXPECTED OUTPUT :

Given two matrices using 2D array, a third matrix with the multiplied result is printed.
Given two matrices using 2D array, a third matrix with the added result is printed.

87
EXPERIMENT # 19
POINTERS

AIM : Do the following using pointers


i)add two numbers
ii)swap two numbers using a user defined function
THEORY :
As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes an address in
memory. Consider the following example, which prints the address of the variables defined −

#include<stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2) ;
return 0;
}

When the above code is compiled and executed, it produces the following result :
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is
type *var-name;

Here, typeis the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Take a look at some of the valid pointer declarations :
int *ip; /* pointer to an integer */

89
double*dp; /* pointer to a double*/
float *fp; /* pointer to a float*/
char* c h ; /* pointer to a character*/
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The only
difference between pointers of different data types is the data type of the variable or constant that
the pointer points to.

#include<stdio.h>
int main()
{
int x=10;
int *p=&x;
printf("*p = %d\n",*p);
printf("&x = %p\n",&x);
printf("p = %p\n",p);
printf("&p = %p\n",&p);
return 0;
}
Output :

ALGORITHM : FLOWCHART :
i)add two numbers
Step 1 : start
Step 2 : read a,b
Step 3 : create two pointers to a and b
Step 4 : sum=add using the pointers
Step 5 : display the sum
Step 6 : stop

91
ALGORITHM : FLOWCHART :
ii)swap two numbers using a user
defined function

Step 1 : start
Step 2 : read two numbers a,b
Step 3 : call swap(&a,&b)
Step 4 : display a,b
Step 5 : stop
swap(*p1,*p2)
step 1 : start
step 2 : t= *p1
step 3 : *p1=*p2
step4 : *p2=t
step 5 : return

EXPECTED OUTPUT :

i) enter first no. : 2


enter second no. : 3
sum : 5

ii) enter a : 2
enter b : 3
a = 2 and b = 3

93
EXPERIMENT # 20
ACCESSING ARRAYS USING POINTERS

AIM : Input and Print the elements of an array using pointers

THEORY : Consider these 2 kinds of int variables:

int i; // An integer variable


int a[10]; // An integer array

Illustrated:

Notice that:

• i is an int typed variable


• a[0] is an int typed variable
• a[1] is an int typed variable
• And so on...

• Therefore, we can use an int *p variable to access any one of these int typed
variables:

int *p;
p = &i;
//*p will access i
p = &a[0];
//*p will access a[0]
p = &a[1];
//*p will access a[1]

95
• Pointer arithmentic: the + operator on reference variables
• Definition: pointer addition

• The expression:
referenceVariable + integer
• evaluates (returns) to the address
referenceVariable + integer*sizeof( (*referenceVariable) )
Example:

• Initially, the variable p points to the variable a[0]:

int a[10];
int *p;

p = &a[0];

• Then the expression p + 1 will evaluates to:

p + 1 ===> &a[0] + 1*sizeof( (*p) ) // (*p) is an int !


<===> &a[0] + 1*4
<===> &a[0] + 4

• The expression p + 2 will evaluates to:

p+2 ===> &a[0] + 1*sizeof( (*p) ) // (*p) is an int !


<===> &a[0] + 2*4
<===> &a[0] + 8

Example C program:

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


{
int a[10];
int *p;

p = &a[0]; // p points to variable a[0]

printf("p = %u, &a[%d] = %u\n", p, 0, &a[0] );


printf("p + 1 = %u, &a[%d] = %u\n", p+1, 1, &a[1] );
printf("p + 2 = %u, &a[%d] = %u\n", p+2, 2, &a[2] );
printf("p + 3 = %u, &a[%d] = %u\n", p+3, 3, &a[3] );
}

Output of C program:

p = 4290769444, &a[0] = 4290769444 (increased by 4 !!!)


p + 1 = 4290769448, &a[1] = 4290769448
p + 2 = 4290769452, &a[2] = 4290769452
p + 3 = 4290769456, &a[3] = 4290769456

97
ALGORITHM : FLOWCHART :
step 1 : start
step 2 : read no of elements in array in n
step 3 : create an array a of size n
step 4 : create pointer p pointing to a
step 5 : i=0
step 6 : read to *p
step 7 : i=i+1
step 8 : p=p+1
step 9 : if i<n go to step 6
step 10 : i=0
step 11 : display *p
step 12 : i=i+1
step 13 : p=p+1
step 14 : if i<n go to step 6
step 15 : stop

EXPECTED OUTPUT :
Enter n: 5
5
6
55
88
95
The entered elements in array is :
5
6
55
88
95

99
EXPERIMENT # 21
POINTERS, ARRAYS AND FUNCTIONS

AIM : Compute sum of the elements stored in an array using pointers and user defined function

THEORY : same as Experiment 20

ALGORITHM : FLOWCHART :
step 1 : start
step 2 : read no of elements in array (n)
step 3 : create an array a of size n
step 4 : create pointer p pointing to a
step 5 : i=0
step 6 : read to a[i]
step 7 : i=i+1
step 8 : if i<n go to step 6
step 9 : call sum(p)
step 10 : stop
sum(p)
step 1: start
step 2 : i=0, sum=0
step 3 : sum=sum+*p
step 4 : i=i+1
step 5 : p=p+1
step 6 : if i<n go to step 3
step 7 : display sum
step 8 : return

EXPECTED OUTPUT :
Enter n: 5
5
6
55
88
95
sum : 249

101
EXPERIMENT # 22
FILES
AIM : Create a file and perform the following i)Write data to the file ii)Read the data in a given
file & display the file content on console iii)append new data and display on console

THEORY :
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C
programming language provides access on high level functions as well as low level (OS level) calls
to handle file on your storage devices. This chapter will take you through the important calls for
filemanagement.
Opening Files
You can use thefopen( )function to create a new file or to open an existing file. This call will
initialize an object of the typeFILE, which contains all the information necessary to control the
stream. The prototype of this function call is as follows :
FILE *fopen( const char * filename, const char * mode );
Here, filenameis a string literal, which you will use to name your file, and accessmode
can have one of the following values :
r
Opens an existing text file for reading purpose.
w
Opens a text file for writing. If it does not exist, then a new file is created. Here your program will
start writing content from the beginning of the file.
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here
your program will start appending content in the existing file content.
r+
Opens a text file for both reading and writing.
w+
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists,
otherwise creates a file if it does not exist.
a+
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will
start from the beginning but writing can only beappended.

If you are going to handle binary files, then you will use following access modes instead of the
above mentioned ones :
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is :

103
int fclose( FILE *fp );
Thefclose() function returns zero on success, or EOF if there is an error in closing the file.
This function actually flushes any data still pending in the buffer to the file, closes the file, and
releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character
by character, or in the form of a fixed length string.
Writing a File
Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if there is an
error. You can use the following functions to write a null-terminated string to a stream :
int fputs( const char *s, FILE *fp );
The function fputs() writes the strings to the output stream referenced by fp. It returns a non-
negative value on success, otherwiseEOFis returned in case of any error. You can use
int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the
following example.
Make sure you have/tmpdirectory available. If it is not, then before proceeding, you must
create this directory on your machine.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new filetest.txt in /tmp directory
and writes two lines using two different functions. Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a single character from a file :
int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returnsEOF. The following function allows to read a
string from a stream :
char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It
copies the read string into the bufferbuf, appending a null character to terminate the string. If this
function encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point including the

105
new line character. You can also useint fscanf(FILE *fp, const char *format, ...) function to read
strings from a file, but it stops reading after encountering the first space character.
ALGORITHM : FLOWCHART :

i)Write data to the file


Step1 : open file using writing mode access using file pointer f1
step 2 : read data from user to s
step 3 : write the data s to f1
step 4 : Close the file f1

ii)Read the data in a given file & display


the file content on console
Step1 : open file using read mode
access using file pointer f1
step 2 : read data from f1 to s
step 3 : display s
step 4 : Close the file f1

iii) append new data and display on console


Step1 : open file using append mode access using file pointer f1
step 2 : read data from user to s
step 3 : append the data s to EOF of f1
step 4 : close f1
Step5 : open file using read mode access using file pointer f1
step 6 : read data from f1 to s
step 7 : display s
step 8 : Close the file f1

EXPECTED OUTPUT :
Read, write and append operation on files performed.

107
EXPERIMENT # 23
FILES : Count Char, Words and Lines

AIM : Open a text input file and count number of characters, words and lines in it; and store the
results in an output file

THEORY : same as experiment 22

ALGORITHM : FLOWCHART :
step 1 : start
step 2 : open file using read mode access using
file pointer f1
step 3 : read data from f1 to s
step 4 : for each character in s
step 4.1 : if c== “\n“ then lncnt =lncnt+1
step 4.2 : if c== “ ” then wdcnt=wdcnt+1
step 4.3 : charcnt=charcnt+1
step 5 : Close the file f1
step 6 : open f2 in writing mode
step 7 : write lncnt, wdcnt and charcnt in f2
step 8 : close f2
step 9 : stop

EXPECTED OUTPUT :

creates a file the linecount, word count and


character count of the given file.

109

You might also like