MAT & C Lab
MAT & C Lab
MAT & C Lab
INTRODUCTION TO C – PROGRAMME
KEYWORDS: The tokens which have predefined meaning in c language are called keyword. Since
they are reserved for specified purpose in c language. They are reserved words ex. break, float, long,
integer, switch for, if, void, while
The keywords should not be used as variable names, function names, array names etc. all keywords
should be written in lower case only
IDENTIFIERS: Identifiers are the names given to various programmers such as constants , functions
, names array, etc
Ex. sum, length, I, a, printf, scanf,
INT: An int is a key word which is used to define integers in c language. Using int keywords c
supports three different sizes
1) Short int
2) Int Here short and long int are type qualifiers
3) Long int
FLOAT: Afloat is akey word which is used to define floating point numbers in c language eg: 3.45,
22.35
VOID: Avoid is a empty data type since there is no value is associated with this data type it does not
occupy any space in the memory
1) PRE PROCESSOR DIRECTIVES :These are called pre compilers directives . thr pre
processor accept the source programme and prepare the source programme for compilation. The
pre processor stamensts stars with symbol #. The normal preprocessor used in all programme
include . this instruct the pre processor to include the specified file contents in the beginning of
the programme.
eg: # include < stdio.h>
2) GLOBAL DECLARATIONS :These are the variables that are define immediately after pre
processor or directives . these variables are visible to all parts of the programme hence the name
global variables
3) MAIN( ): Every programme should have main ( )there should be only one function by name
main( ) this is the first function to be executed always .the function main may call other functions
. the statement enclosed with in left and right brace is a called body of the function.
the main function is divided in to two parts
1)Declaration section
2) Executable section
#include<stdio.h>
#include<conio.h>
void main()
{
int flag=0,n,i;
clrscr();
printf(" Enter the Number\n");
scanf("%d",&n);
for(i=2; i<n; i++)
if (n%i= =0)
{
flag=1;
}
if(flag==0)
printf("\n\n %d is a prime Number\n",n);
else
printf("\n\n %d is a not prime Number\n",n);
getch();
}
Output:
#include<stdio.h>
#include<conio.h>
main()
clrscr();
sum = a + b + c;
avg = sum / 3;
getch();
OUTPUT:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr( );
printf("enter the values of a,b,c");
scanf("%d,%d,%d",&a,&b,&c);
if(a>b&&a>c)
printf("\n\n %d is greater \n",a);
else
if (b>a&&b>c)
printf("\n\n %d is greater \n",b);
else
printf("\n\n %d is greater \n",c);
getch();
}
OUT PUT :
#include<stdio.h>
#include<conio.h>
main()
{
int n;
clrscr();
printf ("Enter the number\n");
scanf ("%d",&n);
if (n%2==0)
{
printf ("The entered number is EVEN.\n",n);
}
else
{
printf ("The entered number is ODD.\n",n);
getch();
}
}
OUTPUT:
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
Long n;
intsum=0,digit;
printf("Enter any number\n");
scanf("%ld",&n);
while(n>0)
{
digit=n%10;
n=n/10;
sum=sum+digit;
}
printf("Sum of digits of a number %d\n", sum);
getch();
}
OUTPUT:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b;
clrscr()
printf(“enter the value of a and b \n”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping the valve of a is %d & b is %d\n”, a,b);
a=a+b;
b=a-b;
a=a-b;
printf(“after swapping the valve of a is %d & b is %d\n”, a,b);
getch();
}
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
11) Write a c program finding the roots of the quadratic equation using switch-
statement
#include<stdio.h>
#include<conio.h>
#include<math.h>
main( )
{
float a,b,c,d,x1,x2;
clrscr();
printf(“enter the values of a,b,c\n”);
scanf(“%f%f%f”,&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
X1=(-b+sqrt(d))/(2*a);
X2=(-b-sqrt(d))/(2*a);
Printf(“the roots are distict\n”);
Printf(“x1=%f\nx2=%f\n”,x1,x2);
If(d==0)
x1=x2=-b/(2*a);
printf(“the roots are equal\n”);
printf(“x1=%f\nx^2=%f\n”,x1,x2);
}
else
{
x1=-b/(2*a);
x2=sqrt(fabs(d))/(2*a);
printf(“the roots are complex\n”);
printf(“first root=%f+i%f\n”,x1,x2);
printf(“second root=%f-i%f\n”,x1,x2);
}
getch();
}
OUTPUT:
MAT LAB
1.0 INTRODUCTION
MATLAB is a powerful language for technical computing. The name MATLAB stands for
Matrix Laboratory, because its basic data element is a matrix (array). MATLAB can be used for math
computations, modeling and simulations, data analysis and processing, visualization and graphics, and
algorithm development. MATLAB is widely used in universities and colleges in introductory and
advanced courses in mathematics, science, and especially engineering. In industry the software is used
in research, development, and design. The standard MATLAB program has tools (functions) that can
be used to solve common problems. In addition, MATLAB has optional toolboxes that are collections
of specialized programs designed to solve specific types of problems. Examples include toolboxes for
signal processing, symbolic calculations, and control systems.
Chapter – 2
Starting with MATLAB
It is assumed that the software is installed on the computer, and that the user can start the
program. Once the program starts, the MATLAB desktop window opens (Figure 1-1). The window
contains four smaller windows: the Command Window, the Current Folder Window, the Workspace
Window, and the Command History Window. This is the default view that shows four of the various
windows of MATLAB. A list of several windows and their purpose is given in Table 1-1. The Start
button on the lower left side can be used to access MATLAB tools and features. Four of the
windows—the Command Window, the Figure Window, the Editor Window, and the Help Window—
are used extensively throughout the book and are briefly described on the following pages. More
detailed descriptions are Included in the chapters where they are used. The Command History
Window, Current Folder Window, and the Workspace Window are described in Sections 1.2, 1.8.4,
and 4.1, respectively.
2.1 Command Window: The Command Window is MATLAB’s main window and opens when
MATLAB is started. It is convenient to have the Command Window as the only visible window, and
this can be done by either closing all the other windows (click on the x at the top right-hand side of the
window you want to close) or by first selecting the Desktop Layout in the Desktop menu, and then
selecting Command Window Only from the submenu that opens. Working in the Command Window
2.2 Figure Window: The Figure Window opens automatically when graphics commands are
executed, and contains graphs created by these command
2.4 Help Window: The Help Window contains help information. This window can be opened from the
Help menu in the toolbar of any MATLAB window. The Help Window is interactive and can be used
to obtain information on any feature of MATLAB. Figure 1-4 shows an open Help Window.
Table 1.1
Window Purpose
Command Window Main window, enters variables,
runs
programs.
Figure Window Contains output from graphic
commands
Editor Window Creates and debugs script and
function files.
Help Window Provides help information.
Command History Logs commands entered in the
Window Command Window.
Workspace Window Provides information about the
variables that are used.
Current Folder Shows the files in the current
Window folder
1. To type a command the cursor must be placed next to the command prompt ( >> ).
2. Once a command is typed and the Enter key is pressed, the command is executed.
3. However, only the last command is executed. Everything executed previously
4. (That might be still displayed) is unchanged.
5. Several commands can be typed in the same line. This is done by typing a comma
6. between the commands. When the Enter key is pressed the commands are executed in order from
left to right.
7. It is not possible to go back to a previous line that is displayed in the Command
8. Window, make a correction, and then re-execute the command.
9. A previously typed command can be recalled to the command prompt with the up arrow key (
). When the command is displayed at the command prompt, it can be modified if needed and then
executed. The down-arrow key ( ) can be used to move down the list of previously typed
commands.
10. If a command is too long to fit in one line, it can be continued to the next line by typing three
periods … (called an ellipsis) and pressing the Enter key. The continuation of the command is
then typed in the new line. The command can continue line after line up to a total of 4,096
characters.
The semicolon ( ; ):
When a command is typed in the Command Window and the Enter key is pressed, the command
is executed. Any output that the command generates is displayed in the Command Window. If a
semicolon ( ; ) is typed at the end of a command the output of the command is not displayed. Typing a
semicolon is useful when the result is obvious or known, or when the output is very large. If several
commands are typed in the same line, the output from any of the commands will not be displayed if a
semicolon is typed between the commands instead of a comma.
Typing %:
When the symbol % (percent) is typed at the beginning of a line, the line is designated as a
comment. This means that when the Enter key is pressed the line is not executed. The % character
followed by text (comment) can also be typed after a command (in the same line). This has no effect
Order of Precedence
MATLAB executes the calculations according to the order of precedence displayed below. This order
is the same as used in most calculators.
Precedence Mathematical Operation
First Parentheses. For nested parentheses, the innermost are executed first.
Second Exponentiation.
Third Multiplication, division (equal precedence).
Fourth Addition and subtraction
In an expression that has several operations; higher-precedence operations are executed before
lower-precedence operations. If two or more operations have the same precedence, the expression is
executed from left to right. As illustrated in the next section, parentheses can be used to change the
order of calculations.
Using MATLAB as a Calculator
The simplest way to use MATLAB is as a calculator. This is done in the Command Window
by typing a mathematical expression and pressing the Enter key. MATLAB calculates the expression
and responds by displaying ans. = and the numerical result of the expression in the next line
Using MATLAB as a calculator.
>> 7+8/2 Type and press Enter.
ans = 8/2 is executed first.
11
Problem no 1
Trigonometric identity
A trigonometric identity is given by:
cosx2 = tanx + sinx
2tanx
Verify that the identity is correct by calculating each side of the equation, substituting
. X= π/5
Solution
The problem is solved by typing the following commands in the Command Window.
>> x=pi/5;
>> LHS=cos(x/2)^2
LHS = 0.9045
>> RHS= (tan(x) +sin(x))/ (2*tan(x))
RHS = 0.9045
Problem no 2: Three forces are applied to a bracket as shown. Determine the total (equivalent)
force applied to the bracket.
F1=400N
The total (equivalent) force applied on the bracket is obtained by adding the
forces that are acting on the bracket. The MATLAB solution below follows three steps:
1. Write each force as a vector with two elements, where the first element is the x component of
the vector and the second element is the y component.
2. Determine the vector form of the equivalent force by adding the vectors.
3. Determine the magnitude and direction of the equivalent force.
F
mm
m Friction
Test # 1 2 3 4 5 6
Mass m-kg 2 4 5 10 20 50
Force F -N 12.5 23.5 30 61 117 294
The coefficient of friction, μ, can be determined in an experiment by measuring the force F required to
move a mass m. When F is measured and m is known, the coefficient of friction can be calculated by:
μ = F ⁄ (mg) (g = 9.81 m/s2).
Results from measuring F in six tests are given in the table above Determine the coefficient of friction
in each test, and the average from all tests
Solution
A solution using MATLAB commands in the Command Window is shown below.
>> m=[2 4 5 10 20 50]; Enter the values of m in a vector.
mu_ave =0.6109
Problem no 3: A cylindrical silo with radius r has a spherical cap roof with radius R. the height of
the cylindrical portion is H. write a program in a script file that determines the height H for given
values of r, R and the volume V. In addition, the program also calculates the surface area of the silo.
Use the program to calculate the height and surface area of a silo with r=30 m , R=45m and volume of
120000 cubic metre.. assign values for r,R and V in the command window.
clc
r = input('Enter the radius of Cylindrical Silo = ');
R = input('Enter the Radius of Sperical Cap = ');
V = input('Enter the Volume of Cylindrical Silo = ');
th = asin(r/R);
h = R-R*cos(th);
vcp = pi*h^2*(3*R-h)/3;
H = (v-vcp)/(pi*r^2);
s = 2*pi*(r*H+R*h);
fprintf ('The Height of Cylindrical Silo H= %f \n', H);
fprintf ('The Surface Area of Cylindrical Silo s= %f \n', s);
Calculate and plot the position, velocity, and acceleration of the piston for one
revolution of the crank.
clc
rpm = input('Enter the RPM = ');
r = input('Enter the Length of Rod = ');
c = input('Enter the Length of Crank = ');
rad = rpm*2*pi/60;
tr = 2*pi/rad;
t = linspace(0, tr, 200);
th = rad*t; f = c^2-r^2*sin(th).^2;
x = r*cos(th)+sqrt(f);
dx = -r*rad*sin(th)-(r^2*rad*sin(2*th))./(2*sqrt(f));
ddx=-r*rad^2*cos(th)- (4*r^2*rad^2*cos(2*th).*f+(r^2*sin(2*th)*rad).^2)./(4*f.^1.5); subplot(3,1,1)
plot(t,x)
grid
xlabel('Time----->')
ylabel('Position----->')
subplot(3,1,2)
plot(t,dx)
grid
Solution:
function[hmax,dmax] = prog6_me(v,th)
g=9.81;
vx=v*cos(th*pi/180);
vy=v*sin(th*pi/180);
thmax=vy/g;
hmax=vy^2/(2*g);
tt=2*thmax;
dmax=vx*tt;
tplot=linspace(0,tt,200);
x=vx*tplot;
y=vy*tplot-0.5*g*tplot.^2;
plot(x,y)
OUTPUT:
>> [h , d] = prog6_me(230,39)
h = 1.0678e+003
d = 5.2746e+003
Solution:
clc
w = input('Enter the Weight of Aluminum Rectangular box w= ');
sp = input('Enter the Specific Weight of Aluminum box sp= ');
v = w/sp; a = [-2 24];
b = [-2 12];
c = [-1 4];
temp = conv(c,conv(a,b));
poly = [0 0 0 (v-24*12*4)] + temp
x = roots (poly)
OUTPUT: <Type file name in command window>
Enter the Weight of Aluminum Rectangular box w= 15
Enter the Specific Weight of Aluminum box sp= 0.101
poly = -4.0000 88.0000 -576.0000 148.5149 The polynomial is:
– 4x3 + 88x2 – 576x + 148.515.
x=
10.8656 + 4.4831i The polynomial has one real root, x = 0.2687
in.,which is the thickness of the aluminum wall.
10.8656 - 4.4831i
0.2687
(8) Viscosity mu is property of gases and fluids that characterises their resistance to flow. For
most materials viscosity is highly sensitive to temperature. Below is a table that gives the
viscosity of SAE 10w oil at different temperatures. Determine an equation that can be fitted to
the data.
T(Oc)
-20 0 20 40 60 80 100 120
μ (Ns/m2)
(x10-5)
4.000 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032
SOLUTION:
clc
t=[-20 0 20 40 60 80 100 120];
u=[4 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032];
tk=t+273;
p=polyfit(tk,log(u),2)
tp=273+[-20:120];
mp=exp(p(1)*tp.^2+p(2)*tp+p(3));
semilogy(tk,u,'o',tp,mp)
xlabel('Temperature (K)----->')
ylabel('Viscosity----->')
OUTPUT:
<Type file name in command window>
p = 0.0003 -0.2685 47.1673
>>
(9) A safety bumper is placed at the end of a race track to stop out of control cars. The bumper
is designed such that the force that the bumper applies to the car is a function of the velocity v
and displacement x of the front edge of the bumper according to the equation. F=Kv3(x+1)3
where K=30 s-kg/m5 is a constant. A car with a mass m of 1500 kg hits the bumper at a speed of
90 km/hr. Determine and plot the velocity of the car as a function of its position for 0≤x≤3 m.
OUTPUT:
<Type main program file name in command window>
>> x = v=
0.0000 25.0000
0.2000 22.0420
0.4000 18.4478
0.6000 14.7561
0.8000 11.4302
1.0000 8.6954
1.2000 6.5733
1.4000 4.9793
1.6000 3.7960
1.8000 2.9220
2.0000 2.2737
2.2000 1.7886
2.4000 1.4226
2.6000 1.1435
2.8000 0.9283
3.0000 0.7607