0% found this document useful (0 votes)
418 views40 pages

C & Matlab Lab Manual Format PDF

The document is a lab manual containing experiments for a course on problem solving and object oriented programming using C and MATLAB. It includes experiments on basic C programs to perform tasks like calculating sums, LCM/GCD, arithmetic operations using switch case, counting vowels/consonants. It also includes MATLAB programs for plotting trajectories, cycloids, and SIMULINK models for simulation. The manual contains the objectives, formulas, programs, and expected output for each experiment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
418 views40 pages

C & Matlab Lab Manual Format PDF

The document is a lab manual containing experiments for a course on problem solving and object oriented programming using C and MATLAB. It includes experiments on basic C programs to perform tasks like calculating sums, LCM/GCD, arithmetic operations using switch case, counting vowels/consonants. It also includes MATLAB programs for plotting trajectories, cycloids, and SIMULINK models for simulation. The manual contains the objectives, formulas, programs, and expected output for each experiment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

LAB MANUAL

for

ME008 PROBLEM SOLVING AND


OBJECT ORIENTED PROGRAMMING

IV​th ​Semester

Department of Mechanical
Engineering
Saveetha School of
Engineering

Saveetha Institute of Medical and Technical


Sciences
TABLE OF CONTENTS
Expt.
Date Experiment Title Page No. Signature
No ​
- C Language: Introduction
C Program to calculate the sum of a set of
1​
C Program to calculate the LCM and GCD of
numbers 2 ​
C Program to perform arithmetic operations
any two integers 3 ​
C Program to count the vowels and ​
​ ​
using ​switch-case 4 consonants in a string of
C Program to calculate the standard deviation
characters 5 ​
of any given data
6 C Program to construct the Pascal triangle
C Program to determine the roots of a
7​
quadratic equation
8 C Program to display the Fibonacci series
C Program to convert the given decimal
9​
C Program to find and display the prime
number to binary number 10 ​
C Program to determine the area moment of ​
numbers 11 ​ inertia of standard shapes 12
C Program to determine the resultant of a set

C Program to analyse the vibrations of a


of coplanar concurrent forces 13 ​
simple spring-mass system
- MATLAB and SIMULINK: Introduction
MATLAB Program to plot the trajectory of a
14 ​
projectile
15 MATLAB Program to plot a cycloid curve
MATLAB Program to plot the position and
16 ​
SIMULINK model for simulating a
velocity of slider in a slider-crank mechanism 17 ​
water tank

SIMULINK model for simulating a single


level control using PID controller 18 ​
hydraulic cylinder
- Study: Python programming for Engineers
C LANGUAGE
INTRODUCTION
C is a programming language developed at AT&T’s BELL Laboratory of USA in
1972. Dennis Ritchie designed it. Because of its reliability. C is very popular. C is highly
portable & it is well suited for structured programming. C program consists of collection
of functions.

Hardware Requirement : ​Desktop Computer / labtop


computer

Software Requirement : ​Windows Operating System with GCC/ TURBOC IN

WINDOWS OS ​GCC

Released by the Free Software Foundation. gcc is a Linux-based C compiler usually


operated via the command line. It often comes distributed with a linux installation, so if
you are running Unix or a Linux variant you likely have it on your system. You can
invoke gcc on a source code file simply by typing :-

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 : -

gcc filename -o outputfile

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':

gcc filename -o outputfile –lm

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.

To do compiling – ​Select -> Compile ​from menu and click->


Compile.​

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

Now you will see the output screen.


Experiment 1

C Program to calculate the sum of a set of


numbers

Aim​:

To evaluate the sum of any set of 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)

Program:

#include<stdio.h>
main ()

int n, m=0, p=0, q;

printf("Enter how many numbers to add: ");

scanf("%d",&n);

for(q=1;q<=n;q++)

printf("Enter number %d: ", q);

scanf("%d",&m);

p=m+p;

printf("Sum is %d", p);

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 2

C Program to calculate the LCM and GCD of any two


integers

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>

int gcd(int x, int y) {


int r = 0, a, b; a = (x > y) ? x : y; // a is
greater number b = (x < y) ? x : y; // b is
smaller number

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)

