Upload
tony-montana
View
1.569
Download
13
Tags:
Embed Size (px)
DESCRIPTION
C Programming & MatLab Manual - DIPLOMA, MECHANICAL ENGINEERING, Karnataka
Citation preview
Table of contents
Serial No. Topic Page number
1 Introduction to computer language 1‐9
2 Executing a C program 10‐11
3 Sum and average of three real numbers 11‐12
4 The largest numbers of three numbers 14‐17
5 Even or odd using IF ELSE statement 18‐19
6 Whether a number is prime or not. 20‐23
7 Sum of digits of a given number. 24‐25
8 Roots of the quadratic equation using switch statements. 26‐29
9 Arrange n‐numbers in ascending order using bubble sort technique 30‐33
10 Multiplication of two matrices 34‐37
11 Addition of two matrices 38‐41
12 Swap two numbers 24‐43
MATLAB
13 Introduction 44‐49
14 Problem‐1 50
15 Problem‐2 51
16 Problem‐3 52
17 Problem‐4 53
18 Problem‐5 54
19 Problem‐6 55
20 Problem‐7 56
21 Problem‐8 57
22 Problem‐9 58
23 Problem‐10 59
Page | 1
Introduction to computer language
Software
The art of writing instructions for a computer to solve a specific task is called programming. The output
of programming is a well defined set of instructions. This is called a program.
Software is a program or a collection of programs to instruct the hardware of computer to perform
specific functions.
Computer languages
Computer languages are classified into two types they are:‐
Low level languages.
High level languages.
Low level languages
These are easily understood by the computer. These are machine dependent and specific to computers.
a.) Machine language
It is called first generation language. It has only “0”s and “1”s forming an instruction that
is “zero” and “one” form the vocabulary of computer. It can be directly typed and executed, ie
no translation program is required. Each instruction has a specific format.
The first field is‐
1.) Op code :‐ operation to be done (+,‐,x,stc) 2.) Address: ‐ memory location where data is required. In machine language it is difficult to
understand, modify and declare errors.
b.) Assembly languages
It is called second generation language. It consists of symbolic instructions. Computer
does not understand these instructions till they are translated into equipment machine codes.
This is carried out by a program called assembler. This language is easy to understand, write,
modify and debug compared to machine language.
High level languages
These are called third generation language. The languages is English like with its elements as
alphabets, digits, punctuation marks and other special symbols. A program in high level language is to be
translated into computer readable form. This is done by an intermediatory program called the
translator.
Compilers and interpret are two translator programs used in this operations.
Page | 2
Introduction to ‘C’ language.
It is a programming language which is used to develop system programs. It is a short, both
general purpose and specific purpose programming language. It runs under various operating system.
(M.S.Dos, windows, etc..)
Characteristics of ‘C’ language
Some of its characteristics are listed below:‐
1.) ‘C’ is a structured programming language.
2.) It has rich set of operators. It provides compact representation for expressions.
3.) Pointer implementation – extensive use of pointers for memory array, structures and functions.
4.) Ability to extend itself by adding functions to its library.
Features of ‘C’ language
Modularity.
Portability.
Code‐reversibility.
Ability to extend itself.
Limited number of keywords.
Structure of ‘C’ program
Documentation selection
Preprosser statement
Global declaration;
Main()
{
declarations;
statements;
}
user defined functions.
Character set
C uses the following as building blocks to form basic program elements.
1.) Upper case letters A to Z. 2.) Lower case letters a to z. 3.) Digits 0 to 9. 4.) Special characters like “/,*,+,\” etc
Page | 3
Structural elements of ‘C’ program
1.) Keywords
In C certain words are reserved as keywords with specific meanings. For example:‐ “int” is used to
indicate that integer valves are concerned. C requires that all keywords are in lower case letters such
words should not be used for any other purpose in c‐program. Ex:‐ auto, double, int.
2.) Statements
These are the entries which make up the program every statement being terminated by a
semicolon. Statements can be grouped together in blocks by putting them between brackets that is {}.
These for a two statement grouped we have:‐
{
Statement 1;
Statement 2;
}
3.) Standard library functions
C packages are supplied with libraries containing a large number of predefined funtions containing c
code that have already been written. In order to use the contents of any particular library that has to be
specified in header file.
Such libraries are:‐
Math.h for mathematical funtions.
Stdio.h for input and output functions.
Time.h for date and time funtions.
For example, the function printf() is a function that can be called up from stdio.h library
and is the function for printing to the screen of the monitor. Another function is scanf()
which can be used to read data from a keyboard.
4.) Pre‐Processor
The pre‐processor is a program that is identified by pre‐processor commands so that it is executed
prior to the compilation all such commands are identified by having # at the beginning of the line. Thus
we might have:‐
#include<>
To include the file named between the angle brackets <>, when this command is
reached the specified file will be inserted into the program. It is frequently used to add the
contents of standard header files. These giving a number of declaration and definations to
enable standard library functions to be used.
Ex :‐ #include<stdio .h>
Page | 4
5.) Main function
Every C program must have a function called “main()”. This function is the one that exercises control
when the program is executed and is the first function to be called up. Execution starts with its first
statement, other functions or statements may be called up within statements each one in turn being
executed and control returned to the main function.
6.) Comments
/* and */ are used to enclose comments.
Comments are ignored by the compiler and are just used to enable a programmer to move easily
comprehend the program comments can span more than one line.
Ex :‐ /* anb example of a program used to illustrate programming */
7.) Variables
A variable is a named memory location that can hold various valves. Variables that can hold a
character are specified using the keywords:‐
1.) Char:‐ such a variable being 8 bit long and generally used to store a single character 2.) Signed integers :‐ numbers with no fractional parts and which are signed to indicate
positive or negative are specified using the keywords :‐ “int”
3.) Float :‐ used for floating point numbers but provides about twice the number of
significant digits os float. The declare a variable the type is inserted before the
variable name ex:‐ int counter.
8.) Assignments :‐
An assignment statement assigns the valve of the expressions to the right of the “=” sign to the
variable on its left. For example:‐ a=2 assigns the valve 2 to the variable a.
9.) Arithmetic operators
The arithmetic operators used arte addition +, subtraction‐, multiplication*, division/, modulus%,
increments++, decrements‐‐, operator increase the valve of variable by 1, decrement operator decreade
its valve by 1.
10.) Relational operators
Relational operators are used to compare expressions. The relation operators are equal to ==, is not
equal to 1=, less than <, less than or equal to <=, greater than >, greater than or equal to >=, Note that
== has to be used when asking if two variables are the same, = is used to assignment when you are
starting that they are the same. For example we might have the equation “ is x equal to 2 !” and
represents this by (a==2).
Page | 5
11.) Logical operators
The logical operators are :‐
operator Symbol
AND &&
OR //
NOT !
12.) Bitwise operations
The bitwise operators treat their operands as a series of individual bits rather than a numerical
valve. Comparing corresponding bits in each operand and only work with integer variables. The
operators are:‐
BITWISE OPERATION SYMBOL
AND &
OR /
EXCLUSIVE‐OR ^
NOT ~
SHIFT RIGHT >>
SHIFT LEFT <<
13.) String
A sequence of characters enclosed within double quotes that “”, is termed a string as the term
implies the characters within the double quotes are treated as a linked entity.
For example we might have
Printf(“sum=%d”,x)
The argument in () specifies what is passed to the print function. There are two arguments, the
two being separated by a comma. The first argument is the string between the double quotes
and specifies hoe the output is to be presented. The %d specifying that the variable is to be
displayed as a decimal integer other format specifies are :‐
%c ‐ character.
%d – signed decimal integer.
%e – scientific notation.
%f – decimal floating point.
14.) Escape sequences
Escape sequences are characters that ‘escape’ from the standard interpretation of charters and are
used to control the location of output on a display by moving the screen cursor or indicating special
Page | 6
treatments. Thus we might have :‐ printf(“\n sum = %d,”d) with the \n in dicating that a new line is to be
used when it is printed on the screen. Escape sequences commonly used are
\a – sound a beep.
\b – back space.
\n – new line.
\t – horizontal tab.
\\ ‐ backlash.
\? – question mark.
\’ – sign quotation.
Page | 7
Branching and looping statements
1.) If statement
The “if” statement allows branching. For example, if an expression is true then the statement is
executed, if not true it is not and the program proceeds to the next statement. Thus we might have
statements of the form‐
If (condition 1==condition 2);
Printf(“\n condition is ok”);
2.) If/else statement
The “if” statement can be combined with the “else” statement. This allows one statement to be
executed if the result is yes and another if the result is no. thus we might have.
If(condition)
{
Statement 1;
}
Else
{
Statement 2;
}
3.) For statement
The term “loop” is used for the execution of a sequence of statements until a particular
condition reaches the required condition of being true or false. This one way of writing statements for a
loop is to use the function “for”. The general form of the statement is.
For (initializing expression; test expression; increment exp)
Loop statement;
4.) While statement
The “while” statement allows for a loop to be continuously repeated as long as the expression is
true when the expression becomes false then the program continues with the statement following the
loop. The general form of statement is
While (log exp)
{
Statements;
}
Page | 8
5.) Switch statement
The “switch” statement allows for the selection between several alternatives the test condition
being in parenthesis. The possible choices are identified by case labels. These identifying the expected
valves of the test condition. The general form of the statement.
Switch (expression)
{
Case 1;
Statement 1;
Break;
Case 2;
Statement 2;
Break;
Case 3;
Statement 3;
Break;
Default;
Default statement;
}
Next statement;
6.) Arrays
An “array” is a collection of data storage locations with each having the same data type and
referenced through the same name. To declare the array with the name temperature to store valves of
type float use the statement.
Float temperature [7];
The size of the array is indicated between square brackets[] immediately after the
name.
Temperature[0] = 22.1;
7.) Multidimensional array
It is an ordered table of homogeneous elements generally refers to as matrix of rows and
columns.
Ex :‐ array[x][y];
8.) User defined functions
If a program is divided into functional parts, then each part may be independently coded and
cater combined into a single unit. These sub‐programs are called functions.
Page | 9
9.) Functional declaration Syntax:‐
Return data type
Fun name (argument, data type, argument data type);
Ex :‐ int add (int,int);
Page | 10
Executing A ‘C’ Program
Flow chart
SYSTEM READY
ENTER PROGRAM
EDIT SOURCE PROGRAM
COMPILE SOURCE PROGRAM
IS
SYNTAX
ERRORS!
LINK WITH SYSTEM LIBRARY
EXECUTE OBJECT CODE
IS LOGIC
AND DATA
ERRORS!
CORRECT
OUTPUT
STOP
PROCESS OF RUNNING AND COMPILING A C‐ PROGRAM
PROGRAM CODE
C‐ COMPILER
SYSTEM LIBRARY
INPUT DATA
Page | 11
Executing A ‘C’ Program
Executing a program written in ‘c’ involves a series of steps these are.
1.) Creating the program.
2.) Compiling the program.
3.) Linking the program with functions that are needed from the ‘C’ library.
4.) Executing the program.
Page | 12
Flow chart
Sum and average of three real numbers
START
INPUT THE
VALVE OF
A,B,C.
SUM = a+b+c
AVG =
PRINT SUM
& AVERAGE
STOP
Page | 13
PROGRAM:‐ 1 SUM AND AVERAGE OF THREE REAL NUMBERS
DATE:‐
AIM:
To write a C program to find the sum and average of three real numbers.
ALGORITHM:
1) Start
2) Input the valve of a,b,c,.
3) Sum = a+b+c
Average = ‐ Calculation of sum and average.
4) Print sum and average.
5) Finished.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,sum;
float avg;
clrscr();
printf("Enter the values of a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
avg=sum/3;
printf("sum=%d\n",sum);
printf("avg=%f",avg);
getch();
}
RESULT: Output
Enter the values of a,b,c
5
3
2
sum=10
avg=3.333333
Page | 14
Flow chart
The largest numbers of three numbers
START
STOP
INPUT THE
VALUE OF a,b,c.
IS a>b
& a>c?
IS b>a
& b>c?
IS c>a
& c>b?
PRINT A IS
THE LARGEST
NUMBER
PRINT B IS
THE LARGEST
NUMBER
PRINT C IS
THE LARGEST
NUMBER
YES
YES
YES
NO
NO
Page | 15
PROGRAM:‐ 2 THE LARGEST OF THREE NUMBERS
DATE:‐
AIM:
To write a C program to find the largest of three numbers.
ALGORITHM:
1) Start
2) Input the valve of a,b,c.
3) If (a>b&&a>c) is true.
Print a is the largest number go to step 6 or else go to step 4.
4) If (b>a&&b>c) is true.
Print b is the largest number go to step 6 or else go to step 5.
5) If (c>a&&c>b) is true.
Print c is the largest number go to step 6.
6) Finished.
Page | 16
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter the values of a,b,c");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("a is the largest number");
}
}
if(b>a)
{
if(b>c)
{
printf("b is the largest number");
}
}
if(c>a)
{
if(c>b)
{
printf("c is the largest number");
}
}
getch();
}
Page | 17
RESULT: OUTPUT
Enter the values of a,b,c
3
9
6
b is the largest number.
Page | 18
Flow chat
Even or odd using IF ELSE statement
START
STOP
INPUT THE
NUMBER
IS
num%2=0 PRINT NUMBER
IS EVEN
PRINT NUMBER
is odd
YES
NO
Page | 19
PROGRAM:‐ 3 EVEN OR ODD USING IF ELSE STATEMENT
DATE:‐
AIM:
To write a C program to find even or odd using If Else statement.
ALGORITHM:
1) Start.
2) Input the number.
3) If num%2=0 is true.
Print the number is even else go to step‐4.
4) If num%2=0 is false.
Print the number is odd, go to step 5.
5) Finished.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num;
clrscr();
printf("Enter the number\n");
scanf("%d",&num);
if((num%2)==0)
{
printf("%d is an even number\n");
}
else
{
printf("%d is an odd number\n");
}
getch();
}
RESULT: OUTPUT
Enter the number 6 6 is an even number.
Page | 20
Flow chart
Whether a number is prime or not.
START
STOP
INPUT THE NUM
IS
NUM<=1
IS
Prime =0 ?
IS
num%J=0
PRINT “NUMBER
IS NON PRIME”
PRINT NUMBER
IS PRIME
PRINT NUMBER
IS NOT PRIME
YES
NO
PRIME = 0
For j=2; j<= 2; j++
PRIME = 1
Page | 21
PROGRAM:‐ 4 EVEN OR ODD USING IF ELSE STATEMENT
DATE:‐
AIM:
To write a C program to find even or odd using If Else statement.
ALGORITHM:
1) Start.
2) Accept the valves of num.
read num.
3) Check the condition for num.
If(num<=1)
Num is not a prime number.
Exit.
4) Process
Prime = 0
For (j=2; j<= 2; j++)
5) Check the condition.
If(num%j)==0
then prime = 1
6) Check the condition.
If(prime == 0)
Print num is a prime number.
Else
Print num is not a prime number.
7) Finished.
Page | 22
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,i,prime;
clrscr();
printf("Enter an integer\n");
scanf("%d",&num);
if(num<=0)
{
printf("\n%d is a non prime number",num);
getch();
exit();
}
prime=0;
for(i=2;i<num/2;i++)
{
if((num%i)==0)
{
prime=1;
break;
}
}
if(prime==0)
printf("\n%d is a prime number",num);
else
printf("\n%d is not a prime number",num);
getch();
}
Page | 23
RESULT: OUTPUT
Enter an integer
7
7 is a prime number
Enter an integer
2
2 is not a prime number.
Page | 24
Flow chart
Sum of digits of a given number.
START
STOP
INPUT THE NUMBERS
IS
num > 0
PRINT SUM
OF THE DIGITS
YES NO
X = NUM
S = NUM %10
P+=S
NUM = NUM/10
Page | 25
PROGRAM:‐ 5 SUM OF THE DIGITS OF THE GIVEN NUMBER
DATE:‐
AIM:
To write a C program to find the sum of the digits of the given number.
ALGORITHM:
1) Start.
2) Input the number.
3) Calculating the sum of digits using while loop.
s=num%10
p+=S
num = num/10,goto step‐4
4) Print the sum of the digits.
5) Finished.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,s,x,p=0;
clrscr();
printf("Enter the number\n");
scanf("%d",&num);
x=num;
while(num>0)
{
s=num%10;
p+=s;
num=num/10;
}
printf("The sum of digits of the number %d is %d",x,p);
getch();
}
RESULT: OUTPUT
Enter the number
1268584
The sum of digits of the number 1268584 is 34
Page | 26
Flow chart
Roots of the quadratic equation using switch statements.
START
INPUT THE NUMBERS a,b,c.
IS a! = 0
IS d==0
IS d<0
PRINT equation
is linear
print roots
r1=real+j imag
r2=real – j imag
Print roots r1,r2
YES
NO
d=b*b‐4*a*c
Case : 3 roots are real
r1=(‐b+sqrt(d))/(2*a) r2=(‐b‐sqrt(d))/(2*a)
STOP
IS d>0
Case : 1 roots are imaginary
real=‐b/(2*a) d= ‐d
h=pow (d,0,5) imag=h/(2*a)
STOP
Case : 2 roots are equal r1 = ‐b/(2*a)
STOP
roots r1,r2
STOP
YES
NO
YES
NO
YES
Page | 27
PROGRAM:‐ 6 ROOTS OF THE QUADRATIC EQUATION USING SWITCH STATEMENT
DATE:‐
AIM:
To write a C program to find the roots of the quadratic equation using switch statement.
ALGORITHM:
1) Start.
2) Input the number a,b,c.
3) Check the condition if (a!=0) is true go to step‐4.
Else point equation is linear.
4) Process.
d = b*b ‐ 4*a*c.
5) Check the condition for step‐4.
If(d>0) then go to step‐9.
6) Check the condition for step‐4.
If(d==0) then go to step‐9.
7) Check the condition for step‐4.
If(d>0) then go to step‐10.
8) [process] case 1:‐ when roots are imaginary.
Real =‐b/(2*a)
d=‐d
n=pow(d,0,5)
imag = n/(2*a)
print roots r1, r2
goto step 11
9) [process] case 2:‐ roots are real and equal
r1 = ‐b/(2*a);
print the roots r1,r2,goto step 11.
10) [process]case 3:‐ when roots are real. r1=(‐b+aqrt(d))/(2*a)
r2=(‐b‐sqrt(d))/(2*a)
print the roots r1,r2, goto step 11.
11) Finished.
Page | 28
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,real,imag,r1,r2,n;
int k;
clrscr();
printf("Enter the values of a,b,c\n");
scanf("%f%f%f",&a,&b,&c);
if(a!=0)
{
d=b*b-4*a*c;
if(d<0)
k=1;
if(d==0)
k=2;
if(d>0)
k=3;
switch(k)
{
case 1:
printf("\nRoots are imaginary\n");
real=-b/(2*a);
d=-d;
n=pow(d,0.5);
imag=n/(2*a);
printf("\n r1=%f+j%f",real,imag);
printf("\n r2=%f-j%f",real,imag);
break;
}
}
else
printf("\n Equation is linear");
getch();
}
Page | 29
RESULT: OUTPUT
Enter the values of a,b,c
9
5
1
Roots are imaginary
r1=-0.277778+j0.184257
r2=-0.277778-j0.184257.
Page | 30
Flow chart
Arrange n‐numbers in ascending order using bubble sort technique.
START
STOP
INPUT THE
NUMBERS OF ITEMS
IS
a[i]>=a[i+1]
temp=a[i]
a[i]=a[i+1]
a[i+1]=temp
For i=0; i<n; i++
INPUT THE ITEMS TO SORT
for(i=0;i<n‐j;i++)
for(j=1;j<n;j++)
For (i=0; i<n; i++)
Print a[i]
Page | 31
PROGRAM:‐ 7
ARRANGE N-NUMBERS IN ASCENDING ORDER USING BUBBLE SORT TECHNIQUE
DATE:‐
AIM:
To write a C program to Arrange n-numbers in ascending order using bubble sort
technique.
ALGORITHM:
1) Start.
2) Input the number OF items.
3) Input the items to sort.
4) Repeat the step‐4 for pass, ranging from 1 t n.
5) Repeat the step‐5 for pass, ranging from 1 to n.
if a[i]>=a[i+1] then
temp=a[i]
a[i]=a[i+1]
a[i+1]=temp
6) Repeat for I ranging from 0 to n.
print a[i].
7) Finished.
Page | 32
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,j,temp,a[20];
clrscr();
printf("Enter the number of items");
scanf("%d",&n);
printf("Enter the items to sort\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=1;j<n;j++)
{
for(i=0;i<n-j;i++)
{
if(a[i]>=a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("The sorted items are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
Page | 33
RESULT: OUTPUT
Enter the number of items 10
Enter the items to sort
3
4
5
7
1
2
9
8
10
6
The sorted items are
1
2
3
4
5
6
7
8
9
10
Page | 34
Flow chart Multiplication of two matrices
START
STOP
Input the order of 2
matrices r1,r2,c1,c2
d[i][j]=0
For i=0; i<r1; i++ For j=0; j<c1; j++
Input the 1st matrix
a[i][j]
For i=0; i<r2; i++ For j=0; j<c2; j++
Input the 2nd matrix
b[i][j]
For i=0; i<r1; i++ For j=0; j<c2; j++
For (k=0; k<r1; k++)
d[i][j]=d[i][j]+a[i][k]*b[k][j]
For i=0; i<r1; i++ For j=0; j<c2; j++
Print d[i][j]
Page | 35
PROGRAM:‐ 8 MULTIPLICATION OF TWO MATRICES
DATE:‐
AIM:
To write a C program to find the multiplication of two matrices.
ALGORITHM:
1) Start. 2) Input the rows and column valves (r1,r2,c1,c2) 3) Input 1st matrix valve (a[i][j]) repeat step‐3
Ranging I to r2, ranging j to c1. 4) Input 2nd matrix valve (b[i][j]) repeat step‐4.
Ranging I to r2,ranging j to c2. 5) Repeat step ‘6’, ‘7’. ‘8’ for I to r1 and j to c2. 6) d [i][j]=0 7) repeat step 7 for k to c2.
d [i][j]=d[i][j]+a[i][k]*b[k][j]; 8) repeat step ‘8’ for I to r1 and j to c2.
Print d[i][j].
Page | 36
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int r1,c1,r2,c2,a[20][20],b[20][20],d[20][20],i,j,k;
clrscr();
printf("Enter the row & column values\n");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
printf("Enter the 1st matrix values\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the 2nd matrix values\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("Resultant matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
d[i][j]=0;
for(k=0;k<c2;k++)
{
d[i][j]=d[i][j]+a[i][k]*b[k][j];
}
printf("%d\t",d[i][j]);
}
printf("\n");
}
getch();
}
Page | 37
RESULT: OUTPUT
Enter the row & column values
2 2 2 2
Enter the 1st matrix values
2 2
2 2
Enter the 2nd matrix values
0 0
2 0
Resultant matrix:
4 0
4 0
Page | 38
Flow chart
Addition of two matrices
START
STOP
Input the row and
column (r,c)
Input the 1st matrix
a[i][j]
For i=0; i<r; i++ For j=0; j<c; j++
Input the 2nd matrix
b[i][j]
For i=0; i<r; i++ For j=0; j<c; j++
d[i][j] = a[i][j]+b[i][j]
For i=0; i<r; i++ For j=0; j<c; j++
Print d[i][j]
For i=0; i<r; i++ For j=0; j<c; j++
Page | 39
PROGRAM:‐ 9 ADDITION OF TWO MATRICES
DATE:‐
AIM:
To write a C program to find the addition of two matrices.
ALGORITHM:
1) Start.
2) Input the rows and column valve (r,c)
3) Input the 1st matrix valve.
repeat ‘step 3’ for ‘i to r’ and ‘j to c’.
read a[i][j].
4) Input the 2nd matrix valve.
repeat ‘step 4’ for ‘i to r’ and ‘j to c’.
read b[i][j]
5) Addition matrix
d[i][j]=a[i][j]+b[i][j]
repeat ‘step 5’ for ‘i to r’ and ‘j to c’.
6) Print d[i][j] repeat ‘step 6’ for ‘I to r’ and ‘j to c’.
7) Finished.
Page | 40
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n;
clrscr();
printf("\nEnter the order of the matrix A and B\n");
scanf("%d%d",&m,&n);
printf("\nEnter the elements of first matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the elements of second matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
{
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("sum of matrixes is\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",c[i][j]);
printf("\n");
}
getch();
}
Page | 41
RESULT: OUTPUT
Enter the order of the matrix A and B
2 2
Enter the first matrix
1 5
7 9
Enter the second matrix
3 8
4 6
sum of matrixes is
4 13 11 15
Page | 42
Flow chart
Swap two numbers
START
STOP
Input the valve a,b
swap (a,b)
Print pa, pb
swap (int pa, int pb )
temp = pa
Pa = pb
Pb = temp
Page | 43
PROGRAM:‐10 TO SWAP TWO NUMBERS
DATE:‐
AIM:
To write a C program to swap two numbers using user defined functions.
ALGORITHM:
1) Start.
2) Input the valve of a,b which is to be swapped.
3) Swap (a,b)
4) In function swap (int pa, int pb)
temp = pa;
pa = pb
pb = temp
5) Print the swapped valve (pa, pb)
6) Finished.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int swap(int pa,int pb);
int a,b;
clrscr();
printf("Enter the value of a,b:");
scanf("%d%d",&a,&b);
swap(a,b);
getch();
}
swap(int pa,int pb)
{
int temp;
temp=pa;
pa=pb;
pb=temp;
printf("The values of a & b after swapping: %d\t%d",pa,pb);
return 0;
}
RESULT: OUTPUT
Enter the value of a,b:8 9
The values of a & b after swapping: 9 8
Page | 44
MAT LAB
The name ‘MAT LAB’ stands for matrix laboratory, because 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. In industry the software is used in
research, development and design. The standard MATLAB program has tools that can be used to solve
commands and common problems. In addition MATLAB has optional tool boxes that are a collection of
specialized programs designed to solve specific types of problems.
MAT LAB window.
1.) Command window
Main window, enters variables, runs programs.
2.) Figure window
Contains output from graphic commands (graphs).
3.) Editor window
Creates and delays script and functions files.
4.) Help window
Provides help information.
5.) Launch pad window
Provides access to tool demos and documentation.
6.) Command history window
Logs commands entered in the commands window.
7.) Workspace window
Provides information about the variables that are used.
8.) Current directory window
Snows the files in current directory.
Working in the command window
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) Several commands can be typed in the same line this is done by typing a comma between the
commands. When the enter key is pressed the commands are executed in order from left to right.
4) It is not possible to go back to same line in the command window to make a correction and re‐
execute.
5) A previously typed command can be recalled to the command prompt with the up arrow key (↑)
6) 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 ellipse).
7) If a semicolon (;) is typed at the end of a command, the output of a command is not displayed.
8) When the symbol (%) is typed in the beginning of a line, the line is designed as a comment.
Rules about variable names
1) Can contain letters, digits and the underscore character.
2) Must begin with a letter.
3) MATLAB is a case sensitive, is distinguishes b/w uppercase and lowercase letters.
4) Avoid using the names of a built in function for a variable.
Page | 45
CREATING A ONE DIMENSIONAL ARRAY
1) Creating a vector form a known list of numbers variables name [type vector elements]
Eg: ‐ yr = [ 1984 1986 1988 1990 1992 1994 1996 ]
Pop = [ 127 ; 130 ; 136 ; 145 ; 158 ; 178 ; 211 ]
2) Creating a vector with constant spacing by specifying the first term, the spacing and the last term.
Variable_name = [m:q:n]
m →first element
q →spacing
n →last element
eg :‐ x=[1:2:13]
x=[1 3 5 7 9 11 13]
3) Creating a vector with constant spacing by specifying the first and last term and the number of
terms.
Variable_name=linespace (xi,xf,h)
Xi →first element
Xf →last element
H →number of elements
CREATING A TWO DIMENSIONAL ARRAY
Variable_name=[1st row elements; 2nd row elements;…………………………; last row elements]
Ex :‐ a = [5 35 43; 4 76 81; 21 32 40]
SCRIPT FILES
1) A script file is a sequence of matlab commands also called a program.
2) When a script file has a command that generates an output, the output is displayed in the
command window.
3) Using a script is convenient because it can be edited and executed many more times.
4) Script files can be typed and edited in any text editor and then pasted into the MAT‐LAB editor.
5) Script files are also called M‐files because the extension .m is used when they are saved.
STEPS TO CREATE AND TO RUN SCRIPT FILES
1) In the file menu select new and then select m‐file once the window is open the commands of
the script file are typed line by line.
2) The file is saved by choosing save as from the file menu selecting a location and entering a name
for the file.
3) A script file can be executed either by typing its name in the command window and then
pressing the enter key or directly from the editor window by clicking on the run icon.
INPUT TO A SCRIPT FILE
1) The variable is defined and assigned valve in the script file.
Page | 46
2) The variable is defined and assigned valve in the command window.
3) The variable is defined in the script file, but specific valve is entered in the command window
when script file is executed
FUNCTION FILES
A user‐defined function is a MATLAB program that is created by the user saved as a function file and
then can be used like a built‐in function.
Structure of a function file
1) Function definition line
2) The h1 line
3) Help text
4) Function body
5) Assignments of valves to output arguments
→Function definition line
The first executed line in a function file must be the function definition line.
→the H1 line and help‐text
The H1 lines and help text lines are comment lines following the function definition line. They
are optional, but frequently used to provide information about the function.
→Function body
The function body contains the computer program (code) that actually performs the
computations the code can use all mat‐lab programming features. This includes calculations,
assignments, comments, blank lines and interactive input and output.
COMPARISION BETWEEN SCRIPT FILES AND FUNCTION FILES
The similarities and differences between script and function files are:‐
1) Both script and function files are saved with the extension .m
2) The first line in a function file is the function definition line.
3) The variables in a function file are local, the variable in a script file are recognized in the
command window.
4) Script files use variables that have been defined in the workspace.
5) Script files contain a sequence of MAT‐LAB commands.
6) Function files can accept data through input arrangement and can return data through output
arguments.
7) When a function file is saved the name of the file should be the same as the name of the
function.
Page | 47
CHARACTERS, COMMANDS AND FUNCTIONS OF MATLAB
Characters and arithmetic operations
Characters Description
+ Addition
‐ Subtraction
* Scalar and array multiplication
/ Right division
\ Left division
.* Element by element multiplication of scalar and array.
./ Element by element right division
.\ Element by element left division
^ Exponentiation.
.^ Element by element exponentiation.
: Colon, creates equally spaced elements, range in array.
= Assignment operator.
() Parenthesis, encloses output arguments.
[] Brackets, encloses output arguments.
, Comma, separates arrays, comma.
; Semicolon, ends row in array.
‘ Single quote, creates string.
…. Ellipses, continuation of line.
% Percent, denote a comment, specifies output format.
Page | 48
MANAGING COMMANDS
Command Description
1 cd Changes current directory.
2 clc Clear the command window.
3 clear Removes all variability’s from memory.
4 clear x,y,z Removes variables x,y,z from memory.
PREDIFNED VARIABLES
Variable Description
1 ans Valve of last expression.
2 naw Not a number.
3 Pi The number pi (π).
ELEMENTRY MATH FUNCTIONS
1 sqrt Square root.
TRIGNOMETRIC MATH FUNCTIONS
1 sin Sine.
2 cos Cosine.
3 tan Tangent.
4 cot Cotangent.
5 asinc Inverse sine.
6 acos Inverse cosine.
7 atan Inverse tangent.
8 acot Inverse cotangent.
CREATING ARRAYS
Function Description
1 Linespace Creates equally spaced vector.
ARRAYS FUNCTIONS
Function Description
1 Mean Calculates mean valve.
INPUT AND OUTPUT
Command Description
1 disp Display output.
2 fprintf Displays and saves output.
3 input Prompts for user input.
TWO DIMENSINAL PLOTTING
Command Description
1 plot Creates a plot.
FORMATTING PLOTS
Command Description
1 grid Adds grip to a plot.
2 legend Adds legend to a plot.
3 subplot Creates multiple plots on one page.
4 text Adds text to a plot.
5 tittle Adds tittle to a plot.
6 X label Adds x label to x‐axis.
7 Y label Adds y label to y‐axis.
Page | 49
FLOW CONTROL COMMANDS
Command Description
1 break Terminates execution of the loop.
2 continue Terminates a pass in loop.
3 else Conditionally executes a command.
4 elseif Conditionally executes a command.
5 end Terminates conditional statements & loop.
6 for Repeats execution of group of commands.
7 if Conditionally executes a command.
8 switch Switches among several cases based on exp.
9 while Repeats execution of group of commands.
POLYNOMINAL FUNCTION
Function Description
1 conv Multiples polynomial.
2 roots Determines roots of polynomial.
3 polyfit Curve fit polynomial to set to points.
Page | 50
PROBLEM‐1
1. A trigonometric identity is given by cos2 ( 2) = .. verify that the identity is correct by
calculating each side of the equation substituting 5
Program:
x=pi/5; ‐define x.
lhs=cos(x/2)^2 ‐calculate the lhs.
rhs=(tan(x)+sin(x))/(2*tan(x)) ‐calculate the rhs.
Page | 51
Problem‐2
2. Three forces are applied to a bracket as shown. Determine the total (equivalent) force applied to the
bracket
Program:
F1=400;F2=500;F3=700; ‐define variables with magnitude of each vector.
Th1=340*pi/180;Th2=30*pi/180;Th3=143*pi/180 ‐define variables with angle of each vector.
Fx=F1*cos(Th1)+F2*cos(Th2)+F3*cos(Th3) ‐calculate the magnitude of each vector.
Fy=F1*sin(Th1)+F2*sin(Th2)+F3*sin(Th3) ‐ calculate the magnitude of each vector.
F=sqrt(Fx^2+Fy^2) ‐calculate the total force.
Th=(180/pi)*atan(Fy/Fx) ‐calculate the angle of the total force vector.
Page | 52
Problem‐3
3. The co‐efficient of friction mu (µ) 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 co‐efficient of friction can be
calculated by mu=f/mg (g=9.81m/s2). Result from measuring ‘F’ in six test are given in the table.
Determine the co‐efficient of friction in each test and average from all test.
TEST NO 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
Program:
m=[1 4 5 10 20 50]; ‐enter the values of m vector.
f=[12.5 23.5 30 61 117 294]; ‐enter the values of f vector.
mu=f./(m*9.81) ‐a value for mu is calculated for each test, using element by element
calculation
avg=mean(mu) ‐the average of the elements in the mu is determined by using the
function mean.
Page | 53
Problem‐4
4. A cylindrical silo with radius ‘r’ has a spherical cap roof with radius ‘R’. The height of the cylindrical
position is ‘H’. Write a program in a script file that determines the height ‘H’ for given values of r, R and
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=30m, R=45m and volume of 120000 cubic meter
(m3) assign the valves for r,Rand V in in the command window.
Program:
r=30;R=45;V=120000;
clc;
Th=asin(r/R); ‐calculating theta
h=R‐R*cos(Th); ‐calculating h
Vcap=(1/3)*pi*(h^2)*(3*R‐h); ‐calculating the volume of cap
H=(V‐Vcap)/(pi*(r^2)); ‐calculating h
S=((2*pi*r*H)+(2*pi*r*h)); ‐calculating the surface area of silo
fprintf(‘the height H is:%f’,H)
fprintf(‘\n the surface area the Silo is:%f’,S)
Page | 54
Problem‐5
5.Create a function file that calculates that trajectory of a projectile. The inputs to the function are the
initial velocity and the angle at which the projectile is fired. The outputs from the function are the
maximum height and distance. In addition, Hx function generates a plot of trajectory, wse the function
to calculate the trajectory of a projectile that is fired at a velocity of 230m/sec at an angle of 390
Program:
Function [hmax,dmax]=trajectory(VO,Th) ‐function definition line
%trajectory calculates the max height & distance of a projectile
%make a plot of the trajectory
%input argumants are:
%Vo:initial velocity in (m/s).
%Th:angle in degrees.
%output argument are:
%hmax:maximum height in (m)
%dmax:maximum distance in(m)
%the function creates also a plot of the trajectory.
g=9.81;
Vox=VO*cos(theta*pi/180);
Voy=VO*sin(theta*pi/180)
Thmax=VOy/g;
hmax=VOy^2/(2*g);
ttot=2*Thmax;
dmax=VOx*ttot;
%creating a trajectory plot
tplot=linespace(0,ttot,200); ‐creating a time vector with 200
elements
X=VOx*tplot;
Y=VOy*tplot‐0.5*g*tplot^2; ‐note the element by element
multiplication
plot(X,y)
xlabel(‘DISTANCE(m)’)
ylabel(‘HEIGHT(m)’)
title(‘PROJECTILE”S TRAJECTORY’)
Page | 55
Program 7
The flight of a model rocket can be modelled as follows. During the first 0.15 seconds the rocket is
propelled up by the rocket engine with a force of gravity after it reaches apex the rocket starts to fall
back down when its down velocity reaches 20m/s a parachute opens(assumed to open instantly) and
the rocket continues to move down at a constant speed of 20m/s until it hits the ground while a
program that calculates and plots the speed and altitude of the rocket as a function of time during the
flight.
PROGRAM:
M=0.05;g=9.81;tEngine=0.15;Force=16;vchute=‐20;Dt=0.01;
Clear t v h
n=1;
t(n)=0;v(n)=0;h(n)=0;
%segment 1
a1=(Force‐m*g)/m;
While t(n)<tEngine * n<50000
n=n+1;
t(n)=t(n‐1)+Dt;
v(n)=a1*t(n);
h(n)=0.5*a1*t(n)^2;
end
v1=v(n);h1=h(n);t1=t(n);
%segment 2
while v(n)>=vchute & n<50000
n=n+1;
t(n)=t(n‐1)+Dt;
v(n)=v1‐g*(t(n)‐t1);
h(n)=h1+v1*(t(n)‐t1)‐0.5*g*(t(n)‐t1)^2;
end
v2=v(n);h2=h(n);t2=t(n);
%segment 3
while h(n)>0 & n<50000
n=n+1;
t(n)=t(n‐1)+Dt;
v(n)=vchute;
h(n)=h2+vchute*(t(n)‐t2);
end
subplot(1,2,1)
plot(t,h,t2,h2,’o’)
subplot(1,2,2)
plot(t,v,t2,v2,’o’)
Page | 56
Program 8
The outside dimensions of a rectangular box(top open) made of aluminium are 24 x 12 x 4 inches. The
wall thickness of the bottom and the side is x, derive an expression that relates the weight of the box &
the wall thickness x. Determine the thickness x for the box that weighs 15 lbs. The specific weight of
aluminium is 0.101 Lt/cubic inch.
PROGRAM:
W=15;gama=0.101; ‐ Assign w & gama.
VAlum=W/gma; ‐ Calculate the polynomial 24 – 2x to a.
a=[‐2 24]; ‐ Assign the polynomial 24‐2x to a.
b=[‐2 12]; ‐ Assign the polynomial 12‐2x to b.
c=[‐1 4]; ‐ Assign the polynomial 4‐x to c.
Vin=conv(c,conv(a,b)); ‐ Multiply the three polynomials above.
polyeq=[0 0 0 (VAlum‐24*12*4)]+Vin ‐ AddVal‐24*12*4 to Vin.
x=roots(polyeq) ‐ Determine the roots of the polynomial
Page | 57
Program 9
Viscosity mu(μ) is properly 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.
Temperature °C ‐20 0 20 40 60 80 100 120
Mu(N‐s/m)² 4.0 0.38 0.095 0.032 0.0150 0.0078 0.0045 0.0032
PROGRAM:
T=[‐20:20:120];
mu=[4 0.38 0.095 0.032 0.015 0.0078 0.0045 0.0032];
TK=T+273;
p=polyfit(TK,log(mu),2)
Tplot=273+[‐20:120];
muplot=exp(p(1)*Tplot.^2+p(3));
semilogy(TK,mu,’o’,Tplot,muplot)
Page | 58
Program 10
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 & the velocity v &
the displacement x of the front edge of the bumper according to the equation
F=kv³(x+1)³
where k=30 kg/m^5 is a constant.
A car with ,ass m of 1500 Kg hits the bumper at a speed of 90 Km/h. Determine & plot the velocity of the
car as a function of its position for 0 ≤ x ≤ 3m.
PROGRAM:
BUMPER FILE ‐ save
function dvdx=bumper(x,v)
global k m
dvdx=‐(k*v^2*(x+1)^3)/m;
CAR FILE – save and run
global k m
k=30;m=1500:v0=90;
xspan=[0:0.23:3];
v0mps=v0*1000*3600;
[x v]=ode45(‘bumper’,xspan,v0mps)
plot(x,v)
xlabel(‘x(m)’ylable(‘velocity(m/s)’)