C Lab Manual
C Lab Manual
C Lab Manual
LABORATORY MANUAL
PROGRAMMING FOR PROBLEM SOLVING
LABORATORY
BE I &II Semester (AICTE Model Curriculum): 2020-21
NAME: ___________________________________________________________________
ROLL NO:__________________________________________________________________
BRANCH:__________________ SEM:______________________________________
VISION
To produce ethical, socially conscious and innovative professionals
who would contribute to sustainable technological development of the
society.
MISSION
To impart quality engineering education with latest technological
developments and interdisciplinary skills to make students succeed in
professional practice.
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
LABORATORY MANUAL
Prepared
By
Dr. M. Sharada Varalakshmi
Professor, Dept. of CSE,
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
VISION
MISSION
PROGRAM OUTCOMES
Engineering graduates will be able to:
PO2: Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12: Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
PSO1: Apply the knowledge of Computer Science and Engineering in various domains
like networking and data mining to manage projects in multidisciplinary
environments.
Suggested Readings:
1. Byron Gottfried, ―Theory and practice of Programming with C”, Schaum‘s Outline McGraw-
Hill, 1996
2. A.K. Sharma, ―Computer Fundamentals and Programming in C, Universities Press, 2nd Edition,
2018
3. E. Balaguruswamy, ―Programming in ANSI C‖, Tata McGraw-Hill Education, 2008
4. Brian W. Kernighan and Dennis M. Ritchie,‖The C Programming Language‖, Prentice Hall of
India,1988.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
CODE : ES 155 CS
SEMESTER : I & II
Taxonomy
CO No. Course Outcome
Level
ES 155 CS.6 Develop programs on stored data and file structures Create
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to
starting time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the
lab with the program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments.
c. Formal dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during
the lab sessions. Misuse of the equipment, misbehaviours with the staff and systems
etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out. If
anybody found loitering outside the lab / class without permission during working
hours will be treated seriously and punished appropriately.
10. Students should SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
• All students must observe the dress code while in the laboratory
• Footwear is NOT allowed
• Foods, drinks and smoking are NOT allowed
• All bags must be left at the indicated place
• The lab timetable must be strictly followed
• Be PUNCTUAL for your laboratory session
• All programs must be completed within the given time
• Noise must be kept to a minimum
• Workspace must be kept clean and tidy at all time
• All students are liable for any damage to system due to their own negligence
• Students are strictly PROHIBITED from taking out any items from the laboratory
• Report immediately to the lab programmer if any damages to equipment
Lab In – charge
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
LIST OF EXPERIMENTS
PROGRAM 1.
Aim:
To find the maximum and minimum of given set of numbers. For input & output Statements we
include the header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
If—else statement
if…else statement is used to make a decision based on two choices. It has the following form:
syntax:
if(condition)
{
True Stmt block;
}
Else
{
False stmt block;
}
Stmt-x;
In this syntax,
<condition> is a relational expression or logical expression or any expression that returns either
true or false. It is important to note that the condition should be enclosed within parentheses ( and ).
The true stmt block and false stmt block are simple statements or compound statements or null
statements.
Stmt-x is any valid C statement.
Algorithm:
Step 1: Start
Step 2: Read ‘n’, which is number of elements
Step 3: If i<n then
Step 4: Accept elements into an array list[i] upto given range
Step 5: min=max=sum=list[0]
Step 6: If i<n then
Step 7: If list[i]>max then
Step 8: max is equal to list[i]
Step 9: If list[i]<min then
Step 10: min is equal to list[i]
Page 1
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], i, n, max, min;
clrscr();
printf(“Enter size of the array: \n”);
scanf(“%d”, &n);
printf(“Enter elements in the array: \n”);
for(i = 0;i < n;i++)
{
scanf(“%d”, &a[i]);
}
max=a[0];
min=a[0];
for(i = 1;i < n;i++)
{
if(a[i] > max)
max=a[i];
if(a[i] < min)
min=a[i];
}
printf(“Maximum element = %d \n”, max);
printf(“Minimum element = %d \n”, min);
getch();
}
Expected Output :
Page 2
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To find the roots of a given quadratic equation. For input & output statements we include the header
file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start
Step 2: Input the values for a, b, c
Step 3: d=b*b –4*a*c
Step 4: if d greater than zero
a) print roots are read and distinct
b) r1= -b+ √ d / (2*a)
c)r2= -b-√ d / (2*a)
Step 5: Print r1 and r2, go to 7
Step 6: if d is equal to zero
a) Print roots are real and equal
b) r1 = - b/2*a
Print r1, go to 7
else
print roots are imaginary
Step 7: Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, d, r1, r2, rp, ip;
clrscr();
printf("Enter a b c values: \n");
scanf("%f%f%f", &a, &b, &c);
if(a = = 0)
{
printf(" not a QE");
}
else
{
d = b*b-4*a*c;
}
if(d >= 0)
{
Page 3
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output 1:
Expected Output 2:
Page 4
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim: To find the value of sin x using series expansion. For input & output statements we include
the header file <stdio.h>, for arithmetic operations include the <math.h> and for clear the screen
include the <conio.h>.
Description:
for statement:
It is one of the looping control statements. It is also called as entry-controlled looping control
statement. i.e., it tests the condition before entering into the loop body. The syntax for “for”
statement is as follows:
Syntax:
for(exp1;exp2;exp3)
for-body
next_statement;
In this syntax,
for is a keyword. exp1 is the initialization statement. If there is more than one statement, then those
should be separated with commas. exp2 is the condition. It is a relational expression or a compound
relational expression or any expression that returns either true or false. The exp3 is the updating
statement. If there is more than one statement, then those should be separated with commas. exp1,
exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for-body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a
null statement.
Algorithm:
Step 1: Start the program.
Step 2: Declare all the required variables.
Step 3: Read the Input for Number of terms (n) and Angle in degres (x).
Step 4: Compute x = (x * 3.14) / 180.
Step 5: Set sum = x and term = x.
Step 6: if(i < = n) then goto step 7.
Step 7: Compute and set term = (term * (-1) * x * x) / ((2 * i) * (2 * i + 1)).
Step 8: Compute and set sum+ = term.
Step 9: Compute i = i + 1 then goto step 6.
Step 10: Display the sinx value.
Step 11: Stop the program.
Page 5
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x, sum, term;
int i, n;
clrscr();
printf("Enter the no of terms: \n");
scanf("%d", &n);
printf("Enter the angle in degrees x: \n");
scanf("%f", &x);
x = (x*3.14) / 180;
sum = x;
term = x;
for(i = 1;i <= n;i++)
{
term = (term*(-1)*x*x) / ((2*i)*(2*i+1));
sum+ = term;
}
printf("Sin valve of given angle is %f", sum);
getch();
}
Expected Output:
Aim:
To find the value of cos x using series expansion. For input & output statements we include the
header file <stdio.h>, for arithmetic operations include the <math.h> and for clear the screen
include the <conio.h>.
Algorithm:
Step 1: Start the program.
Step 2: Declare all the required variables.
Step 3: Read the Input for Number of terms (n) and Angle in degres (x).
Step 4: Compute x = (x * 3.14) / 180.
Step 5: Set sum = 1 and term = 1.
Page 6
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x, sum, term;
int i, n;
clrscr();
printf("Enter the no of terms: \n");
scanf("%d", &n);
printf("Enter the angle in degrees x: \n");
scanf("%f", &x);
x = (x*3.14) / 180;
sum = 1;
term = 1;
for(i = 1;i <= n;i++)
{
term = (term*(-1)*x*x) / ((2*i)*(2*i-1));
sum+ = term;
}
printf("Cos valve of given angle is %f", sum);
getch();
}
Expected Output:
Page 7
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To convert binary to decimal. For input & output statements we include the header file <stdio.h>
and for clear the screen include the <conio.h>.
Description:
While:
The simplest of all the looping structures in c is the while statement. The basic format of the while
statement is:
Syntax:
While(condition)
{
Statements;
}
The while is an entry –controlled loop statement The condition is evaluated and if the condition is
true then the statements will be executed.After execution of the statements the condition will be
evaluated and if it is true the statements will be executed once again. This process is repeated until
the condition becomes false and the control is transferred out of the loop .On exit the program
continues with the statement immediately after the body of the loop.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
long int binary, decimal = 0, j = 1, rem;
clrscr();
printf("Enter any number any binary number: \n");
scanf("%ld", &binary);
while(binary != 0)
{
rem = binary % 10;
decimal = decimal+rem*j;
j = j*2;
binary = binary / 10;
}
printf("Equivalent decimal value: %ld", decimal);
getch();
}
Expected Output:
Page 8
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To convert decimal to binary. For input & output statements we include the header file <stdio.h>
and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start
Step 2: Declare decimalnum, rem, temp, binarynum
Step 3: Read decimalnum
Step 4: Set binarynum to 0 and temp to 1
Step 5: rem equals decimalnum mod 2
Step 6: decimalnum equals decimalnum by 2
Step 7: binarynumequlasbinarynum plus rem times temp
Step 8: temp equals temp times 10
Step 9: Repeat step 5 to step 8 until decimalnum!=0
Step 10: End while
Step 11: print binary equivalent of decimal number
Step 12: Exit
Step 13: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
long int decimal, rem, q;
int binary[100], i = 1, j;
clrscr();
printf("Enter any decimal number: \n");
scanf("%ld", &decimal);
q = decimal;
while(q != 0)
{
binary[i++] = q % 2;
q = q / 2;
}
printf("Equivalent binary value of decimal number %d: ", decimal);
for(j = i -1 ;j > 0;j--)
printf("%d", binary[j]);
getch();
}
Expected Output:
Enter any decimal number:50
Equivalent binary value of decimal number 50: 110010
Page 9
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To convert binary to octal. For input & output statements we include the header file <stdio.h> and
for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
long int binary, octal = 0, j = 1, rem;
clrscr();
printf("Enter any number any binary number: \n");
scanf("%ld", &binary);
while(binary != 0)
{
rem = binary % 10;
octal = octal+rem*j;
j = j*2;
binary = binary / 10;
}
printf("Equivalent octal value: %lo", octal);
getch();
}
Expected Output:
Aim:
To convert octal to binary. For input & output statements we include the header file <stdio.h> and
for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
#define MAX 1000
void main()
{
char octal[MAX];
long int i = 0;
clrscr();
printf("Enter any octal number: \n");
scanf("%s", octal);
printf("Equivalent binary value: \n");
while(octal[i])
{
Page 10
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
switch(octal[i])
{
case '0': printf("000");
break;
case '1': printf("001");
break;
case '2': printf("010");
break;
case '3': printf("011");
break;
case '4': printf("100");
break;
case '5': printf("101");
break;
case '6': printf("110");
break;
case '7': printf("111");
break;
default: printf("Invalid octal digit %c ", octal[i]);
}
i++;
}
getch();
}
Expected Output:
Aim:
To convert binary to hexadecimal. For input & output statements we include the header file
<stdio.h> and for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
long int binary, hexadecimal = 0, j = 1, rem;
clrscr();
printf("Enter any number any binary number: \n");
scanf("%ld", &binary);
while(binary != 0)
{
rem = binary % 10;
hexadecimal = hexadecimal+rem*j;
j = j*2;
binary = binary / 10;
Page 11
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
}
printf("Equivalent hexadecimal value: %lX", hexadecimal);
getch();
}
Expected Output:
Aim:
To convert hexadecimal to binary. For input & output statements we include the header file
<stdio.h> and for clear the screen include the <conio.h>.
Description:
switch statement:
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also
used to make a decision among multiple choices. switch statement has the following form:
switch(<exp>)
{
case <exp-val-1>: statements block-1
break;
break;
break;
:
:
case <exp-val-N>: statements block-N
break;
In this syntax,
• switch, case, default and break are keywords.
Page 12
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
• <exp> is any expression that should give an integer value or character value. In other words,
it should never return any floating-point value. It should always be enclosed with in
parentheses ( and ). It should also be placed after the keyword switch.
• <exp-val-1>, <exp-val-2>, <exp-val-3>…. <exp-val-N> should always be integer
constants or character constants or constant expressions. In other words, variables can never
be used as <exp-val>. There should be a space between the keyword case and <exp-val>.
The keyword case along with its <exp-val> is called as a case label. <exp-val> should
always be unique; no duplications are allowed.
• Statements block-1, statements-block-2, statements block-3… statements block-N and default
statements block are simple statements, compound statements or null statements. It is
important to note that the statements blocks along with their own case labels should be
separated with a colon ( : ).
• The break statement at the end of each statements block is an optional one. It is
recommended that break statement always be placed at the end of each statements block.
With its absence, all the statements blocks below the matched case label along with
statements block of matched case get executed. Usually, the result is unwanted.
• The statement block and break statement can be enclosed with in a pair of curly braces { and
}.
• The default along with its statements block is an optional one. The break statement can be
placed at the end of default statements block. The default statements block can be placed at
anywhere in the switch statement. If they placed at any other places other than at end, it is
compulsory to include a break statement at the end of default statements block.
• Next-statement is a valid C statement.
Program:
#include<stdio.h>
#include<conio.h>
#define MAX 1000
void main()
{
char binary[MAX], hexadecimal[MAX];
long int i = 0;
clrscr();
printf("Enter any hexadecimal number: \n");
scanf("%s", hexadecimal);
printf("Equivalent binary value: \n");
while(hexadecimal[i])
{
switch(hexadecimal[i])
{
case '0': printf("0000");
break;
case '1': printf("0001");
break;
case '2': printf("0010");
break;
case '3': printf("0011");
break;
case '4': printf("0100");
break;
Page 13
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output:
Page 14
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To print pascal triangle. For input & output statements we include the header file <stdio.h> and for
clear the screen include the <conio.h>.
Description:
All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire
a space in pascal's triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The
output is sandwiched between two zeroes. The process continues till the required level is achieved.
Pascal's triangle can be derived using binomial theorem. We can use combinations and factorials to
achieve this.
Algorithm:
Step1: Start.
Step2: Declare variables x, y, n, a, z, s.
Step3: Enter the limit.
Step4: Initialize the value of variables, s=n , x=0, y=0 , z=s.
Step5: Do the following operations in loop. x = 0 to n. a= 1, x++ z=s to 0.
Step6: print space. z—- y = o to x. print a. a = a*(x-y)/(y+1) y= y+1. go to next line.
Step7: Repeat the process to n.
Step8: Print the final required triangle.
Step9: Stop.
Program:
#include<stdio.h>
#include<conio.h>
long fact(int);
void main()
{
int n, i, j;
clrscr();
printf("Enter the no. of lines: \n");
scanf("%d", &n);
for(i = 0;i < n;i++)
{
for(j = 0;j < n-i-1;j++)
printf(" ");
for(j = 0;j <= i;j++)
printf("%ld ", fact(i) / (fact(j)*fact(i-j)));
printf("\n");
}
getch();
}
Page 15
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output:
Aim:
To print Pyramid of Numbers (Floyd’s Triangle). For input & output statements we include the
header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
A pyramid of numbers is a graphical representation that shows the number of organisms at each
trophic level. It is an upright pyramid in light of the fact that in an ecosystem, the producers are
always more in number than other trophic levels
.
Algprithm:
Page 16
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, r, k = 1;
clrscr();
printf("Enter the range: \n");
scanf("%d", &r);
printf("FLOYD'S TRIANGLE: \n \n");
for(i = 1;i <= r;i++)
{
for(j = 1;j <= i;j++,k++)
printf(" %d", k);
printf("\n");
}
getch();
}
Expected Output:
Page 17
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To find factorial of a given number using recursion. For input & output statements we include the
header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
Recursion is the process of repeating items in a self-similar way. ... 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.
Algorithm:
Step 1: Start
Step 2: Read ‘n’
Step 3: a=recfactorial(n)
Step 4: if ‘x’ is equal to zero then return 1 else
Step 5: f = x*recfactorial(x-1) and return value of ‘f’
Step 6: Print “recfactorial”
Step 7: b=nonrecfactorial(n)
Step 8: Initialize ‘f’ to one
Step 9: If i<=x then f=f*I until i<=n
Step 10: End for and return ‘f’
Step 11: Print “nonrecfactorial”
Step 12: Exit
Step 13: Stop
Program:
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int num,f;
clrscr();
printf("Enter a number: \n");
scanf("%d", &num);
f = fact(num);
printf("Factorial of %d is: %d", num, f);
getch();
}
int fact(int n)
Page 18
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
{
if(n = = 1)
return 1;
else
return(n*fact(n-1));
}
Expected Output:
Enter a number:5
Factorial of 5 is: 120
Aim:
To print fibonacci series using recursion. For input & output statements we include the header file
<stdio.h> and for clear the screen include the <conio.h>.
Description:
Algorithm:
Step 1: Start
Step 2: Read n
Step 3: a=0, b=1
Step 4: write a, b
Step 5: c= a + b
Step 6: write c
Step 7: a=b
Step 8: b=c
Step 9: n--
Step 10: Repeat Steps 5 to 9 until n>0
Step 11: Stop
Page 19
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void fibonacci(int);
void main()
{
int k, n;
long int i = 0, j = 1, f;
clrscr();
printf("Enter the range of the Fibonacci series: \n");
scanf("%d", &n);
printf("Fibonacci Series: \n");
printf("%2d %2d ", i, j);
fibonacci(n);
getch();
}
void fibonacci(int n)
{
static long int first = 0, second = 1, sum;
if(n > 0)
{
sum = first + second;
first = second;
second = sum;
printf("%ld ", sum);
fibonacci(n-1);
}
}
Expected Output:
Aim:
To find gcd of a number using recursion. For input & output statements we include the header file
<stdio.h> and for clear the screen include the <conio.h>.
Description:
The GCD of two numbers in C, i.e., integer 8 and 12 is 4 because, both 8 and 12 are divisible by 1,
2, and 4 (the remainder is 0) and the largest positive integer among the factors 1, 2, and 4 is 4.
GCD of two numbers in the C program allows the user to enter two positive integer values. Then,
we are going to calculate the Highest Common Factor of those two values.
Page 20
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Algorithm :
Step 1: Start
Step 2: Read ‘a’ and ‘b’
Step 3: Call gcdrecursive(n,m)
Step 4: If n>m then return gcdrecursive(n,m)
Step 5: If n is equal to zero return value of ‘m’ else
Step 6: Return the value of gcdrecursive(n,m%n)
Step 7: Print ‘a’, ‘b’ and gcdrecursive(a,b)
Step 8: Call gcdnonrecursive(p,q)
Step 9: remainder=p-(p/q*q)
Step 10: If remainder is zero then return value of ‘q’ else
Step 11: Call gcdrecursive(q,remainder)
Step 12: Print ‘a’, ‘b’ and gcdnonrecursive(a,b)
Step 13: Exit
Step 14: Stop
Program:
#include<stdio.h>
#include<conio.h>
int findgcd(int, int)
void main()
{
int n1, n2, gcd;
clrscr();
printf("Enter two numbers: \n");
scanf("%d %d", &n1, &n2);
gcd = findgcd(n1, n2);
printf("GCD of %d and %d is: %d \n", n1, n2, gcd);
getch();
}
int findgcd(int x, int y)
{
while(x != y)
{
if(x > y)
return findgcd(x-y, y);
else
return findgcd(x, y-x);
}
return x;
}
Expected Output:
Enter two numbers: 366
60
GCD of 366 and 60 is: 6
Page 21
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To perform addition of two matrices. For input & output statements we include the header file
<stdio.h> and for clear the screen include the <conio.h>.
Description:
Array:- An array is defined as an ordered set of similar data items. All the data items of an array
are stored in consecutive memory locations in RAM. The elements of an array are of same data type
and each item can be accessed using the same name.
Declaration of an array:- We know that all the variables are declared before the are used in the
program. Similarly, an array must be declared before it is used. During declaration, the size of the
array has to be specified. The size used during declaration of the array informs the compiler to
allocate and reserve the specified memory locations.
Algorithm:
Step 1: Start the process.
Step 2: Read the values for m,n,p,q.
Step 3: If(m!=p || n!=q) then goto step 4 else goto step 6.
Step 4: Print ‘addition is not possible’.
Step 5: Initialize I=0,j=0.
Step 6: If(I<m) then goto step 7.
Step 7: If(j<n)then goto step 8.
Step 8: Read a[I][j] goto step 9.
Step 9: Set I=I+1,j=j+1.
Step 10: If(I<p) then goto step 11.
Step 11: If(j<q)then goto step 12.
Step 12: Read b[I][j] goto step 9.
Step 13: Compute & set c[i][j] = a[i][j] + b[i][j].
Step 14: Display the value of c[I][j] goto step 9.
Step 15: Stop the process.
Page 22
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5], b[5][5], c[5][5], i, j, n, m, p, q;
clrscr();
printf("Enter first matrix size: \n");
scanf("%d%d", &m, &n);
printf("Enter second matrix size: \n");
scanf("%d%d", &p, &q);
if(m != p || n != q)
printf("Size mismatch, Addition is not possible \n");
else
{
printf("Enter first matrix elements: \n");
for(i = 0;i < m;i++)
for(j = 0;j < n;j++)
scanf("%d", &a[i][j]);
printf("Enter second matrix elements: \n");
for(i = 0;i < p;i++)
for(j = 0;j < q;j++)
scanf("%d", &b[i][j]);
printf("Addition of two Matrices is \n");
for(i = 0; < m;i++)
{
for(j = 0;j < n;j++)
c[i][j] = a[i][j] + b[i][j];
}
for(i = 0;i < m;i++)
{
for(j = 0;j < n;j++)
printf("%4d", c[i][j]);
printf("\n");
}
}
getch();
}
Expected Output 1:
Page 23
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
5
6
Expected Output 2:
Aim:
To multiply two matrices using arrays. For input & output statements we include the
header file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start the process.
Step 2: Read the values for m,n,p,q.
Step 3: If(n!=p) then goto step 4 else goto step 6.
Step 4: Print ‘multiplication is not possible’.
Step 5: Initialize I=0,j=0.
Step 6: If(I<m) then goto step 7.
Step 7: If(j<n)then goto step 8.
Step 8: Read a[I][j] goto step 9.
Step 9: Set I=I+1,j=j+1.
Step 10: If(I<p) then goto step 11.
Step 11: If(j<q)then goto step 12.
Step 12: Read b[I][j] goto step 9.
Page 24
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Step 13: If((I<m) &&(j<q) )then set c[I][j]=0 else goto step 9.
Step 14: Compute & set c[i][j] = c[I][j]+ a[i][k] * b[k][j].
Step 15: Diplay the value of c[I][j] goto step 9.
Step 16: Stop the process.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5], b[5][5], c[5][5], i, j, n, m, p, q;
clrscr();
printf("Enter first matrix size: \n");
scanf("%d%d", &m, &n);
printf("Enter second matrix size: \n");
scanf("%d%d", &p, &q);
if(n != p)
printf("Not compatible, Multiplication is not possible \n");
else
{
printf("Enter first matrix elements: \n");
for(i = 0;i < m; i++)
for(j = 0;j < n; j++)
scanf("%d", &a[i][j]);
Page 25
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output 1:
Expected Output 2:
Page 26
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program on Linear Search and Binary Search using Recursive and Non – Recursive
Procedures?
Aim:
To implement linear search using recursive procedure. For input & output statements we include the
header file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
int linear(int[], int, int);
void main()
{
int a[100], n, i, x;
clrscr();
printf("Enter Size: \n");
scanf("%d", &n);
printf("Enter %d elements: \n", n);
for(i = 0;i < n;i++)
scanf("%d", &a[i]);
printf("Enter element to search: \n");
scanf("%d", &x);
i=linear(a, n-1, x);
if(i != -1)
printf("The element %d found at %d location", x, i);
else
printf("The element %d is not found", x);
getch();
}
int linear(int a[100], int n, int x)
Page 27
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
{
if(n<= 0)
return -1;
if(a[n] = = x)
return n;
else
return linear(a, n-1, x);
}
Expected Output:
Enter Size: 5
Enter 5 elements: 25 30 12 54 60
Enter element to search: 60
The element 60 found at 4 location
Aim:
To implement linear search using non – recursive procedure. For input & output statements we
include the header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
Linear search technique is also known as sequential search technique. The linear search is a
method of searching an element in a list in sequence. In this method, the array is searched for the
required element from the beginning of the list/array or from the last element to first element of
array and continues until the item is found or the entire list/array has been searched.
Algorithm:
Page 28
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
endif
end for
4: if (loc>0)
Display message “Search is successful and element is found at location:
loc” and Exit
5: else
Display the message “Search Unsuccessful” and exit.
Step 6: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, n, x, xloc = -1;
clrscr();
printf("Enter array size: \n");
scanf("%d", &n);
printf("Enter any %d elements: \n", n);
for(i=0;i<n;i++)
scanf("%d", &a[i]);
printf("Enter the element you want to search for \n");
scanf("%d", &x);
for(i = 0;i < n;i++)
{
if(a[i] = = x)
{
xloc = i;
break;
}
}
if(xloc = = -1)
printf("%d is not found in the array \n", x);
else
printf("%d is found at location %d \n", x, xloc);
getch();
}
Expected Output 1:
Expected Output 2:
Page 29
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To implement binary search using recursive procedure. For input & output statements we include
the header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
Binary search is quicker than the linear search. However, it cannot be applied on unsorted data
structure. The binary search is based on the approach divide-and-conquer. The binary search starts
by testing the data in the middle element of the array. This determines target is whether in the first
half or second half. If target is in first half, we do not need to check the second half and if it is in
second half no need to check in first half. Similarly we repeat this process until we find target in the
list or not found from the list. Here we need 3 variables to identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order. Search is performed as
follows:
• If the key is less than mid positioned item, then the item to be found must be in first half of
array, otherwise it must be in second half of array.
• Repeat the procedure for lower (or upper half) of array until the element is found.
Algorithm:
Page 30
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Step 11: If(ele==a[mid-1]) then set check=1 goto step else goto STEP 12.
Step 12: If(ele<a[mid-1]) then set high=mid-1 else goto step 13.
Step 13: If(ele>a[mid-1]) then set low=mid+1.
Step 14: If(check) then write element is found else write element not found.
Step 15: Stop the process.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define size 10
int binary(int[], int, int, int);
void main()
{
int n, i, key, position;
int low, high, list[size];
clrscr();
printf("\nEnter the total number of elements: \n");
scanf("%d", &n);
printf("Enter the elements of list: \n");
for(i = 0; i < num; i++)
{
scanf("%d", &list[i]);
}
low = 0;
high = num - 1;
printf("Enter element to be searched: \n");
scanf("%d", &key);
position = binary(list, key, low, high);
if(position != -1)
{
printf("Number present at %d \n", position);
}
else
printf("The number is not present in the list \n");
getch();
}
Page 31
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output:
Aim:
To implement binary search using non – recursive procedure. For input & output statements we
include the header file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
X is sorted array. The lb and ub are lower bounds and upper bounds of segment. This
algorithm search for an item and finds the location of item in array X.
Step 1: Start
mid=(beg+end)/2
Page 32
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
et beg= mid+1
else
set flag=1
display the message “Search is successful” and exit.
Step 6: If flag=0 then
Step 7: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, n, x, xloc = -1, low, high, mid;
clrscr();
printf("Enter array size: \n");
scanf("%d", &n);
printf("Enter any %d elements in the sorted order: \n",n);
for(i = 0;i < n;i++)
scanf("%d", &a[i]);
printf("Enter the element you want to search for \n");
scanf("%d", &x);
low = 0;
high = n-1;
while(low <= high)
{
mid = (low+high) / 2;
if(a[mid] = = x)
{
xloc = mid;
break;
}
else if(x < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if(xloc = = -1)
printf("%d is not found in the array \n", x);
else
printf("%d is found at location %d \n", x, xloc);
getch();
}
Expected Output 1:
Page 33
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output 2:
Page 34
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To implement bubble sort. For input & output statements we include the header file <stdio.h> and
for clear the screen include the <conio.h>.
Description:
In bubble sort method the list is divided into two sub-lists sorted and unsorted. The smallest element
is bubbled from unsorted sub-list. After moving the smallest element the imaginary wall moves one
element ahead. The bubble sort was originally written to bubble up the highest element in the list.
But there is no difference whether highest / lowest element is bubbled. This method is easy to
understand but time consuming. In this type, two successive elements are compared and swapping
is done. Thus, step-by-step entire array elements are checked. Given a list of ‘n’ elements the
bubble sort requires up to n-1 passes to sort the data.
Algorithm:
Step 1: Start the process.
Step 2: Read n.
Step 3: Set i=0.
Step 4: If(i<n) then goto step 5 else goto step 7.
Step 5: Read a[i].
Step 6: Set i=i+1 and goto step 4.
Step 7: Set i=0.
Step 8: If(i<n-1) then goto step 9.
Step 9: Set j=i+1 then goto step 10 else go to step 14.
Step 10: If(j<n) then goto step 11else goto step 14.
Step 11: If(a[i]>a[j]) then goto step 12.
Step 12: Set temp=a[i].
a[i]=a[j].
a[j]=temp.
Step 13: Set j=j+1 and goto step 10.
Step 14: Set i=i+1 and goto step 8.
Step 15: Set i=0.
Step 16: If(i<n) then goto step 17 else goto step 19.
Page 35
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, j, n, temp;
clrscr();
printf("Enter array size: \n");
scanf("%d", &n);
printf("Enter any %d elements: \n", n);
for(i = 0;i < n;i++)
scanf("%d", &a[i]);
for(i = 1;i <= n-1;i++)
{
for(j = 0;j < n-i;j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("After sorting, the element are \n");
for(i = 0;i < n;i++)
printf("%4d", a[i]);
getch();
}
Expected Output:
Page 36
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To implement selection sort. For input & output statements we include the header file <stdio.h> and
for clear the screen include the <conio.h>.
Description:
In selection sort the list is divided into two sub-lists sorted and unsorted. These two lists are divided
by imaginary wall. We find a smallest element from unsorted sub-list and swap it to the beginning.
And the wall moves one element ahead, as the sorted list is increases and unsorted list is decreases.
Assume that we have a list on n elements. By applying selection sort, the first element is compared
with all remaining (n-1) elements. The smallest element is placed at the first location. Again, the
second element is compared with remaining (n-1) elements. At the time of comparison, the smaller
element is swapped with larger element. Similarly, entire array is checked for smallest element and
then swapping is done accordingly. Here we need n-1 passes or iterations to completely rearrange
the data
Algorithm:
Step 1: Start
Step 2: Read size of array ‘n’
Step 3: Read number of elements of an array ‘a[i]’
Step 4: Call ‘selection_sort()’ function
Step 5: for(i=0;i<n;i++)
Step 6: Equate ‘min’ to ‘i’
Step 7: for(j=i+1;j<n;j++)
Step 8: If ‘a[j]’ is greater than ‘a[min]’ then
Step 9: Equate ‘min’ to ‘j’
Step 10: End for
Step 11: ‘temp = a[i]’
Step 12: ‘a[i]=a[min]’
Step 13: ‘a[min]=temp’
Step 14: End for
Step 15: Print all the elements in the array ‘after sorting’
Step 16: Exit
Step 17: Stop
Page 37
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, j, n, temp, maxloc, k;
clrscr();
printf("Enter array size: \n");
scanf("%d", &n);
printf("Enter any %d elements: \n", n);
for(i = 0;i < n;i++)
scanf("%d", &a[i]);
for(i = 0;i < n-1;i++)
{
maxloc = 0;
for(j = 0;j <= (n-1-i);j++)
{
if(a[j] > a[maxloc])
maxloc = j;
}
temp = a[n-1-i];
a[n-1-i] = a[maxloc];
a[maxloc] = temp;
}
printf("After sorting, the element are \n");
for(i = 0;i < n;i++)
printf("%4d", a[i]);
getch();
}
Expected Output:
Page 38
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To print address of each individual element of an array. For input & output statements we include
the header file <stdio.h>, for clear the screen include the <conio.h>
Description:
Pointer is a user defined data type that creates special types of variables which can hold the address
of primitive data type like char, int, float, double or user defined data type like function, pointer etc.
or derived data type like array, structure, union, enum.
Examples:
int *ptr; int (*ptr)();
int (*ptr)[2];
Benefits of using pointers are:-
1) Pointers are more efficient in handling arrays and data tables.
2) Pointers can be used to return multiple values from a function via function arguments.
3) The use of pointer arrays to character strings results in saving of data storage space in
memory.
4) Pointers allow C to support dynamic memory management.
5) Pointers provide an efficient tool for manipulating dynamic data structures such as structures ,
linked lists , queues , stacks and trees.
6) Pointers reduce length and complexity of programs.
7) They increase the execution speed and thus reduce the program execution time.
Algorithm:
Step 1: Start
Step 2: Declare an array
Step 3: enter the number of elements
Step 4: Print the address of each element in the array
Step 5: Stop
Program :
#include<stdio.h>
int main()
{
Page 39
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
int
x[4];
int i;
for( i = 0; i < 4; ++i )
{
printf(“&x[%d] = %u\n”,I, &x[i]);
}
printf("Addressofarrayx:%u",x);
return 0;
}
Expected Output:
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Aim:
To implement pointer to Functions. For input & output statements we include the header file
<stdio.h>, for clear the screen include the <conio.h>
Description:
Pointers can be used to pass addresses of variables to called functions, thus allowing the called
function to alter the values stored there.
Passing only the copy of values to the called function is known as "call by value". Instead of
passing the values of the variables to the called function, we pass their addresses, so that the called
function can change the values stored in the calling routine. This is known as "call by reference",
since we are referencing the variables.
Page 40
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Here the addresses of actual arguments in the calling function are copied into formal arguments of
the called function. Here The formal parameters should be declared as pointer variables to store
the address.
Algorithm:
Step 1: Start
Step 2: Declare a function to swap two numbers
Step 3: Enter two integer numbers to be swapped
Step 4: return to main function
Step 5: End
Program:
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2=%d",num2);
return 0;
}
void swap(int* n1, int*n2)
{
int temp;
temp=*n1;
*n1 = *n2;
*n2 = temp;
}
Expected Output:
num1 = 10
num2 = 5
Page 41
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To find the length of a given string using library function. For input & output statements we include
the header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
Declaring Strings:- Since strings are group of characters, generally we use the structure to store
these characters is a character array.
Char name[30];
Initializing strings:-
Char city[8]={‘N’,’E’,’W’,’Y’,’O’,’R’,’K’,’\0’};
The string city size is 8 but it contains 7 characters and one character space is for NULL terminator.
A string is stored in array, the name of the string is a pointer to the beginning of the string.
If we use one-character string it requires two locations. The difference shown below,
Page 42
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Because strings are variable-length structure, we must provide enough room for maximum-length
string to store and one byte for delimiter.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char arr[ ] = "Methodist College" ;
int len1, len2 ;
clrscr();
len1 = strlen (arr) ;
len2 = strlen ("Engineerimg") ;
printf ("String = %s length = %d \n", arr, len1) ;
printf (“String = %s length = %d \n", "Engineerimg", len2) ;
getch();
}
Expected Output:
9. b). Copy the given String to another String using Library Function?
Aim:
To copy the given string to another string using library function. For input & output statements we
include the header file <stdio.h> and for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char source[ ] = "Methodist College of Engineering & Technology" ;
char target[20] ;
cltscr();
strcpy(target, source) ;
printf("Source String = %s \n", source ) ;
printf("Target String = %s \n", target ) ;
Page 43
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
getch();
}
Expected Output:
9. c). Appending one String at the end of another String using Library Function?
Aim:
To appends one string at the end of another string using library function. For input & output
statements we include the header file <stdio.h> and for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char source[ ] = "Methodist College";
char target[30] = “Welcome to”;
cltscr();
strcat ( target, source) ;
printf("Source String = %s \n", source);
printf("Target String = %2s \n", target);
getch();
}
Expected Output:
9. d). Reverse the Contents of the given String using Library Function?
Aim:
To reverse the contents of the given string using library function. For input & output statements we
include the header file <stdio.h>, for clear the screen include the <conio.h> and for string functions
include <string.h>.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
Page 44
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
{
char a[20];
cltscr();
printf(“Enter any string: \n”);
gets(a);
strrev(a);
printf(“Reverse string: \n”, a);
getch();
}
Expected Output:
9. e). Compare the Contents of given two Strings using Library Function?
Aim:
To compare the contents of the given two strings using library function. For input & output
statements we include the header file <stdio.h> and for clear the screen include the <conio.h>.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char string1[ ] = "Methodist";
char string2[ ] = “MCET”;
int i, j, k;
cltscr();
i = strcmp(string1, “Methodist”);
j = strcmp(string1, string2);
k = strcmp(string1, “Methodist College”);
printf("i = %d \n", i);
printf("j = %d \n", j);
printf("k = %d \n", k);
getch();
}
Expected Output:
i=0
j = 34
k = -32
Page 45
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To abbreviate the contents of the given string using library function. For input & output statements
we include the header file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start
Step 2: Declare a file pointer fp, ch
Step 2: Attach filename using fp=fopen(“filename”,”r+”)
Step 3: Read n (no.of characters from given file until end of the file)
Step 4: Print the characters
Step5: Close file pointer
Step 6: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100];
int i;
clrscr();
printf("Enter a String: \n");
gets(s);
i = 0;
while(s[i] = = ' ')
i++;
putchar(s[i]);
putchar(' ');
while(s[i] != '\0')
{
if(s[i] = = ' ' && s[i+1] != ' ')
{
putchar(s[i+1]);
putchar(' ');
}
i++;
}
getch();
}
Expected Output:
Page 46
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
10. a). Print employees name and gross salary using structures.
Aim:
To print employees name and gross salary using structures.
Description:
A structure is a collection of one or more variables of different data types, grouped together under a
single name. By using structures variables, arrays, pointers etc can be grouped together.
The structure definition associated with the structure name is referred as tagged structure. It does
not create an instance of a structure and does not allocate any memory.
The structure definition associated with the keyword typedef is called type-defined structure.
General Syntax:
struct tag_name {
type member1;
type member2;
/* declare as many members as desired, but the entire structure size must be known to the
compiler. */
};
Algorithm:
Step 1: Start
Step 2: Declare structure for employee details
Step 3: Read 100 employee details
Step 4: Repeat loop 100 employees and calculate gross salary of each employee
Step 5: Print each employee name and gross salary
Step 6: Stop
Program:
#include<stdio.h>
struct employee
{
char name[20];
float basic;
float da;
float gross;
Page 47
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
}e[5];
void main()
{
int i;
for(i=0;i<5;i++)
scanf("%s%f",e[i].name,&e[i].basic);
for(i=0;i<5;i++)
{
e[i].da=52.0/100*e[i].basic;
e[i].gross=e[i].da+e[i].basic;
printf("\n name=%s gross=%f",e[i].name,e[i].gross);
}
}
Expected Output:
Aim:
To display your present address using union
Description:
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
Syntax of Union
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
Page 48
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Algorithm:
Step 1: Start
Step 2: Declare union for address details
Step 3: Assign address to union
Step 4: Print union details
Step 5: Stop
Program:
#include<stdio.h>
#include<string.h>
union details
{
char name[20];
char home_add[30];
char hostel_add[30];
char city[10];
char state[10];
int pincode;
}a;
void main()
{
strcpy(a.name,"rama");
printf("\n %s",a.name);
strcpy(a.home_add,"1-83/10,jublie hills");
printf("\n %s",a.home_add);
strcpy(a.hostel_add,"mcet college");
printf("\n %s",a.hostel_add);
strcpy(a.city,"hyderabad");
printf("\n %s",a.city);
strcpy(a.state,"telangana");
printf("\n %s",a.state);
a.pincode=500043;
printf("\n %d",a.pincode);
getch();
}
Expected Output:
rama
1-83/10, jublie hills
mcet college
Hyderabad
Telangana
500043
Page 49
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
PROGRAM 11. Finding the No. of Characters, Words and Lines of given Text File?
Aim:
To find the no. of characters, words and lines of given text file. For input & output statements we
include the header file <stdio.h> and for clear the screen include the <conio.h>.
Description:
Naming and opening a file: A name is given to the file used to store data. The file name is a string
of characters that make up a valid file name for operating system. It contains two parts. An optional
name and an optional period with extension.
fp is a pointer to data type file. It acts as link between systems and program. Filename is the name
of the file.
For reading data from file, Input functions used are (Input and output operations on files)
a) getc(); It is used to read characters from file that has been opened for read operation.
This statement reads a character from file pointed to by file pointer and assign to c. It returns an
end-of-file marker EOF, when end of file as been reached
b) fscanf(); This function is similar to that of scanf function except that it works on files.
Example : fscanf(f1,”%s%d”,str,&num);
The above statement reads string type data and integer types data from file.
d) fgets(): This function reads a string from a file pointed by a file pointer. It also copies the
string to a memory location referred by an array.
Syntax: fgets(string,no of bytes,filepointer);
e) fread(): This function is used for reading an entire structure block from a given file.
Page 50
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Syntax: fread(&struct_name,sizeof(struct_name),1,filepointer);
a) putc(): This function writer a character to a file that has been opened in write mode.
Syntax: putc(variable,fp);
This statement writes the character contained in character variable c into a file whose pointer is fp.
Syntax: fprintf(f1,”%s,%d”,str,num);
d) fputs(): This function writes a string into a file pointed by a file pointer.
Syntax: fputs(string,filepointer);
e) fwrite(): This function is used for writing an entire block structure to a given file. Syntax:
fwrite(&struct_name,sizeof(struct_name),1,filepointer);
Closing a file:
A file is closed as soon as all operations on it have been completed. Library function for closing a
file is fclose(file pointer);
Syntax: fclose(fp);
This statement closes a file pointed by file pointer fp. Or fcloseall(), to close all opened files at a
time.
Algorithm:
Step 1: Start
Step 2: Initialize str[100], i=0, l=0 and f=1
Step 3: Read string ‘str’
Step 4: for(i=0;str[i]!=’\0’;i++)
Step 5: Equate ‘l’ is equal to ‘l’ plus 1 until str[i]!=’\0’
Step 6: End for
Step 7: Print number of characters in the string
Step 8: for(i=0;i<=l-1;i++)
Step 9: if ‘str[i]’ is equal to space then increment ‘f’ by 1
Page 51
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Expected Output:
Page 52
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Aim:
To create a file. For input & output statements we include the header file <stdio.h> and for
clear the screen include the <conio.h>.
Description:
In order to perform the file operations in C we must use the high level I/O operation functions
which are in C standard I/O library.
i) fopen():
The function fopen is one of the Standard Library functions and returns a file pointer which you
use to refer to the file you have opened e.g.
The above statement opens a file called prog.c for reading and associates the file pointer fp with
the file.When we wish to access this file for I/O, we use the file pointer variable fp to refer to it.
You can have up to about 20 files open in your program - you need one file pointer for each file you
intend to use.
ii) fclose():
Closing a file ensures that all outstanding information associated with the file is flushed out from
the buffers and all links to the file are broken.
Another instance where we have to close a file is to reopen the same file in a different mode.
fclose (file_pointer);
Once a file is closed, its file pointer can be reused for another file.
iii) getc():
getc() is used to read a character from a file that has been opened in a read mode. For example
the statement
c=getc(fp);
would read a character from the file whose file pointer is fp. The file pointer moves by one
character for every operation of getc(). The getc() will return an end-of –marker EOF, when an end
of file has been reached.
Page 53
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
In order to handle a group of mixed data simultaneously there are two functions that are fprintf()
and fscanf().These two functions are identical to printf and scanf fuctions,except they work on files.
The first argument of these functions is a file pointer which specifies the file to be used . the general
form of fprintf is
fprintf(fp,”control string”,list);
where fp is a file pointer associated with a file that has been opened for writing . the control string
contains output specifications for the items in the list. .
fprintf(fp,”%s %f %d”,name,6.6,age);
Like fprintf fscanf() also contains the same syntax which is used to read a no of values from a file.
fscantf(fp,”control string”,list);
like scanf , fscanf also returns the number number of items that are successfully read.when the end
of file is it returns the value EOF.
The getw() and putw() are integer oriented functions .They are similar to the getc() and putc()
functions and are used to read and write integer values . These functions would be useful when we
deal with only integer data. The general form of
putw(integer,fp); getw(fp);
vii) ftell:-
ftell takes a file pointer and returns a number of type long, that corresponds to the current position.
This function is useful in saving the current position of the file,which can be later used in the
program.
Syntax: N=ftell(fp);
N would give the Relative offset (In bytes) of the current position. This means that already n bytes
have a been read or written.
viii) rewind:-
It takes a file pointer and resets the position of to the start of the file.
Syntax:
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to start of the file by rewind. The first
byte in the file is numbered 0,second as 1, so on. This function helps in reading the file more than
once, without having to close and open the file.
Page 54
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
xi) fseek:-
fseek function is used to move the file pointer to a desired location in the file.
is a pointer to the file concerned, offset is a number or variable of type file pointers.long,and
position is an integer number. The offset specifies the number of
Algorithm:
Step 1: Start
Step 2: Declare a file pointer fp, ch
Step 2: Attach filename using fp=fopen(“filename”,”r+”)
Step 3: Read n (no.of characters from given file until end of the file)
Step 4: Print the characters
Step5: Close file pointer
Step 6: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("text.dat", "w");
printf("Enter text, to stop press Ctrl – Z: \n");
while((ch = getchar()) != EOF)
{
fputc(ch,fp);
}
fclose(fp);
getch();
}
Expected Output:
Page 55
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
12. b). Program to print the contents of the file on the monitor?
Aim:
To print the contents of the file on the monitor. For input & output statements we include the header
file <stdio.h> and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start
Step 2: Declare a file pointer fp, ch
Step 3: Attach filename using fp=fopen(“filename”,”r+”)
Step 4: Read n (no.of characters from given file until end of the file)
Step 5: Print the characters
Step 6: Close file pointer
Step 7: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("text.dat", "r");
if(fp==NULL)
printf("No such file \n");
else
{
printf("File contents are: \n");
while(!feof(fp))
{
ch = fgetc(fp);
Page 56
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
putchar(ch);
}
fclose(fp);
}
getch();
}
Expected Output 1:
Given text.dat
File contents are:
This is my first program
in C to create a file with some text.
Bye
To see the contents of the file open text.dat
in any editor.
Expected Output 2:
Given example.dat
No such file
Aim:
To copy one file into another. For input & output statements we include the header file <stdio.h>
and for clear the screen include the <conio.h>.
Algorithm:
Step 1: Start
Step 2: create two file pointers
Step 3: open first file in read mode
Step 4: open second file in write mode using another file pointer.
Step 5: If either of the two file pointers are NULL, then print unable to open file
Step 6: read the character from first file and convert it to uppercase and write that character
into second file
Step 7: repeat Step 6 till end of first file
Step 8: close both the files
Step 9: Stop.
Page 57
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs, *ft ;
char ch;
clrscr();
fs = fopen ("text.dat", "r");
if( fs == NULL )
{
puts ("Cannot open source file");
}
ft = fopen ("example.dat", "w");
if(ft == NULL)
{
puts("Cannot open target file");
fclose(fs);
}
while (1)
{
ch = fgetc (fs);
if(ch = = EOF)
break;
else
{
fputc (ch, ft);
puts("File copied");
}
}
fclose (fs);
fclose (ft);
getch();
}
Expected Output:
File copied
Page 58
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
ADDITIONAL PROGRAMS
Algorithm:
1. Start
2. Pass a to arguments argc and argv in main function
3. Check the condition argc equal to 2 then printf the argv[1] value
4. Else if argc is greter than 2 the print Too many arguments supplied
5. Else One argument expected
6. Stop
Program :
#<include stdio.h>
#include<string.h>
void main(int argc,char *argv[])
{
int i;
printf("\n total no of
arguments=%d",argc);
for(i=0;i<argc;i++)
printf("\n args[%d]=%s",i,argv[i]);
}
Expected Output:
total no of arguments = 4
args[0] = c:\pathname
args[1] = ram
args[2] = ravi
args[3] = raj
Page 59
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Algorithm:
1. Start
2. Define PI constant value 3.14
3. Define macro function to pass a radius value as a argument
4. Call the macro function
5. Print the result
6. Stop
Program:
#include<stdio.h>
#include<math.h>
#define PI 3.142
#define volume(r) ((4/3.0)*PI*pow(r,3))
void main()
{
int r; float v;
scanf("%d",&r);
v=volume(r);
printf("\n volume of the sphere v=%.3f",v);
}
Expected Output:
Volume of sphere 5 = 314.15
Volume of sphere 10 =1256.6000
Volume of sphere 15 = 2827.35000
Page 60
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
Algorithm:
1. Start
2. Read roman numbers
3. Repeat loop for all given roman letters and convert each letter into digit and add to
variable
4. Print the result
5. Stop
Program:
#include<stdio.h>
#include<string.h>
void main()
{
char a[10];
int total[10],sum=0,i,l;
printf("\n enter a roman number: ");
gets(a);
l=strlen(a);
for(i=0;i<l;i++)
{
switch(a[i])
{
case 'M': total[i]=1000; break;
case 'D': total[i]=500; break;
case 'C': total[i]=100; break;
case 'L': total[i]=50; break;
case 'X': total[i]=10; break;
case 'I': total[i]=1; break;
}
sum=sum+total[i];
}
for(i=0;i<l-1;i++)
if(total[i]<total[i+1])
sum=sum-2*total[i];
printf("\n the decimal equivalent is %d",sum);
}
Expected Output:
enter a roman number: XVII
the decimal equivalent is 17
Page 61
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
1. INTRODUCTION TO C
1) What is an algorithm?
2) What is a flowchart?
1) What is a C token?
Page 62
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
22) List different bit-wise operators. What is the use of bit-wise operators?
3. CONTROL STRUCTURES
while(1) {…}
for( ; ; ) {…}
Page 63
MCET PROGRAMMING FOR PROBLEM SOLVING LAB MANUAL
22) In switch control structure if there is no break statement in particular case block then
what happen?
25) Write the recurrence relation to find the factorial of a given number.
4. SORTING TECHNIQUES
1) How many number of comparisons required to sort n numbers using bubble sort?
5. SEARCHING TECHNIQUES
2) If the file contains large number of records in sorted order based on a key, then which
Page 64