EST02 C LAB MANUAL
EST02 C LAB MANUAL
EST02 C LAB MANUAL
COURSE MATERIAL
• To become an ultimate destination for acquiring latest and advanced knowledge in the
multidisciplinary domains.
• To provide high quality education in engineering and technology through innovative
teaching-learning practices, research and consultancy, embedded with professional ethics.
• To promote intellectual curiosity and thirst for acquiring knowledge through outcome
based education.
• To have partnership with industry and reputed institutions to enhance the employability
skills of the students and pedagogical pursuits.
• To leverage technologies to solve the real life societal problems through community
services.
ABOUT THE DEPARTMENT
DEPARTMENT VISION
To produce competent professionals with research and innovative skills, by providing them with
the most conducive environment for quality academic and research oriented undergraduate
education along with moral values committed to build a vibrant nation.
DEPARTMENT MISSION
Course Outcomes: After the completion of the course the student will be able to
CO Write readable C programs which use pointers for array processing and
5 parameter passing
CO Develop readable C programs with files for reading input and storing output
6
readable* - readability of a program means the following:
Logic used is easy to follow
Standards to be followed for indentation and formatting
Meaningful names are given to variables
Concise comments are provided wherever needed
Prerequisite: NIL
CO
1
CO
2
CO
3
CO
4
CO
5
CO
6
Assessment Pattern
Continuous Assessment
Tests End Semester
Bloom’s Category Test 1 Test 2 Examination
(Mark (Mark Marks
s) s)
Remember 15 10 25
Understand 10 15 25
Apply 20 20 40
Analyse 5 5 10
Mark distribution
Attendance : 10 marks
Continuous Assessment Test 2 (for lab, internal examination, for 2 hrs) : 20 marks
COURSE OBJECTIVE
To understand the fundamental concept of programming and use it in problem solving.
COURSE OUTCOME
2
Programming in C Lab Manual EST 102
INDEX
Page
Sl.No. Content
No.
1 Familiarization of Hardware Components of a Computer 5
2 Familiarization of Linux environment 10
3 Introduction to C 12
4 Experiments 26
4.1 Familiarization of console I/O and operators in C 26
4.2 Read 3 integer values and finds the largest among them. 27
4.3 Check whether the number is prime or not 27
4.4 Check whether the number is Armstrong or not 27
4.5 Find the sum and average of numbers in an array 28
4.6 Search an element in the array using Linear Search 28
4.7 Sort the elements in the array using Bubble Sort 29
4.8 Check whether the given string is palindrome or not. 29
4.9 Concatenate two strings without using library functions 30
4.10 Count the number of vowels, consonants and spaces in a string 30
4.11 Find the distances between two points in the Euclidean space 31
4.12 Print employee details using structure 32
4.13 Display the address of a person using union. 32
4.14 Find the factorial of a given Natural Number 33
4.15 Reverse of a string 34
4.16 Matrix addition, multiplication and transpose. 35
4.17 Add and swap two numbers using Pointer 37
4.18 Print the elements of an array using pointers 37
4.19 Sum of the elements in an array using pointers and functions. 38
4.20 File operations 39
4.21 Count the number of characters, words and lines in a file 40
5 Reference 41
3
Programming in C Lab Manual EST 102
Microprocessor
A motherboard is the central or primary printed circuit board (PCB) making up a complex
electronic system, such as a modern computer. It is also known as a main board,
4
Programming in C Lab Manual EST 102
baseboard, system board, planar board, or, on Apple computers, logic board, and is
sometimes abbreviated casually as mobo.
RAM
Random access memory (usually known by its acronym, RAM) is a type of computer data
storage. Today it takes the form of integrated circuits that allow the stored data to be
accessed in any order, i.e. at random.
A hard disk drive (HDD), commonly referred to as a hard drive, hard disk, or fixed disk
drive, is a non-volatile storage device which stores digitally encoded data on rapidly rotating
platters with magnetic surfaces. Strictly speaking, "drive" refers to a device distinct from its
medium, such as a tape drive and its tape, or a floppy disk drive and its floppy disk. Early
HDDs had removable media; however, an HDD today is typically a sealed unit.
5
Programming in C Lab Manual EST 102
Keyboard
A keyboard is an arrangement of buttons, or keys. A keyboard typically has characters
engraved or printed on the keys; in most cases, each press of a key corresponds to a single
written symbol.
Mouse
A mouse (plural mice, mouse devices, or mouses) is a pointing device that functions by
detecting two-dimensional motion relative to its supporting surface. Physically, a mouse
consists of a small case, held under one of the user's hands, with one or more buttons.
6
Programming in C Lab Manual EST 102
Monitor
A monitor is a piece of computer hardware that displays the video and graphics
information generated by a connected computer through the computer's video card.
A computer case is the enclosure that contains the main components of a computer. Cases are
usually constructed from steel, aluminum, or plastic, although other materials such as wood,
plexiglas or fans have also been used in case designs. Cases can come in many different sizes,
or form factors.
Computer Speaker
Computer speakers, or multimedia speakers, are external speakers, commonly equipped with
a low-power internal amplifier. The standard audio connection is 3.5mm (1/8 inch) stereo jacks
plug often colour-coded lime green (following the PC 99 standard) for computer sound cards.
7
Programming in C Lab Manual EST 102
An uninterruptible power supply (UPS), also known as a continuous power supply (CPS) or a
battery backup is a device which maintains a continuous supply of electric power to connected
equipment by supplying power from a separate source when utility power is not available.
Small UPS systems provide power for a few minutes; enough to power down the computer in
an orderly manner, while larger systems have enough battery for several hours.
8
Programming in C Lab Manual EST 102
Student can login into the system using the username and password then take the terminal,
for getting command terminal, search for terminal or use shortcut key Ctrl+Alt+t. In terminal
each student can login into the lab server using ssh command.
ssh login name@server IP address then press the enter key
vi program name.c
For saving the program, press Esc key then type :wq
After successful compilation take the output of the program using ./a.out
command.
LINUX COMMANDS
1. ls :- used to list the files and directories under the current directory.
Syntax:- ls press enter key
2. rm:- used to remove a particular file.
Syntax:- rm < file name>
3. mkdir:- used to create a directory.
Syntax:- mkdir <directory name>
4. cd:- used to change the directory.
Syntax:- cd <directory name>
5. cd .. :-used to leave from a particular directory.
Syntax:- cd .. press enter key
6. rmdir:- used to remove an empty directory.
Syntax:- rmdir <empty directory name>
9
Programming in C Lab Manual EST 102
10
Programming in C Lab Manual EST 102
3. Introduction to C
● Easy to learn
● Structured language
● It produces efficient programs
● It can handle low-level activities
● It can be compiled on a variety of computer platforms
Facts about C
Why to use C?
C was initially used for system development work, in particular the programs that make-
up the operating system. C was adopted as a system development language because it
produces code that runs nearly as fast as code written in assembly language. Some
examples of the use of C might be:
● Operating Systems
● Language Compilers
● Assemblers
● Text Editors
● Print Spoolers
● Network Drivers
● Modern Programs
11
Programming in C Lab Manual EST 102
● Databases
● Language Interpreters
● Utilities
The largest measure of C's success seems to be based on purely practical
considerations:
Structure of a C program
Documentation Section
Link Section /Include header file section
Definition Section
Global declaration section
Main() function section
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2
…
Function n
(User defined functions)
12
Programming in C Lab Manual EST 102
Documentation Section:-
Documentation section consists of a set of comment lines giving the name of the program,
the author and other details.
Link section:-
Link section provides instructions to the compiler to link functions from the system
library.
Definition Section:-
This section declares some variables that are used in more than one function. This
section also declares all the user defined functions.
Main() function section:-
Every C program must contain a main() function. This section contains two parts,
declaration and executable parts. Declaration part declares all the variables used in the
executable part. There is at least one statement in the executable part. Executable part
contains the statements following the declaration of the variables.
Subprogram section:-
This section contains all the user defined functions that are called in the main() function.
All sections, except the main () function and link section may be absent when they are not
required.
The character set in C Language can be grouped into the following categories.
1.Letters
2.Digits
3.Special characters
4.White Spaces
13
Programming in C Lab Manual EST 102
White Spaces are ignored by the compiler until they are a part of string constant. White
Space may be used to separate words, but are strictly prohibited while using between
characters of keywords or identifiers.
2. Digits (0-9)
3. Special Characters
Special Characters
Escape sequences
1. BlankSpace(\b)
2.HorizontalTab(\t)
3.CarriageReturn(\r)
4.NewLine(\n)
5. Form Feed (\f)
6. Vertical Tab (\v)
14
Programming in C Lab Manual EST 102
Every word in C language is a keyword or an identifier. Keywords are reserved words that
have standard, predefined meanings in C. All keywords must be written in lowercase.
Keywords in C language cannot be used as a variable name. They are specifically used by
the compiler for its own purpose and they serve as building blocks of a c program.
Identifier refers to the name of user-defined variables, array and functions. A variable
should be essentially a sequence of letters and or digits and the variable name should
begin with a character.
Both uppercase and lowercase letters are permitted. The underscore character is also
permitted in identifiers. The underscore (_) symbol can be used as an identifier.
Data Types
Data types are used to store various types of data that is processed by program. The
definition of a variable will assign storage for the variable and define the type of data that
will be held in the location.
C has different data types for different types of data and can be broadly classified as:
15
Programming in C Lab Manual EST 102
16
Programming in C Lab Manual EST 102
Character Type:
Character type variable can hold a single character. As there are singed and unsigned int
(either short or long), in the same way there are signed and unsigned chars; both occupy 1
byte each, but having different ranges. Unsigned characters have values between 0 and 255,
signed characters have values from –128 to 127.
double num2;
long double num3;
Void Type:
The void type has no values therefore it cannot be declared as a variable. The
void data type is usually used with function to specify its type. Like in our first C program
we declared “main()” as void type because it does not return any value. The concept of
returning values will be discussed in detail in the C function hub.
17
Programming in C Lab Manual EST 102
Constants
A constant is a number, character, or a character string that can be used as a value in a
program. Use constants to represent floating-point, integer, enumeration, or character
values that cannot be modified. Constants are fixed values that do not change during the
execution of a program. C has 4 basic types of constants.
Integer constant
Integer constants are a sequence of digits. It can be written in 3 different
number systems
● 0 to 9
● E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767)
● 0 to 7
● Add “0” before the value.
● Eg.: 045, 056, 067
(iii) Hexadecimal Integer:
● 0 to 9 and A to F
● Add 0x before the value
● E.g: 0x42, 0x56, 0x67
18
Programming in C Lab Manual EST 102
Floating point constants are a sequence of digits, followed by a decimal point, followed by a
sequence of digits, and optionally followed by an exponent. Ex: +867.9, -26.9876,
654.0 .In exponential form, the real constant is represented as two parts. The part lying
before the ‘e’ is the ‘mantissa’, and the one following ‘e’ is the ‘exponent’. For example, the
value 237.95 may be written as 23795E2 in exponential notation. E2 means multiply by
102.
Character constants
Character constants are a single character surrounded by single quotes (`''), or a number-
-the ordinal value of the corresponding character (usually its ASCII value). Within quotes,
the single character may be represented by a letter or by "escape sequences. Example of
character constants are ‘3’,’c’. Since each character constant represents an integer value,
it is also possible to perform arithmetic operations on character constants.
String constants
String constants are a sequence of character constants surrounded by double quotes (`"').
The character may be letters, numbers, special characters and blank space. Examples are
“hello”,”65”. Each string constant always ends with a special character ‘\0’. The compiler
automatically places a null character (\0) at the end of every string constant.
Variables
A variable is a value that can change any time. It is a memory location used to store a data
value. A variable name should be carefully chosen by the programmer so that its use is
reflected in a useful way in the entire program. Variable names are case sensitive. Example
of variable names are,
Sun
number
Salary
Emp_name
average1
19
Programming in C Lab Manual EST 102
1. They must always begin with a letter, although some systems permit
underscore as
first character.
2. The length of a variable must not be more than 8 characters.
3. White space is not allowed
4. A variable should not be a Keyword
5. It should not contain any special characters.
Variable declaration
The declaration of variables should be done in the declaration part of the program. These
variables must be declared before they are used in the program. The declaration provides
two things:
data_type variable_name;
int tax;
float tax_rate,count;
Arrays
An array is a series of elements of the same type placed in contiguous memory locations
that can be individually referenced by adding an index to a unique identifier.That means
that, for example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array we
20
Programming in C Lab Manual EST 102
can store 5 different values of the same type, int is an example of a unique identifier. For
example, an array to contain 5 integer values of type int called temp could be represented
like this:
temp
Where each blank panel represents an element of the array of type integer values. These
elements are numbered from 0 to 4 since in arrays the first index is always 0,
independently of its length.
Declaring Arrays
An array is declared by specifying its data type, name and the number of elements the
array holds between square brackets immediately following the array name.
Here is the syntax:
data_type array_name[size];
For example, to declare an integer array which contains 100 elements we can do as follows:
int a[100];
There are some rules on array declaration. The data type can be any valid C data types
including structure and union. The array name has to follow the rule of variable and the
size of array has to be a positive constant integer.
Array elements can be accessed via indexes array_name[index]. Indexes of array starts from
0 not 1 so the highest elements of an array is array_name[size-1].
Initializing Arrays
It is like a variable, an array can be initialized. To initialize an array, provide initializing
values which are enclosed within curly braces in the declaration and placed following an
equals sign after the array name. Here is an example of initializing an integer array.
int a[3]={1,2,3};
21
Programming in C Lab Manual EST 102
Each array element occupies consecutive memory locations and array name is a
pointer that points to the first element. Beside accessing array via index we can use pointer
to manipulate array. This program helps you visualize the memory address each array
elements and how to access array element using pointer.
Multidimensional Arrays
An array with more than one index value is called a multidimensional array. All the
array above is called single-dimensional array. To declare a multidimensional array you can
do follow syntax
datatype arrayname[size][size][size]
The number of square brackets specifies the dimension of the array. For example to declare
two dimensions integer array we can do as follows:
int matrix[3][3];
Statements in C
The statements of a C program control the flow of program execution. In C, as in
other programming languages, several kinds of statements are available to perform loops,
to select other statements to be executed, and to transfer control. C statements consist of
tokens, expressions, and other statements. A statement that forms a component of another
statement is called the "body" of the enclosing statement.
The expression statement contains a C expression that can contain the arithmetic or
logical operators introduced in Expressions and Assignments. The null statement is an
empty statement. Any C statement can begin with an identifying label consisting of a name
and a colon.
22
Programming in C Lab Manual EST 102
*/ % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
|| Logical OR left-to-right
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
23
Programming in C Lab Manual EST 102
Note 1:
Parentheses are also used to group sub-expressions to force a different precedence; such
parenthetical expressions can be nested and are then evaluated from inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or decrement
of the operand is delayed (to be accomplished sometime before the statement completes
execution). So in the statement y = x * z++; the current value of z is used to evaluate the
expression (i.e., z++ evaluates to z) and z only incremented after all else is done.
24
Programming in C Lab Manual EST 102
4. Experiments
ii) Read two numbers add them and display their sum
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.
i) ALGORITHM
1. Start
3. Stop
ii) ALGORITHM
1. Start
2. Read a,b
3. sum=a+b
4. Print sum
5. Stop
iii) ALGORITHM
1. Start
2. Read r
3. area=3.14*r*r
4. Print area
5. Stop
iv) ALGORITHM
1. Start
25
Programming in C Lab Manual EST 102
2. Read a,b,c,d,e,f,g
3. s=((a -b / c * d + e) * (f +g))
4. Print s
5. Stop
4.2 Read 3 integer values and find the largest among them.
ALGORITHM
1. Start
2. Read a,b,c
3. if(a > b && a>c) then print a is largest else goto step 4
4. if(b > a && b>c ) then print b is largest else print c is largest
5. Stop
4.3 Read a Natural Number and check whether the number is prime or not
ALGORITHM
1. Start
2. Read num
3. Set flag=0, i = 2
4. If (num num/2) then goto step 4.1 else goto
4.1 if( num % 2 == 0) then set flag=1 else goto step 4.2
4.2 i=i+1, goto step 4
5. if (flag ==0) then print num is prime else print num is not prime
6. Stop
4.4 Read a Natural Number and check whether the number is Armstrong or not
ALGORITHM
1. Start
2. sum = 0
3. Read n
26
Programming in C Lab Manual EST 102
4. temp=n
5. If (temp != 0) then goto step 6 else goto step 9
6. t = temp%10
7. sum = sum+t*t*t
8. temp = temp/10 goto step 5
9. if(n == sum) then print it is an armstrong no else print it is not an
armstrong no
10. Stop
4.5 Read n integers store them in an array and find their sum and average
ALGORITHM
1. Start
2. Read the limit n
3. sum =0,i=0
4. if(i<n) then goto step 5 else goto step 8
5. Read the number A[i]
6. sum = sum + A[i]
7. i=i+1, then goto step 4
8. avg = sum / n
9. Print sum, avg
10.Stop
4.6 Read n integers, store them in an array and search for an element in the array
using an algorithm for Linear Search
ALGORITHM
START
1. Start
2. Read the limit n
3. Read the number to be search num
4. i=0
5. if(i<n) then goto step 6 else goto step 8
27
Programming in C Lab Manual EST 102
28
Programming in C Lab Manual EST 102
ALGORITHM
1. Start
2. Read two strings to a and b
3. Find length of a to n
4. i=0,j=n-1
5. (if b[i]!= ‘\0’) then a[j]=b[i] else goto step 7
6. i=i+1,j=j+1 then goto step 5
7. a[j]=’\0’
8. Print a
9. Stop
4.10 Read a string (ending with a $ symbol), store it in an array and count the
number of vowels, consonants and spaces in it.
ALGORITHM
1. Start
2. Read the string to str
3. vowels=0,Consonant=0,space=0,i=0
4. if(str[i]!=’\0’) then goto step 5 else goto step 9
29
Programming in C Lab Manual EST 102
ALGORITHM
1. Start
2. Read x1,x2,y1,y2 using structure
3. s= ((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1))
4. distance = square root (s)
5. Print distance
6. Stop
30
Programming in C Lab Manual EST 102
4.12 Using structure, read and print data of n employees (Name, Employee Id and
Salary)
ALGORITHM
1. Start
2. Declare a structure employee with a variable emp and structure
members name, e_id and salary
3. read name, e_id and salary using structure variable emp.
4. print name, e_id and salary using structure variable emp.
5. stop
4.13 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.
ALGORITHM
1. Start
2. Define a variable C_SIZE with a constant value.
3. Declare a structure union with a variable emp and union members
Name, House_Name, City_Name, State and Pin code
4. Read name using union variable emp
5. Print name using union variable emp
6. Read House_Name, using union variable emp
7. Print House_Name, using union variable emp
8. Read City_Name using union variable emp.
9. Print City_Name using union variable emp.
10.Read State using union variable emp.
11.Print state using union variable emp.
12.Read pin_code using union variable emp.
13.Print pin_code using union variable emp.
14.Stop
31
Programming in C Lab Manual EST 102
4.14 Find the factorial of a given Natural Number n using recursive and non
recursive functions
i) Non recursive
ALGORITHM of main()
1. Start
2. Read n
3. Call the function fact(n)
4. Stop
ALGORITHM of Function fact(x)
1. Start
2. z=1
3. If (x != 0) then goto step 2.3 else goto step 2.5
4. z= z*x
5. x=x-1, go to step 2.2
6. Print z
7. Read the number to n
8. Call the function fact(n)
9. Stop
ii) Recursive
ALGORITHM for main()
1. Start
2. Read n
3. Call the function fact(n)
4. Print Factorial f
5. Stop
ALGORITHM of Function fact(x)
1. Start
2. If (x==1) then return 1 else goto step 3
3. f=x*fact(x-1)
4. Return f
5. Stop
32
Programming in C Lab Manual EST 102
4.15 Read a string (word), store it in an array and obtain its reverse by using a user
defined function.
ALGORITHM of main()
1. Start
2. Call the function reverse()
5. Stop
ALGORITHM of Function reverse
1. Start
2. Read a word to str
3. Find length of str to n.
4. n=n-1
5. if(n>=0)then Print str[n] else goto step 4
6. Stop
4.16 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.
ALGORITHM of main()
1. Start
2. Declare 2 matrices a,b and their rows and columns(m1, n1, m2, n2) and a choice
variable op
3. Read m1, n1
4. Call the function readmatrix(a,m1,n1)
5. Read m2, n2
6. Call the function readmatrix(b,m2,n2)
7. To print Matrix a, call the function displaymatrix(a,m1,n1);
8. To print Matrix b, call the function displaymatrix(b,m2,n2);
9. Read op // 1.add 2.multiply 3.transpose 4.exit
10.if(op==1) then goto step 11 else goto step 12
11. if(m1==m2 && n1==n2) then call the function addmatrix(a,b,m1,n1) else print
matrix addition is not possible go to step 15
12. if(op==2) then goto step 13 else goto step 14
33
Programming in C Lab Manual EST 102
13. if(n1==m2) then call the function multmatrix(a,b,m1,n1,n2), else print “matrix
multiplication is not possible” , go to step 15
14. if(op==3) then call the function transpose(a,m1,n1) else print invalid choice.
15.Stop
34
Programming in C Lab Manual EST 102
7. j=j+1,goto step 6
8. i=i+1,goto step 4
9. Call the function displaymatrix(c,m,n);
10.Stop
ALGORITHM of transpose(int a[][100],int m,int n)
1. Start
2. Declare a matrix c
3. i=0,j=0
4. if(i<m)then goto step 5 else goto step 9
5. j=0
6. if(j<n) then c[j][i]=a[i][j] ,goto step 7 else goto step 8
7. j=j+1,goto step 6
8. i=i+1,goto step 4
9. Call the function displaymatrix(c,n,m);
10. Stop
ALGORITHM of multmatrix(int a[][100],int b[][100],int m1,int n1,int n2)
1. Start
2. Declare a matrix c
3. i=0,j=0
4. if(i<m1)then goto step 5 else goto step 12
5. j=0
6. if(j<n2) then c[j][i]=0 ,goto step 7 else goto step 8
7. k=0
8. if(k<n1) then c[i][j]=c[i][j]+ a[i][k] * b[k][j],goto step 9 else
goto step 10
9. k=k+1,goto step 8
10.j=j+1,goto step 6
11.i=i+1,goto step 4
12. Call the function displaymatrix(c,m1,n2)
13.Stop
35
Programming in C Lab Manual EST 102
4.17 Do the following using pointers i) add two numbers ii) swap two numbers using
a user defined function.
i) Add two numbers
ALGORITHM
1. Start
2. Initialize two integer pointers p,q.
3. Read a,b
4. Reference the pointers to variables using '&' operator.//p=&a,q=&b
5. Now, add the values, using * operator//sum=*p+*q
6. Print the sum.
7. Stop
ii) Swap two numbers
ALGORITHM
1. Start
2. Initialize two integer pointers p,q.
3. Read a,b
4. Reference the pointers to variables using '&' operator.//p=&a,q=&b
5. Now, interchange the values, using * operator//t=*p,*p=*q,*q=t
Print the swapped values using * operator.//Print *p,*q
6. Stop
36
Programming in C Lab Manual EST 102
10. i=0
11. ptr=&a[0]
12. if(i<n) then goto step 13 else goto step 16
13. Print a number using pointer ptr
14. ptr=ptr+1
15. i=i+1,goto step 12
16. Stop
4.19 Compute sum of the elements stored in an array using pointers and user
defined functions.
ALGORITHM for main()
1. Start
2. Read size of the array to n
3. Initialize one integer pointer *ptr
4. i=0
5. ptr=&a[0]
6. if(i<n) then goto step 7 else goto step 10
7. Read a number to ptr
8. ptr=ptr+1
9. i=i+1,goto step 6
10. Call the function sum(&a,n)
11.Stop
ALGORITHM for function sum(int *ptr, int n)
1. Start
2. i=0,s=0
3. if(i<n) then goto step 4 else goto step 7
4. s=s+*ptr
5. ptr=ptr+1
6. i=i+1,goto step 3
7. Print s
8. Stop
37
Programming in C Lab Manual EST 102
1. Start
2. Create a file pointer *fp
3. Open an existing file in read mode using file pointer fp
//fp=fopen(“a.txt”,”r”)
4. if(fp==NULL) then print Error opening file else goto step 5
5. Read the content from file a.txt//ch=getc(fp)
6. if (ch!='EOF') then goto step 7 else goto step 8
7. Print the content from the file a.txt, goto step 5 //putchar(ch);
8. Close the file
9. Stop
iii) Append new data and display on console
1. Start
2. Create a file pointer *fp
38
Programming in C Lab Manual EST 102
4.21 Open a text input file and count the number of characters, words and lines in
it; and store the results in an output file.
1. Start
2. Create a file pointer *fp
3. c=o,w=0,l=0
4. Open an existing file in read mode using file pointer fp
//fp=fopen(“a.txt”,”r”)
5. if(fp==NULL) then print Error opening file else goto step 5
6. Read the content from file a.txt to ch//ch=getc(fp)
7. if (ch!='EOF') then goto step 7 else goto step 10
8. if(ch==’\n’) then l=l+1 else goto step 9
9. if(ch==’ ’) then w=w+1 else c=c+1,goto step 6
10. Print c,w,l
11. Close the file
12. Stop
39
Programming in C Lab Manual EST 102
5. REFERENCES
PROGRAM
#include<stdio.h>
main()
{
printf("Hello World!!");
}
OUTPUT
Hello World!!
PROGRAM
#include<stdio.h>
main()
{
int a,b,c;
printf("Enter First Number:");
scanf("%d",&a);
printf("Enter Second Number:");
scanf("%d",&b);
c=a+b;
printf("Sum of above numbers is:%d",c);
}
OUTPUT
PROGRAM
#include<stdio.h>
# define PI 3.14
main()
{
40
Programming in C Lab Manual EST 102
float r,Area;
printf("Enter the radius:");
scanf("%f",&r);
Area=PI*r*r;
printf("Area of Circle:%f",Area);
}
OUTPUT
#include<stdio.h>
main()
{
int a,b,c,d,e,f,g,Ans;
printf("Enter 7 values for the variables:");
scanf("%d%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f,&g);
Ans=((a-b/c*d+e)*(f+g));
printf("Solutin=%d",Ans);
}
OUTPUT
Enter 7 values for the variables:1 2 3 4 5 6 7
Solutin=78
PROGRAM
#include<stdio.h>
main()
{
int n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%d%d%d", &n1, &n2, &n3);
if (n1 >= n2 && n1 >= n3)
printf("%d is the largest number.", n1);
if (n2 >= n1 && n2 >= n3)
printf("%d is the largest number.", n2);
else
printf("%d is the largest number.", n3);
}
OUTPUT
41
Programming in C Lab Manual EST 102
34
3
78
78 is the largest number.
PROGRAM
#include <stdio.h>
main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (n == 1)
{
printf("1 is neither prime nor composite.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
OUTPUT
#include <stdio.h>
main()
42
Programming in C Lab Manual EST 102
{
int num, S, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
S = num;
while (S != 0)
{
remainder = S % 10;
result += remainder * remainder * remainder;
S /= 10;
}
if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);
}
OUTPUT
Enter a three-digit integer: 153
153 is an Armstrong number.
./a.out
Enter a three-digit integer: 346
346 is not an Armstrong number.
43
Programming in C Lab Manual EST 102
OUTPUT
Enter the numbers of elements: 5
1. Enter number: 1
2. Enter number: 2
3. Enter number: 3
4. Enter number: 4
5. Enter number: 5
Sum=15.00
Average = 3.00
PROGRAM
#include<stdio.h>
main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
44
Programming in C Lab Manual EST 102
8
12
Enter a number to search
7
7 is present at location 4.
PROGRAM
#include <stdio.h>
main()
{
int a[25],n;
int i,j,t;
printf("enter the size of array");
scanf("%d",&n);
printf("enter the elements are");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
45
Programming in C Lab Manual EST 102
45
sorted array is:2 33 34 45 780
PROGRAM
#include <stdio.h>
#include <string.h>
main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
}
OUTPUT
Enter a string:malayalam
malayalam is a palindrome
./a.out
Enter a string:great
great is not a palindrome
46
Programming in C Lab Manual EST 102
OUTPUT
Please Enter the First String :(end with $!!)best$
PROGRAM
#include <stdio.h>
main()
{
char line[150];
int vowels, consonant, space,i;
vowels = consonant = space = 0;
printf("Enter line of string:(end with $)");
gets(line);
for (i = 0; line[i] != '$'; ++i)
{
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U')
{
++vowels;
}
else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z'))
{
47
Programming in C Lab Manual EST 102
++consonant;
}
else if (line[i] == ' ')
{
++space;
}
}
printf("Vowels: %d", vowels);
printf("\nConsonants: %d", consonant);
printf("\nWhite spaces: %d", space);
}
OUTPUT
Enter line of string:(end with $)india is my country$
Vowels: 6
Consonants: 10
White spaces: 3
int main() {
float x1, y1, x2, y2, gdistance;
printf("Input x1: ");
scanf("%f", &x1);
printf("Input y1: ");
scanf("%f", &y1);
printf("Input x2: ");
scanf("%f", &x2);
printf("Input y2: ");
scanf("%f", &y2);
gdistance = ((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1));
printf("Distance between the said points: %.4f", sqrt(gdistance));
printf("\n");
return 0;
}
OUTPUT
Input x1: 3
Input y1: 6
Input x2: -2
Input y2: 4
Distance between the said points: 5.3852
48
Programming in C Lab Manual EST 102
PROGRAM
#include <stdio.h>
struct employee
{
char name[30];
int empId;
float salary;
};
main()
{
}
OUTPUT
Enter details :
Name ?:Amrutha
ID ?:349
Salary ?:23000
49
Programming in C Lab Manual EST 102
4.13 UNION
PROGRAM
#include <stdio.h>
#include <string.h>
#define C_SIZE 50
union Address
{
char name[C_SIZE];
char hname[C_SIZE];
char cityname[C_SIZE];
char state[C_SIZE];
char pin[C_SIZE];
};
int main()
{
union Address record1;
printf("Enter name:");
scanf("%s",record1.name);
getchar();
printf("Enter house name:");
scanf("%s",record1.hname);
getchar();
printf("Enter city name:");
scanf("%s",record1.cityname);
getchar();
printf("Enter state name:");
scanf("%s",record1.state);
getchar();
printf("Enter pin:");
scanf("%s",record1.pin);
printf("Union record1 values .... \n");
printf(" Name : %s \n", record1.name);
printf(" House Name : %s \n", record1.hname);
printf(" City Name : %s \n", record1.cityname);
printf(" State name : %s \n", record1.state);
printf(" Pin : %s \n", record1.pin);
}
OUTPUT
Note: it is noted that the program will print only Pin because the union will
hold only one value at a time .
50
Programming in C Lab Manual EST 102
PROGRAM
#include <stdio.h>
long int factnr(int n)
{ int i;
long int f=1;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
long int factr(int n)
{
if(n==0) return 1;
else
return (n*factr(n-1));
}
int main()
{int n;
system("clear");
printf("Enter the number \n");
scanf("%d",&n);
printf("Factorial using non recursive function %d !=%ld\n",n,factnr(n));
printf("Factorial using recursive function %d !=%ld\n",n,factr(n));
}
PROGRAM
#include <stdio.h>
#include <string.h>
void reversestr(char str[])
{ int i,n;
char c;
n=strlen(str);
for(i=0;i<n/2;i++)
{ c=str[i];
str[i]=str[n-1-i];
str[n-1-i]=c;
}
}
int main()
{
char str[100];
system("clear");
51
Programming in C Lab Manual EST 102
PROGRAM
#include <stdio.h>
#include <stdlib.h>
void readmatrix(int a[][100],int m,int n)
{
int i,j;
printf("enter the elements row by row\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
void displaymatrix(int a[][100],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%5d",a[i][j]);
printf("\n");
}
}
void addmatrix(int a[][100],int b[][100],int m,int n)
{
int i,j,c[100][100];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("Sum of matrix...\n");
displaymatrix(c,m,n);
}
void transpose(int a[][100],int m,int n)
{
int i,j,c[100][100];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
52
Programming in C Lab Manual EST 102
c[j][i]=a[i][j];
displaymatrix(c,n,m);
}
void multmatrix(int a[][100],int b[][100],int m1,int n1,int n2)
{
int c[100][100],i,j,k;
for (i = 0; i < m1; i++) {
for (j = 0; j < n2; j++) {
c[i][j] = 0;
for (k = 0; k < n1; k++)
c[i][j] += a[i][k] * b[k][j];
}
}
printf("Product of matrix...\n");
displaymatrix(c,m1,n2);
}
int main()
{ int a[100][100],b[100][100],m1,n1,m2,n2,op;
system("clear");
printf("Enter the size of the matrix A row,column\n");
scanf("%d%d",&m1,&n1);
printf("Enter Matrix A\n");
readmatrix(a,m1,n1);
printf("Enter the size of the matrix B row column\n");
scanf("%d%d",&m2,&n2);
printf("Enter Matrix B\n");
readmatrix(b,m2,n2);
system("clear");
printf("Matrix A..\n");
displaymatrix(a,m1,n1);
printf("Matrix B..\n");
displaymatrix(b,m2,n2);
while(1)
{
printf("\n************************************\n");
printf("1.add 2.multiply 3.transpose 4.exit \n");
printf("Enter the option. .... ");
scanf("%d",&op);
switch(op)
{
case 1: if(m1==m2 && n1==n2)
addmatrix(a,b,m1,n1);
else
printf("Incompatable matrix...cannot add..\n");
break;
case 2: if(n1==m2)
multmatrix(a,b,m1,n1,n2);
53
Programming in C Lab Manual EST 102
else
printf("Incompatable matrix...cannot mutliply..\n");
break;
case 3: printf("Transpose of A..\n");
transpose(a,m1,n1);
printf("Transpose of B..\n");
transpose(b,m2,n2);
break;
case 4: exit(0);
}
}
}
OUTPUT
************************************
1.add 2.multiply 3.transpose 4.exit
Enter the option.....:1
Sum of matrix...
2 4 6
2 4 6
2 4 6
************************************
54
Programming in C Lab Manual EST 102
************************************
1.add 2.multiply 3.transpose 4.exit
Enter the option.....:3
Transpose of A..
1 1 1
2 2 2
3 3 3
Transpose of B..
1 1 1
2 2 2
3 3 3
************************************
1.add 2.multiply 3.transpose 4.exit
Enter the option.....:4
4.17 POINTERS
(i) ADD TWO NUMBERS
PROGRAM
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
}
OUTPUT
Enter two integers to add
34
55
Programming in C Lab Manual EST 102
9
Sum of the numbers = 43
PROGRAM
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
int main()
{
int x, y;
printf("Enter Value of x ");
scanf("%d", &x);
printf("\nEnter Value of y ");
scanf("%d", &y);
swap(&x, &y);
printf("\nAfter Swapping: x = %d, y = %d", x, y);
return 0;
}
OUTPUT
Enter Value of x 45
Enter Value of y 7
After Swapping: x = 7, y = 45
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int n, i;
int * ptr = arr;
printf("Enter size of array: ");
scanf("%d", &n);
56
Programming in C Lab Manual EST 102
OUTPUT
Enter size of array: 5
Enter elements in array:
23
4
5
7
9
Array elements:
23
4
5
7
9
#include <stdio.h>
#include <stdlib.h>
int arraysum(int *ptr,int n)
{
int sum=0,i;
for (i = 0; i < n; i++)
{ sum=sum+ *(ptr + i);
}
return sum;
}
int main()
{
int arr[]={4,5,6,7,8,9,10,1,2,3};
int sum;
sum=arraysum(arr,10);
printf("Array elements sum=:%d \n",sum);
}
OUTPUT
Array elements sum=:55
57
Programming in C Lab Manual EST 102
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("a.txt","w");
if (fp==NULL)
{
printf("error opening file..\n");
exit(1);
}
else
{
fprintf(fp,"%s","Welcome\n");
fprintf(fp,"%s","to file handling in C\n");
}
printf("File Created...named a.txt");
fclose(fp);
}
OUTPUT
File Created...named a.txt
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","r");
if(fp==NULL)
{
printf("Error opening source file..");
exit(1);
}
printf("Content of File a.txt\n................... \n");
while(fscanf(fp,"%s",t)==1)
{
printf("%s\n",t);
}
fclose(fp);
58
Programming in C Lab Manual EST 102
OUTPUT
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char t[100];
fp=fopen("a.txt","a");
if(fp==NULL)
{
printf("Error opening source file..");
exit(1);
}
printf("Enter the contents to append. ............... \n");
while(1)
{
fgets(t,sizeof(t),stdin);
if(strcmp(t,"end\n")==0) break;
fputs(t,fp);
}
fclose(fp);
fp=fopen("a.txt","r");
printf("File contents after appending. \n");
printf("********************************\n");
while(fgets(t,sizeof(t),fp)!=NULL)
{
printf("%s",t);
}
fclose(fp);
}
59
Programming in C Lab Manual EST 102
OUTPUT
Enter the contents to append
.................
mea engg college
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char fname[50];
int ch;
int nl=0,nc=0,nw=0;
printf("Enter the file name. .. \n");
scanf("%[^\n]",fname);
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("Error opening file..");
exit(1);
}
ch=getc(fp);
while(ch!=EOF)
{
if (ch=='\n') nl++;
if(ch==' ') nw++;
nc++;
ch=getc(fp);
}
fclose(fp);
printf("Number of lines=%d Number of words=%d ,Number of characters =
%d,\n",nl,nw,nc+nl);
printf("results are written into result.dat file..\n");
fp=fopen("result.dat","w");
fprintf(fp,"Number of lines=%d Number of words=%d ,Number of characters =
%d,\n",nl,nw,nc+nl);
fclose(fp);
}
OUTPUT
Enter the file name....
a.txt
Number of lines=2 Number of words=4 ,Number of characters = 32,
results are written into result.dat file..
****************************************************************************************************
60
Programming in C Lab Manual EST 102
61
62