C & Matlab Lab Manual Format PDF
C & Matlab Lab Manual Format PDF
for
IVth Semester
Department of Mechanical
Engineering
Saveetha School of
Engineering
WINDOWS OS GCC
gcc filename
The default executable output of gcc is "a.out", which can be run by typing “ ./a.out”. It is
also possible to specify a name for the executable file at the command line by using the
syntax -o outputfile , as shown in the following example : -
Again, you can run your program with "./outputfile". (The ./ is there to ensure you run the
program for the current working directory.)
Note: If you need to use functions from the math library (generally functions from math.h
such as sin or sqrt), then you need to explicitly ask it to link with that library with the -l
flag and the library 'm':
Open Turbo C from your Desktop or Programs menu. Select “File” from Menu bar and
select option “New” and Save C program in filename .C extension.
If the compilation is success – you will see a “Success” message. Else you will see the
number of errors.
To RUN the program – you may select ->Run f rom menu and click ->
Run
Aim:
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Addition (x = a + b)
Program:
#include<stdio.h>
main ()
scanf("%d",&n);
for(q=1;q<=n;q++)
scanf("%d",&m);
p=m+p;
return 0;
} Result:
Aim:
To evaluate the LCM and GCD of any two integers that are given as
input.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
• GCD: In mathematics, the greatest common divisor (gcd) of two or more integers,
which are not all zero, is the largest positive integer that divides each of the integers.
For example, the gcd of 8 and 12 is 4.
• LCM: In mathematics, the least common multiple, lowest common multiple, or
smallest common multiple of two integers a and b is the smallest positive integer that
is divisible by both a and b.
Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
r = b; while (a % b !=
0) {
r = a % b; a = b; b =
r; } return r; } int
lcm(int x, int y) {
int a; a = (x > y) ? x : y; // a is greater
number while (1) {
if (a % x == 0 && a % y == 0)
Aim:
To simulate a calculator and perform the selected arithmetic operation on any two
numbers that are given as input.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Addition (x = a + b)
Subtraction (x = a - b)
Multiplication (x = a * b)
Division (x = a / b)
Program:
# include <stdio.h>
int main() {
switch(operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf",num1, num2, num1 + num2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",num1, num2, num1 - num2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",num1, num2, num1 * num2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", num1, num2, num1 / num2);
break;
default:
printf("Error! Entered operator is not correct"); }
return 0; }
Result:
The program is compiled, executed and the output is
verified.
OUTPUT:
Experiment 4
To create a C program that can count the vowels, consonants, numbers and spaces in
a entered string of characters.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
N/A
Program:
#include <stdio.h>
int main() {
char line[150]; int i, vowels,
consonants, digits, spaces;
printf("Vowels: %d",vowels);
printf("\nConsonants:
%d",consonants); printf("\nDigits:
%d",digits); printf("\nWhite spaces:
%d", spaces);
return 0; }
Result:
The program is compiled, executed and the output is
verified.
OUTPUT:
Experiment 5
C Program to calculate the standard deviation of any given data
Aim:
To create a C program that can calculate the standard deviation of any set of given
numerical data.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Standard deviation, s = √∑ (xi−x)2 Ni=1
N
Program:
#include <stdio.h>
#include <math.h>
#define N 25
main()
{
int i, n;
float x[N];
float sum = 0, mean, var=0, SD;
printf("Enter the total number of data values: ");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
printf("Enter data value %d: ", i);
scanf("%f", &x[i]);
}
for(i=1; i<=n; i++)
sum = sum + x[i];
mean = sum/n;
SD = sqrt(var/n);
return 0;
} Result:
Aim:
To create a C program that can construct a Pascal Triangle for any given number of
rows.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
N/A
Program:
#include <stdio.h>
int main()
scanf("%d",&rows);
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
printf("\n");
return 0;
} Result:
else if (discriminant == 0)
else
realPart = -b/(2*a);
imaginaryPart = sqrt(-discriminant)/(2*a);
}
return 0;
} Result:
Aim:
To create a C program that can compute and display the Fibonacci series upto any
number of values.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Program:
#include <stdio.h>
int main()
{
scanf("%d", &n);
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
printf("%d\n", next);
return 0;
} Result:
Aim:
To create a C program that can convert any given decimal number into its equivalent
binary number.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
N/A
Program:
#include <stdio.h>
int main()
int n, c, k;
scanf("%d", &n);
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
printf("\n");
return 0;
} Result:
Aim:
To create a C program that can find and display any number of prime numbers in the
ascending order.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
Program:
#include<stdio.h>
int main()
int n, i = 3, count, c;
scanf("%d",&n);
if ( n >= 1 )
printf("2\n");
{
if ( i%c == 0 )
break;
}
if ( c == i )
printf("%d\n", i);
count++;
i++;
return 0;
} Result:
Aim:
To evaluate the area moment of inertia of the standard geometric shapes - square,
rectangle, circle, semi-circle, triangle, and ellipse.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language. Application of the
programming knowledge in mechanical engineering domain.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Program:
#include<stdio.h>
#include<math.h>
float pi = 3.14159;
main() {
int sect, cont; float a, b, d, r, h; float A, x, y, MOIx, MOIy, MOId;
printf("Program to calculate section properties for standard
sections\n\n"); printf("NOTE: Please enter all dimensions in cm \n\n");
REPEAT: printf("1. Square \n2. Rectangle \n3. Circle \n4. Semi-circle \n5. Triangle \n6.
Ellipse \n\n"); printf("Choose the type of section (1, 2, 3, 4, 5, or 6):\n");
scanf("%d", §);
switch(sect) {
case 1: /* Square */
printf("Enter dimensions:\n"); printf("Side of square, a = "); scanf("%f", &a);
A = a * a; x = a * 0.5; y = a * 0.5; MOIx = (a*a*a*a)/12; printf("Area = %.3f
cm^2\n", A); printf("Centroid = (%.1f,%.1f)\n", x, y); printf("Moment of
Inertia about x-axis through centroid = %.3f cm^4\n", MOIx);
printf("Moment of Inertia about y-axis through centroid = %.3f cm^4\n",
MOIx); break; case 2: /* Rectangle */
printf("Enter dimensions:\n"); printf("Width of rectangle, b = ");
scanf("%f", &b); printf("Height of rectangle, d = "); scanf("%f", &d); A
= b * d; x = b * 0.5; y = d * 0.5; MOIx = (b*d*d*d)/12; MOIy =
(b*b*b*d)/12; printf("Area = %.3f cm^2\n", A); printf("Centroid =
(%0.1f,%.1f)\n", x, y); printf("Moment of Inertia about x-axis through
centroid = %.3f cm^4\n", MOIx); printf("Moment of Inertia about
y-axis through centroid = %.3f cm^4\n", MOIy); break;
case 3: /* Circle */
printf("Enter dimensions:\n"); printf("Radius of the circle, r = "); scanf("%f",
&r); A = pi * r * r; x = r; y = r; MOIx = (pi*r*r*r*r)/4; printf("Area = %.3f
cm^2\n", A); printf("Centroid = (%0.1f,%.1f)\n", x, y); printf("Moment of
Inertia about x-axis through centroid = %.3f cm^4\n", MOIx);
printf("Moment of Inertia about y-axis through centroid = %.3f cm^4\n",
MOIx); break; case 4: /* Semi Circle */
printf("Enter dimensions:\n"); printf("Radius of the semi-circle, r = ");
scanf("%f", &r); A = pi * r * r / 2; x = r; y = 4 * r / (3 * pi); MOId =
(pi*r*r*r*r)/8; MOIx = 0.11 * r*r*r*r; printf("Area = %.3f cm^2\n", A);
printf("Centroid = (%0.1f,%.1f)\n", x, y); printf("Moment of Inertia about the
diameter = %.3f cm^4\n", MOId); printf("Moment of Inertia about x-axis
through centroid = %.3f cm^4\n", MOIx); break; case 5: /* Triangle */
printf("Enter dimensions:\n"); printf("Base
length of the Triangle, b = "); scanf("%f",
&b); printf("Height of Triangle, h = ");
scanf("%f", &h); A = 0.5 * b * h; x = b / 3;
y = h / 3; MOIx = (b*h*h*h)/36; MOIy =
(b*b*b*h)/48; printf("Area = %.3f cm^2\n",
A);
printf("Centroid = (%0.1f,%.1f)\n", x, y); printf("Moment of Inertia about
x-axis through centroid = %.3f cm^4\n", MOIx); printf("Moment of Inertia
about y-axis through centroid = %.3f cm^4\n", MOIy); break; case 6: /*
Ellipse */
printf("Enter dimensions:\n"); printf("Major axis of the Ellipse, a = ");
scanf("%f", &a); printf("Minor axis of the Ellipse, b = "); scanf("%f", &b); A
= pi * a * b / 4; x = a / 2; y = b / 2; MOIx = (pi * a * b * b * b)/64; MOIy = (pi
* a * a * a * b)/64; printf("Area = %.3f cm^2\n", A); printf("Centroid =
(%0.1f,%.1f)\n", x, y); printf("Moment of Inertia about x-axis through
centroid = %.3f cm^4\n", MOIx); printf("Moment of Inertia about y-axis
through centroid = %.3f cm^4\n", MOIy); break; default:
printf("Incorrect entry for selection, please try again..."); break; }
printf("Do you want to continue? Type '1' for YES: \n");
scanf("%d",&cont);
if(cont==1)
goto REPEAT; printf("End
Aim:
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language. Application of the
programming knowledge in mechanical engineering domain.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
Fx = F * cos θ; Fy = F * sin θ;
Magnitude of Resultant R = √(ΣFx)2 + (ΣFy)2
Program:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
main ()
int i, n;
val = PI / 180;
for(i=1;i<=n;i++)
scanf("%lf", &F);
printf("Enter the angle of Force-%d from positive x-axis (in deg 0-360): ",
i);
scanf("%lf", &T);
Fx = Fx+(F*cos(T*val));
Fy = Fy+(F*sin(T*val));
R = sqrt((Fx*Fx)+(Fy*Fy));
A = (atan(Fy/Fx))/val;
printf("The Resultant of the %d forces is %.2lf N acting at %.2lf deg from positive
x axis", n, R, A);
printf("\n\nEnd of program");
return 0;
} Result:
Aim:
To analyse the vibrations of a simple spring-mass system and to determine the natural
frequency of the system.
Objectives:
Study about basic building blocks such as constants, variables, keywords, operators,
expressions and input - output statements in C language. Application of the
programming knowledge in mechanical engineering domain.
Tools/Equipment:
Editors like TurboC in Windows (or an online C Compiler through web browser),
desktop or laptop computer.
Formula Used:
√g
Natural frequency of vibration, N = 1 2π x
Program:
#include<stdio.h>
#include<math.h>
#define g 9.81
#define pi 3.14159265
main()
float m, k, r, x, n, t, v;
printf("Program to determine the Natural Frequency of a simple Spring-Mass
system\n\n");
scanf("%f", &m);
scanf("%f", &k);
scanf("%f", &r);
x = m*g/k; /* natural deflection of the spring mass system */
if (x<=0.001)
else
return 0;
} Result:
Cleve Moler, the chairman of the computer science department at the University
of New Mexico, started developing MATLAB in the late 1970s. He designed it to give his
students access to LINPACK and EISPACK without them having to learn Fortran. It
soon spread to other universities and found a strong audience within the applied
mathematics community. Jack Little, an engineer, was exposed to it during a visit Moler
made to Stanford University in 1983. Recognizing its commercial potential, he joined
with Moler and Steve Bangert. They rewrote MATLAB in C and founded MathWorks in
1984 to continue its development. These rewritten libraries were known as JACKPAC.
In 2000, MATLAB was rewritten to use a newer set of libraries for matrix manipulation,
LAPACK.
plot (x,y);
xgrid;
endfunction;
Result:
The program is compiled and executed. The 2D graph is plotted and the output is
verified.
OUTPUT:
GRAPH PLOT:
Experiment 15
Aim:
To plot cycloid curve for the given radius of circle and number of
rotations.
Objectives:
Learn the usage of functions i n MATLAB and also to learn the various 2D graph plotting
commands.
Tools/Equipment:
MATLAB in Windows (or any equivalent compiler like OCTAVE or SCILAB), desktop or
laptop computer.
Formula Used:
Co-ordinates for a cycloid curve,
x = a (θ − sinθ); y = a (1 − cosθ);
Program:
t = 0:5:a; x = r * ((t*pi/180) -
sin(t*pi/180));
y = r * (1 - cos (t*pi/180));
plot (x,y,'k');
ylabel ('Height');
xgrid;
endfunction;
Result:
The program is compiled and executed. The 2D graph is plotted and the output is
verified.
OUTPUT:
GRAPH PLOT:
Experiment 16
MATLAB Program to plot the position and velocity of slider in a slider-crank mechanism
Aim:
To plot the position curve and velocity curve of a slider in a slider-crank mechanism for
the given link dimensions and crank rotation speed.
Objectives:
Learn the usage of functions i n MATLAB and also to learn the various 2D graph plotting
commands.
Tools/Equipment:
MATLAB in Windows (or any equivalent compiler like OCTAVE or SCILAB), desktop or
laptop computer.
Formula Used:
Slider position, S = L − R
2
+ R(sinθ + R sin2θ) cos2θ)
4L 4L Slider velocity, V = ω R (cosθ + R
2L NOTE: Rotational
speed ω and angle θ are measured in radians.
Program:
function slider (r, l, N, a);
pi = 3.1415926535897932384626433832795;
t = 0:pi/50:2*pi*a;
P = l - (r*r/(4*l)) + r*(sin(t) + (r*sin(2*t) / (4*l)));
V = (2*pi*N/60) *r * (cos (t) + (r*cos(2*t)/(2*l)));
subplot (2, 1, 1);
plot (t,P,'r', 'Linewidth', 2);
title ('SLIDER POSITION CURVE');
xlabel ('Angle of Crank rotation, radians');
ylabel ('Slider position');
xgrid;
subplot (2, 1, 2);
plot (t,V,'g', 'Linewidth', 2);
xgrid;
endfunction;
Result:
The program is compiled and executed. The 2D graph is plotted and the output is
verified.
OUTPUT:
GRAPH PLOT:
Experiment 17
SIMULINK model for simulating a water tank level control using PID
controller
Aim:
To simulate the working of a non-linear Water-Tank System plant controlled using a PID
controller in a single-loop feedback system.
Objectives:
Learn the simulation environment in SIMULINK and to understand the various blocks
used in the simulation models.
Tools/Equipment:
MATLAB - SIMULINK environment in Windows (or any equivalent software like XCOS
in SCILAB), desktop or laptop computer.
Model design:
Water enters the tank from the top at a rate proportional to the voltage, V, applied to the
pump. The water leaves through an opening in the tank base at a rate that is
proportional to the square root of the water height, H, in the tank. The presence of the
square root in the water flow rate results in a nonlinear plant.
Aim:
Objectives:
Learn the simulation environment in SIMULINK and to understand the various blocks
used in the simulation models.
Tools/Equipment:
MATLAB - SIMULINK environment in Windows (or any equivalent software like XCOS
in SCILAB), desktop or laptop computer.
Model design:
The above figure shows a schematic diagram of the basic model. The model directs the
pump flow, Q, to supply pressure, p1, from which laminar flow, q1ex, leaks to exhaust.
The control valve for the piston/cylinder assembly is modelled as turbulent flow through
a variable-area orifice. Its flow, q12, leads to intermediate pressure, p2, which
undergoes a subsequent pressure drop in the line connecting it to the actuator cylinder.
The cylinder pressure, p3, moves the piston against a spring load, resulting in position
x.
Simulation Model:
The pump subsystem:
The valve-cylinder-piston-spring
subsystem:
Result:
Traditional systems languages such as C++, Ada, and Java evolved to solve
problems that arise in large-scale programming, where the primary emphasis is on
structure and discipline. They were not designed to make writing small- or
medium-scale programs easy. The recent rise in popularity (in industry, if not
necessarily in academia) of scripting (sometimes called “agile”) languages, such as
Python, suggests an alternative approach. Python is very flexible and makes
experimentation easy. Solutions to simple problems are simply and elegantly
expressed. Python provides a great laboratory for the neophyte programmer.
The common myth is that Mechanical Engineering is not connected with any
coding type of platform. Generally Mechanical Engineers tend to have an aversion to
computer programming and end up not understanding the opportunities that they miss
out on. As the world moves into a future that is tied up intrinsically with electric cars,
autonomous transportation, and automation, the next era of mechanical, aerospace &
automotive engineers need to understand how they can integrate mechanical
engineering concepts with a computer language in order to simulate concepts or
automate them at a faster pace. Python for that matter is an extremely easy and
efficient programming language. It can solve complex problems in a matter of seconds.
Even for a mechanical or an automobile engineer, Python can still be handy in many
occasions.
Areas where Python is used in the mechanical engineering industry includes but
not limited to,
Numerical analysis:
To find the pressure difference across a pipe when there is a liquid flowing
through it; not only will the problem take forever to solve, it will be extremely hard to
obtain accurate values or plot the differences in a graph. With programming languages,
it is possible to solve such problems in a matter of seconds and obtain graphical
simulations at the same instant.
Learning numerical analysis and coding opens up a plethora of opportunities in
areas like manufacturing, automotive, energy and even mechanical jobs in software
companies (like thermal engineers). Software companies like Google and Facebook
hire Mechanical/Thermal engineers to ensure efficient and safe thermal management of
their database and cluster computers in their respective companies.
Thermodynamics:
CFD:
Moreover, a look at the careers page of major companies like Tesla, Mercedes
Benz and Boeing etc. reveal that they employ and prefer mechanical engineers who can
code.
“C” vs “Python”
A tough question arises as to when to use python and when to use C. C and
Python languages are similar yet have many key differences. C and Python languages
are useful languages to develop a various application. The difference between C and
Python is that python is a multi-paradigm language and C is a structured programming
language. Python is a general- purpose language which is used for machine learning,
natural language processing, web development and many more. C is mainly used for
hardware related application development such as operating systems, network drivers.
Before deciding on particular language keep in mind following things
• Ease of development: – python has very fewer keywords and more free English
language syntax whereas C is far more difficult to write and maintain. Hence if you
want easy development process go for python.
• Performance: – Python is much slower than C as python takes significant CPU
time for interpretation.
*****