return a; ++a; } } ​int main(int

argc, char **argv) {


printf("Enter the two numbers: "); int x, y; scanf("%d",
&x); scanf("%d", &y); printf("The GCD of two numbers
is: %d", gcd(x, y)); printf("\nThe LCM of two numbers is:

%d", lcm(x, y)); return 0; } ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 3

C Program to perform arithmetic operations using


switch-case

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() {

char operator; double


num1, num2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf",&num1, &num2);

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

C Program to count the vowels and consonants in a string of


characters
Aim​:

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;

vowels = consonants = digits = spaces =


0;

printf("Enter a line of string: ");


scanf("%[^\n]", line);

for(i=0; line[i]!='\0'; ++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')) {
++consonants; } else if(line[i]>='0'
&& line[i]<='9') {
++digits; } else if
(line[i]==' ') {
++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 = √​∑ (x​i​−x)​2 N​i=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;

for(i=1; i<=n; i++)

var = var + pow(x[i] - mean, 2);

SD = sqrt(var/n);

printf("\nData Count = %d", n);

printf("\nSum of data = %.3f", sum);

printf("\nData average = %.3f", mean);

printf("\nData Variance = %.3f", var);

printf("\nStandard Deviation = %.10f", SD);

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 6

C Program to construct the Pascal


Triangle

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()

int rows, coef = 1, space, i, j;

printf("Enter number of rows: ");

scanf("%d",&rows);

for(i=0; i<rows; i++)

for(space=1; space <= rows-i;


space++)
printf(" ");

for(j=0; j <= i; j++)

if (j==0 || i==0)

coef = 1;

else

coef = coef*(i-j+1)/j;
printf("%4d", coef);

printf("\n");

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 7
C Program to determine the roots of a quadratic equation
Aim​:
To create a C program that can determine the roots of any given quadratic equation in
the form of ​ax​2 ​+ bx + c = 0​.
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:
Roots = ±b−√b​
​ 2​
−4ac

2a ​Discriminant = ​b​2 – 4ac
If discriminant > 0; real unequal roots
If discriminant = 0; real equal roots
If discriminant < 0; imaginary roots
Program:
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
discriminant = b*b-4*a*c;
if (discriminant > 0)
{
root1 = (-b+sqrt(discriminant))/(2*a);
root2 = (-b-sqrt(discriminant))/(2*a);
printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);

else if (discriminant == 0)

root1 = root2 = -b/(2*a);

printf("root1 = root2 = %.2lf;", root1);

else

realPart = -b/(2*a);

imaginaryPart = sqrt(-discriminant)/(2*a);

printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart,


realPart, imaginaryPart);

}
return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 8

C Program to display the Fibonacci


series

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:

In mathematics, the Fibonacci numbers, commonly denoted F​n ​form a sequence,


called the Fibonacci sequence, such that each number is the sum of the two preceding
ones, starting from 0 and 1.

F​0 ​= 0, F​1 ​= 1 and F​n = ​ -1 ​+ F​n-2 f​ or all n>1.


​ Fn

The first few Fibonacci numbers are 1 1 2 3 5 8 13 21


....

Program:

#include <stdio.h>

int main()
{

int n, first = 0, second = 1, next, c;

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

scanf("%d", &n);

printf("First %d terms of Fibonacci series are:\n",


n);

for (c = 1; c <= n; c++)

if (c <= 1)

next = c;

else

{
next = first + second;

first = second;

second = next;

printf("%d\n", next);

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 9

C Program to convert the given decimal number to binary


number

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;

printf("Enter an integer in decimal number


system\n");

scanf("%d", &n);

printf("%d in binary number system is:\n", n);

for (c = 10; c >= 0; c--)


{

k = n >> c;

if (k & 1)

printf("1");

else

printf("0");

printf("\n");

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 10

C Program to find and display the prime


numbers

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;

printf("Enter the number of prime numbers


required\n");

scanf("%d",&n);

if ( n >= 1 )

printf("First %d prime numbers are :\n",n);

printf("2\n");

for ( count = 2 ; count <= n ; )

for ( c = 2 ; c <= i - 1 ; c++ )

{
if ( i%c == 0 )

break;

}
if ( c == i )

printf("%d\n", i);

count++;

i++;

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 11

C Program to determine the area moment of inertia of standard


shapes

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", &sect);

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

of Program!!"); return 0; } ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 12

C Program to determine the resultant of a set of coplanar concurrent


forces

Aim​:

To determine the magnitude and direction of the resultant of a set of coplanar


concurrent forces.

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

Angle of Resultant θ​R ​= tan​−1​(Fy Fx ⁄ )

Program:

#include <stdio.h>

#include <math.h>

#define PI 3.14159265

main ()

int i, n;

double F, T, val, Fx, Fy, R, A;

val = PI / 180;

printf("Enter the number of forces to resolve:


");
scanf("%d", &n);

for(i=1;i<=n;i++)

printf("Enter the magnitude of Force-%d (in 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:

The program is compiled, executed and the output is


verified.
OUTPUT:
Experiment 13

C Program to analyse the vibrations of a simple spring-mass


system

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");

printf("Enter the mass value (in kg): ");

scanf("%f", &m);

printf("Enter the spring constant of the spring (in N-m):


");

scanf("%f", &k);

printf("Enter the initial displacement of the mass (in m):


");

scanf("%f", &r);
x = m*g/k; /* natural deflection of the spring mass system */

n = (sqrt(g/x))/(2*pi); /* natural frequency */

t = 1/n; /* time period */

v = sqrt(g/x) * r; /* maximum velocity */

if (x<=0.001)

printf("\nNatural deflection of the Spring-mass system, x = %.3f mm",


x*1000);

else

printf("\nNatural deflection of the Spring-mass system, x = %.3f m",


x);

printf("\nNatural frequency of vibration, n = %.2f Hz", n);

printf("\nTime period of vibration, Tp = %.2f s", t);

printf("\nMaximum velocity of vibration (at mean position), Vmax = %.3f m/s",


v);

return 0;

} ​Result:

The program is compiled, executed and the output is


verified.
OUTPUT:
MATLAB AND SIMULINK
INTRODUCTION

MATLAB (matrix laboratory) is a multi-paradigm numerical computing


environment and proprietary programming language developed by MathWorks.
MATLAB allows matrix manipulations, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs written in other
languages, including C, C++, C#, Java, Fortran and Python.
As of 2018, MATLAB has more than 3 million users worldwide. MATLAB users
come from various backgrounds of engineering, science, and economics.

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.

MATLAB was first adopted by researchers and practitioners in control


engineering, Little's specialty, but quickly spread to many other domains. It is now also
used in education, in particular the teaching of linear algebra and numerical analysis,
and is popular amongst scientists involved in image processing.

The MATLAB application is built around the MATLAB scripting language.


Common usage of the MATLAB application involves using the Command Window as an
interactive mathematical shell or executing text files containing MATLAB code.

MATLAB supports developing applications with graphical user interface (GUI)


features. MATLAB includes GUIDE(GUI development environment) for graphically
designing GUIs. It also has tightly integrated graph-plotting features. A MATLAB
program can produce three-dimensional graphics using the functions surf, plot3 or
mesh. In MATLAB, graphical user interfaces can be programmed with the GUI design
environment (GUIDE) tool.

MATLAB can call functions and subroutines written in the programming


languages C or Fortran. A wrapper function is created allowing MATLAB data types to
be passed and returned. MEX files (MATLAB executables) are the dynamically loadable
object files created by compiling such functions. Libraries written in Perl, Java, ActiveX
or .NET can be directly called from MATLAB, and many MATLAB libraries are
implemented as wrappers around Java or ActiveX libraries.
Experiment 14
MATLAB Program to plot the trajectory of a projectile
Aim​:
To plot the trajectory of a projectile on a 2D graph for a given initial velocity and angle.
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:
Equation for path of the projectile, y = x tanθ − ( g​ x​2
2​ ) ​ u​2 ​
2 u​ cos​ θ​ Maximum range, x​max ​= ​ sin2θ
2​

Maximum height reached y​max ​= u​​ 2 ​sin​2 ​θ


2g
Program:
function projectile (u, a);
pi = 3.14159265359;
g = 9.81;
r = (u^2) * sin (2*a*pi/180) / g;
x = 0:r/100:r;
y = (x*tan(a*pi/180)) - ( (g*(x^2)) / (2*(u*(cos(a*pi/180)))^2) );
H = (u^2)*((sin(a*pi/180))^2)/2/g;
T = (2*u) * sin (a*pi/180) / g;
disp(r, 'Range =');
disp(H, 'Maximum Height =');

disp(T, 'Time of travel =');

plot (x,y);

title ('TRAJECTORY OF A PROJECTILE');

xlabel ('Distance travelled by the


projectile');

ylabel ('Height of the projectile');

xgrid;

endfunction;

Result:

The program is compiled and executed. The 2D graph is plotted and the output is
verified.
OUTPUT:

GRAPH PLOT:
Experiment 15

MATLAB Program to plot a cycloid curve

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:

function cycloid (r, a);


pi = 3.14159265;

t = 0:5:a; x = r * ((t*pi/180) -
sin(t*pi/180));

y = r * (1 - cos (t*pi/180));
plot (x,y,'k');

title ('CYCLOID CURVE');


xlabel ('Rotational Distance');

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);

title ('SLIDER VELOCITY CURVE');

xlabel ('Angle of Crank rotation, radians');

ylabel ('Slider velocity');

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.

Variables ​H ​is the height of water in the tank.


Vol ​is the volume of water in the tank. ​V i​ s the voltage applied
to the pump. Parameters ​A ​is the cross-sectional area of the
tank.
b i​ s a constant related to the flow rate into the tank. ​a i​ s a constant related
dH​ = bV
to the flow rate out of the tank. Differential Equation ​ddt​Vol = A​ dt ​
− a√H ​
States ​H ​Inputs ​V O
​ utputs ​H
Simulation Model:

The Water-Tank System is shown in the following


figure
Result:

The simulation model is designed and executed and the output is


verified.
OUTPUT:
Experiment 18

SIMULINK model for simulating a single hydraulic cylinder

Aim​:

To simulate the working of a single acting hydraulic cylinder with a spring-return


mechanism.

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​.

Block 1 Equation: Block 2 Equation:


Block 3 Equation: Block 4 Equation:

Simulation Model:
The pump subsystem:

The valve-cylinder-piston-spring
subsystem:

Result:

The simulation model is designed and executed and the output is


verified.
OUTPUT:
STUDY PYTHON PROGRAMMING FOR
ENGINEERS

Python is a high-level and general-purpose programming language. According to


several survey results or search engine queries, it is one of most popular programming
languages. Part of the reason that it is a popular choice for scientists and engineers is
the language versatility, online community of users, and powerful analysis packages. It
is a multi- paradigm programming language which is being used by the developers
worldwide to develop various things like websites, machine learning algorithms and also
simplifying and automating day to day tasks.

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:

The most popular application of python is to perform numerical analysis. When


problems with linear equations or differential equations are involved, it would take a long
time to solve the problems analytically. In terms of mechanical engineering, there are
usually boundary conditions present which makes it twice harder to solve numerical
analysis problems.

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:

Python can be used to solve classical thermodynamics problems. Whether it is a


chemical kinetics or fluid dynamics problem, it is possible to write a code to solve the
problem and save time. In real world, industries do not pay attention to how the
problems are solved or how the tasks are completed. One can save enormous amounts
of time in problem solving by choosing to solve them in Python and use the remaining
time to focus on the real troubles at hand. The only aspect of any outcome that matters
is the efficiency.

CFD:

In the field of computational fluid dynamics, Python has a massive application. In


order to simulate problems in CFD software, it is required to write the scripts in
programming languages like MATLAB/Python. Python is also used in other areas of
mechanical engineering like vibrations and dynamic motion, simulation and modelling
engineering, optimization, etc. Mechanical and automobile industries use python to
automate tasks. Even when the script is written in another programming language, it is
rewritten in Python before automation since it is the most common language and hence
the interface between industries and codes.

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.

*****

You might also like